Android碎片中的Recycle View显示“未连接适配器;跳过布局”

3

如果我在一个继承自AppCompatActivity的类中编写这段代码,它可以运行。但是在fragment类中,我不知道为什么它不能正常工作。在包含此fragment的activity中,我使用另一个适配器来显示具有相同代码的产品,并且它可以工作。

public class Categroy extends  Fragment{

    // CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
    public static final int CONNECTION_TIMEOUT = 10000;
    public static final int READ_TIMEOUT = 15000;
    public RecyclerView mRVcategoryList;
    public AdapterCategory mAdapter;
    private String myurl="http://10.0.3.2/mobilaApp/category.php";
    // private String categoryurl="http://10.0.3.2/mobilaApp/category.php";



    public LinearLayoutManager layoutManager;
    List<DataCategory> data=new ArrayList<>();
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // execute asyncLogin
        new AsyncLogin().execute();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                  Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_categroy, container,     false);
        RecyclerView recyclerView = (RecyclerView)   rootView.findViewById(R.id.rvcat);
        // 2. set layoutManger
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        // 3. create an adapter
        AdapterCategory mAdapter = new          AdapterCategory(getActivity().getApplicationContext(), data);
        // 4. set adapter
        recyclerView.setAdapter(mAdapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        return rootView;
        }
    private class AsyncLogin extends AsyncTask<String, String, String> {
        ProgressDialog pdLoading = new ProgressDialog(getActivity());
        HttpURLConnection conn;
        URL url = null;
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //this method will be running on UI thread
            pdLoading.setMessage("\tLoading...");
            pdLoading.setCancelable(false);
            pdLoading.show();
        }
        @Override
        protected String doInBackground(String... params) {
            try {

                // Enter URL address where your json file resides
                // Even you can make call to php file which returns json data
                url = new URL(myurl);
                // urlcat = new URL(categoryurl);

            } catch (MalformedURLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                return e.toString();
            }
            try {

                // Setup HttpURLConnection class to send and receive data from php and mysql
                conn = (HttpURLConnection) url.openConnection();
                conn.setReadTimeout(READ_TIMEOUT);
                conn.setConnectTimeout(CONNECTION_TIMEOUT);
                conn.setRequestMethod("GET");

                // setDoOutput to true as we recieve data from json file
                conn.setDoOutput(true);

            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return e1.toString();
            }

            try {

                int response_code = conn.getResponseCode();

                // Check if successful connection made
                if (response_code == HttpURLConnection.HTTP_OK) {

                    // Read data sent from server
                    InputStream input = conn.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(input));
                    StringBuilder result = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        result.append(line);
                    }

                    // Pass data to onPostExecute method
                    return (result.toString());

                } else {

                    return ("unsuccessful");
                }

            } catch (IOException e) {
                e.printStackTrace();
                return e.toString();
            } finally {
                conn.disconnect();
            }
        }
        @Override
        protected void onPostExecute(String result) {

            //this method will be running on UI thread

            // dississ dialog   pdLoading.dismiss();

            pdLoading.dismiss();
            try {

                JSONArray jArray = new JSONArray(result);

                // Extract data from json and store into ArrayList as class objects
                for(int i=0;i<jArray.length();i++){
                    JSONObject json_data = jArray.getJSONObject(i);
                    DataCategory categorydata = new DataCategory();

                    categorydata.name_cat= json_data.getString("name_cat");


                    data.add(categorydata);
                }



                mRVcategoryList = (RecyclerView)getActivity(). findViewById(R.id.rvcat);
                mAdapter = new AdapterCategory(getActivity().getApplicationContext(), data);
                mRVcategoryList.setAdapter(mAdapter);
                mRVcategoryList.setLayoutManager(new LinearLayoutManager(getActivity().getApplicationContext()));

            } catch (JSONException e) {
                Toast.makeText(getActivity().getApplicationContext(), e.toString(), Toast.LENGTH_LONG).show();
            }

        }

    }
}
     /* if i write this code in a class extends AppCompatActivity it
        works but in a fragment class i don't know why it doesn't work .
        in the activity that has this fragment i use another adapter
        to show products with the same code and it works 
       */
  Adapter is here
                    public AdapterCategory(Context context, List<DataCategory> data){
    this.context=context;
    inflater= LayoutInflater.from(context);
    this.data=data;
  }

// Inflate the layout when viewholder created
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    View view=inflater.inflate(R.layout.categoryrow, parent,false);
    MyHolder holder=new MyHolder(view);
    return holder;
}

// Bind data
@Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

    // Get current position of item in recyclerview to bind data and assign values from list
    MyHolder myHolder= (MyHolder) holder;
    DataCategory current=data.get(position);
    myHolder.namecat.setText(current.name_cat);




}

// return total item from List
@Override
public int getItemCount() {
    return data.size();
}


class MyHolder extends RecyclerView.ViewHolder{

    TextView namecat;





    // TextView textPrice;

    // create constructor to get widget reference
    public MyHolder(View itemView) {
        super(itemView);
        namecat= (TextView) itemView.findViewById(R.id.category_name);


    }

}

}


使用Android Volley。 - Abhinav singh
展示你的适配器类代码。 - Jas
在Android开发中,Fragment的onCreate方法是在布局被创建之前执行的。因此,“mRVcategoryList =(RecyclerView)getActivity()。findViewById(R.id.rvcat);”可能会为空值。 - Serg
适配器已更新。 - bob
哪个 RecyclerView 抛出了异常? - faranjit
2个回答

1
使用getContext()而不是getActivity()将layoutManager设置为您的recyclerView,它就会起作用。
mListLayoutManager=new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(mListLayoutManager);

08-05 10:22:06.462 3069-3069/? E/RecyclerView: 没有附加适配器; 跳过布局 - bob

1
感谢大家。问题是在onPostExecute中将getActivity()替换为getView()。
 mRVFishPrice = (RecyclerView)getView().findViewById(R.id.fishPriceList);
 mAdapter = new AdapterFish(getActivity(), data);
 mRVFishPrice.setAdapter(mAdapter);
 mRVFishPrice.setLayoutManager(new LinearLayoutManager(getActivity()));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接