2016-08-05 7 views
3

Wenn ich diesen Code in einer Klasse schreibe erweitert AppCompatActivity es funktioniert aber in einer Fragmentklasse Ich weiß nicht, warum es nicht funktioniert. in der Aktivität, die dieses Fragment i einen anderen Adapter verwenden hat Produkte zu zeigen, mit dem gleichen Code und es funktioniertAndroid Recycle Ansicht innerhalb des Fragments anzeigen "Kein Adapter angeschlossen; Layout überspringen"

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

Verwendung android Volley zu ersetzen. – Destro

+0

Zeigen Sie den Code Ihrer Adapterklasse an – Jas

+0

Fragment 'onCreate' Methode wird ausgeführt, bevor das Layout erstellt wird https://developer.android.com/reference/android/app/Fragment.html#onCreate(android.os.Bundle). Also 'mRVcategoryList = (RecyclerView) getActivity(). findViewById (R.id.rvcat); ' kann zu null – Serg

Antwort

1

Set Layoutmanager auf Ihre recyclerView mit getContext() anstelle von getActivity() und es wird klappen.

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

08-05 10: 22: 06.462 3069-3069 /? E/RecyclerView: Kein Adapter angeschlossen; Layout überspringen – bob

1

Vielen Dank das Problem war getActivity() von getView() OnPostExecute

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

danke, du bist mein Zeitsaver !! – inthy