Android循环视图里面的片段显示"没有附加适配器;跳过布局"

时间:2016-08-05 09:25:24

标签: android android-fragments

如果我在类中编写此代码扩展AppCompatActivity它     虽然工作但是在一个片段课程中,我不知道为什么它不起作用。     在具有此片段的活动中,我使用另一个适配器     显示具有相同代码的产品并且可以正常工作

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);


    }

}

}

2 个答案:

答案 0 :(得分:1)

使用getContext()而不是getActivity()将layoutManager设置为recyclerView,它将起作用。

mListLayoutManager=new LinearLayoutManager(getContext());
    recyclerView.setLayoutManager(mListLayoutManager);

答案 1 :(得分:1)

谢谢大家 问题是用getView()onpostexecute取代getActivity()

 mRVFishPrice = (RecyclerView)getView().findViewById(R.id.fishPriceList);
 mAdapter = new AdapterFish(getActivity(), data);
 mRVFishPrice.setAdapter(mAdapter);
 mRVFishPrice.setLayoutManager(new LinearLayoutManager(getActivity()));