Адаптер не подключен, не уверен, где возникает эта проблема

#java #android

Вопрос:

Я пытаюсь получить данные JSONObject в адаптер RecyclerView, но выводит ошибку в классе адаптера и показывает, что адаптер не подключен. Две ошибки: **Адаптер не подключен **Не найден идентификатор пакета 07 для идентификатора 0x073d0cd9

JSONObject

 onResponse:{"country":"USA","timeline":{"3/19/21":118313818,"3/20/21":121441497,"3/21/21":124481412,"3/22/21":126509736,"3/23/21":128217029,"3/24/21":130473853,"3/25/21":133305295,"3/26/21":136684688,"3/27/21":140180735,"3/28/21":143462691,"3/29/21":145812835,"3/30/21":147602345,"3/31/21":150273292,"4/1/21":153631404,"4/2/21":157606463,"4/3/21":161688422,"4/4/21":165053746,"4/5/21":167187795,"4/6/21":168592075,"4/7/21":171476655,"4/8/21":174879716,"4/9/21":178837781,"4/10/21":183467709,"4/11/21":187047131,"4/12/21":189692045,"4/13/21":192282781,"4/14/21":194791836,"4/15/21":198317040,"4/16/21":202282923,"4/17/21":202282923}}
 

Ошибка: **Не зная, где я допустил ошибку, я дважды проверяю прикрепленный макет.

 E/RecyclerView: No adapter attached; skipping layout
D/FirebaseAuth: Notifying id token listeners about a sign-out event.
    Notifying auth state listeners about a sign-out event.
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@73265c8
D/EGL_emulation: eglMakeCurrent: 0xe5c528c0: ver 3 1 (tinfo 0xe663e800)
D/EGL_emulation: eglMakeCurrent: 0xe5c528c0: ver 3 1 (tinfo 0xe663e800)
D/EGL_emulation: eglMakeCurrent: 0xe5c528c0: ver 3 1 (tinfo 0xe663e800)
D/EGL_emulation: eglMakeCurrent: 0xe5c528c0: ver 3 1 (tinfo 0xe663e800)
E/VaccinationTotalUSA: onResponse:{"country":"USA","timeline":{"3/20/21":121441497,"3/21/21":124481412,"3/22/21":126509736,"3/23/21":128217029,"3/24/21":130473853,"3/25/21":133305295,"3/26/21":136684688,"3/27/21":140180735,"3/28/21":143462691,"3/29/21":145812835,"3/30/21":147602345,"3/31/21":150273292,"4/1/21":153631404,"4/2/21":157606463,"4/3/21":161688422,"4/4/21":165053746,"4/5/21":167187795,"4/6/21":168592075,"4/7/21":171476655,"4/8/21":174879716,"4/9/21":178837781,"4/10/21":183467709,"4/11/21":187047131,"4/12/21":189692045,"4/13/21":192282781,"4/14/21":194791836,"4/15/21":198317040,"4/16/21":202282923,"4/17/21":205871913,"4/18/21":205871913}}
E/.senior_projec: No package ID 07 found for ID 0x073d0cd9.
D/AndroidRuntime: Shutting down VM
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.programming_concept.senior_project, PID: 7781
    android.content.res.Resources$NotFoundException: String resource ID #0x73d0cd9
        at android.content.res.Resources.getText(Resources.java:348)
        at android.widget.TextView.setText(TextView.java:5831)
        at com.programming_concept.senior_project.VaccinationAdapter.onBindViewHolder(VaccinationAdapter.java:37)
        at com.programming_concept.senior_project.VaccinationAdapter.onBindViewHolder(VaccinationAdapter.java:14)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at androidx.recyclerview.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:2303)
        at androidx.recyclerview.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1627)
        at androidx.recyclerview.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1587)
        at androidx.recyclerview.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:665)
        at androidx.recyclerview.widget.RecyclerView.dispatchLayoutStep2(RecyclerView.java:4134)
        at androidx.recyclerview.widget.RecyclerView.onMeasure(RecyclerView.java:3540)
        at android.view.View.measure(View.java:23169)
        at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:715)
        at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:461)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
        at android.view.View.measure(View.java:23169)
        at androidx.drawerlayout.widget.DrawerLayout.onMeasure(DrawerLayout.java:1156)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at androidx.appcompat.widget.ContentFrameLayout.onMeasure(ContentFrameLayout.java:146)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1535)
        at android.widget.LinearLayout.measureVertical(LinearLayout.java:825)
        at android.widget.LinearLayout.onMeasure(LinearLayout.java:704)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:6749)
        at android.widget.FrameLayout.onMeasure(FrameLayout.java:185)
        at com.android.internal.policy.DecorView.onMeasure(DecorView.java:716)
        at android.view.View.measure(View.java:23169)
        at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2718)
