2016-08-05 85 views
3

如果我在一个类中编写此代码扩展AppCompatActivity它 工作,但在片段类中,我不知道它为什么不起作用。 具有此片段我用另一个适配器 显示产品代码相同的活动,它的工作原理Android回收查看里面的片段显示“没有适配器连接;跳过布局”

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


    } 

} 

}

+0

采用Android抽射。 – Destro

+0

显示适配器类的代码 – Jas

+0

片段'onCreate'方法在创建布局之前运行https://developer.android.com/reference/android/app/Fragment.html#onCreate(android.os.Bundle)。所以'mRVcategoryList =(RecyclerView)getActivity()。 findViewById(R.id.rvcat);”可能评估为空 – Serg

回答

1

设置的layoutManager使用的getContext(您recyclerView),而不是getActivity()和它会工作。

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

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

1

谢谢大家 的问题是,以取代getActivity()由getView()onpostexecute

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

谢谢你,你是我的时间! – inthy

相关问题