E/AndroidRuntime:     at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1572)
        at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1855)
        at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1460)
        at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:7183)
        at android.view.Choreographer$CallbackRecord.run(Choreographer.java:949)
        at android.view.Choreographer.doCallbacks(Choreographer.java:761)
        at android.view.Choreographer.doFrame(Choreographer.java:696)
        at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:935)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

 

Класс Java выдает мне эту ошибку:

 public class VaccinationAdapter extends RecyclerView.Adapter<VaccinationAdapter.ViewHolder> {

    ArrayList<VaccinationTimeline> recentRecords;

    public VaccinationAdapter(ArrayList<VaccinationTimeline> recentRecords) {
        this.recentRecords = recentRecords;
    }



    @NonNull
    @Override
    public VaccinationAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_vaccination_record,
                parent, false);

        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull VaccinationAdapter.ViewHolder holder, int position) {
        VaccinationTimeline recentRecord = recentRecords.get(position);
        holder.tvTimeline.setText(recentRecord.getmDate());
        holder.tvCount.setText(recentRecord.getmCount());
    }

    @Override
    public int getItemCount() {
        return recentRecords.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder {
        TextView tvTimeline;
        TextView tvCount;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            tvTimeline = itemView.findViewById(R.id.tvTimeline);
            tvCount = itemView.findViewById(R.id.tvCount);
        }
    }
}
 

xml:

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black">



    <androidx.recyclerview.widget.RecyclerView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@ id/vaccinationRecord"
        tools:listitem="@layout/item_list_vaccination_record"
        />

    <ProgressBar
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@ id/progress_circular_vaccination"
        android:indeterminateDrawable="@drawable/progress"
        android:indeterminate="true"
        android:layout_centerInParent="true"
        />


</RelativeLayout>



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="8dp"
    >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal">



        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@ id/tvTimeline"
            android:text="mm/dd/yyyy:"
            android:textColor="@color/colorTotalConfirmed"
            android:textSize="20sp"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@ id/tvCount"
            android:text="100000"
            android:textColor="@color/colorTotalConfirmed"
            android:textSize="20sp"
            />



    </LinearLayout>

</RelativeLayout>
 

Более подробно(класс фрагментов):
Не уверен, есть ли ошибка в этом классе или классе адаптера.

 public class VaccinationTotalUSA extends Fragment {

    RecyclerView rvRecentRecord;
    ProgressBar progressBar;

    private static final String TAG = VaccinationTotalUSA.class.getSimpleName();

    ArrayList<VaccinationTimeline> recentRecords;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_vaccination, container, false);


        // call view
        rvRecentRecord = view.findViewById(R.id.vaccinationRecord);
        progressBar = view.findViewById(R.id.progress_circular_vaccination);
        rvRecentRecord.setLayoutManager(new LinearLayoutManager(getActivity()));

        // Volley Fetch
        getDataFromServer();

        return view;
    }

    private void showRecyclerView() {
        VaccinationAdapter vaccinationAdapter = new VaccinationAdapter(recentRecords);
        rvRecentRecord.setAdapter(vaccinationAdapter);
    }

    private void getDataFromServer() {
        String url = "https://disease.sh/v3/covid-19/vaccine/coverage/countries/USA";

        recentRecords = new ArrayList<>();

        StringRequest stringRequest = new StringRequest(Request.Method.GET, url, new Response.Listener<String>() {

            @Override
            public void onResponse(String response) {

                progressBar.setVisibility(View.GONE);

                if (response != null) {
                    Log.e(TAG, "onResponse:"   response);
                    try {
                        
                        JSONObject jsonObject = new JSONObject(response);
                        JSONObject subObject = jsonObject.getJSONObject("timeline");

                        JSONArray keys = subObject.names();



                        for (int i = 0; i < keys.length(); i  ) {

                            String key = keys.getString(i);
                            int value = subObject.getInt(key);

                            recentRecords.add(new VaccinationTimeline(key, value));

                        }

                        showRecyclerView();
                    }catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressBar.setVisibility(View.GONE);
                        Log.e(TAG, "onResponse"   error);
                    }
                });
        Volley.newRequestQueue(getActivity()).add(stringRequest);
    }
}
 

Ответ №1:

Вы получаете сообщение «Адаптер не подключен», потому что вы устанавливаете адаптер с помощью асинхронного обратного вызова. К тому времени, когда обратный вызов вернется, Android уже завершил свой проход по макету, увидел, что RecyclerView еще не настроен, и уже решил пропустить его.

Вместо этого вы должны установить свой адаптер непосредственно внутри onCreateView и обновить его с помощью обратного вызова.

Добавьте метод обновления в свой адаптер:

 // Update your Adapter's member variable to instantiate a new ArrayList.
// (This will let the Layout Manager know that there are 0 items in the adapter
// initially. This way the layout can still be drawn without error before we add the
// items from our response callback.)
ArrayList<VaccinationTimeline> recentRecords = new ArrayList<>();

// Update your constructor to receive no parameters
// since the items will be updated later.
public VaccinationAdapter() {}

// ...

// Create a method to update your Adapter's items
public void updateRecords(ArrayList<VaccinationTimeline> recentRecords) {
    this.recentRecords = recentRecords;
    notifyDataSetChanged(); // Notify the Adapter that the item data has changed
}
 

Установите адаптер в свой onCreateView :

 // Create a member variable for your Adapter
VaccinationAdapter vaccinationAdapter;

@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_vaccination, container, false);


    // call view
    rvRecentRecord = view.findViewById(R.id.vaccinationRecord);
    progressBar = view.findViewById(R.id.progress_circular_vaccination);
    rvRecentRecord.setLayoutManager(new LinearLayoutManager(getActivity()));
    
    // Set your Adapter
    vaccinationAdapter = new VaccinationAdapter();
    rvRecentRecord.setAdapter(vaccinationAdapter);

    // Volley Fetch
    getDataFromServer();

    return view;
}
 

Обновите адаптер с помощью обратного вызова:

 @Override
public void onResponse(String response) {
    
    progressBar.setVisibility(View.GONE);
    
    if (response != null) {
        Log.e(TAG, "onResponse:"   response);
        
        try {
            JSONObject jsonObject = new JSONObject(response);
            JSONObject subObject = jsonObject.getJSONObject("timeline");
            
            JSONArray keys = subObject.names();
            
            // Collect the new values from the callback
            ArrayList<VaccinationTimeline> newRecords = new ArrayList<>():
            
            for (int i = 0; i < keys.length(); i  ) {
                String key = keys.getString(i);
                int value = subObject.getInt(key);
                
                newRecords.add(new VaccinationTimeline(key, value));
            }
            
            // Update the adapter with the new values
            vaccinationAdapter.updateRecords(newRecords);
            
        }catch (JSONException e) {
            e.printStackTrace();
        }
    }
}
 

Комментарии:

1. Спасибо. Я отмечу это, действительно полезно.

Ответ №2:

**Идентификатор пакета 07 не найден для идентификатора 0x073d0cd9 Эта проблема устранена.

Я пытаюсь установить целое число с помощью setText(),

Оригинал:

 holder.tvCount.setText(recentRecord.getmCount());
 

Исправлено:

 holder.tvCount.setText(String.valueof(recentRecord.getmCount());
 

По-прежнему нет проблем с подключением адаптера. Кто-нибудь знаком с этим?
Я дважды проверяю свой файл макета и убеждаюсь, что вложил правильный xml. Может быть, я что-то упускаю?