2016-08-11 35 views
0

我想讓我的JSON在recyclerview中加載,但無法確定代碼的問題。在recyclerview中加載JSON數據

Category.java

public class Category extends AppCompatActivity { 
    private List<String> Category; 
    private RecyclerView rcv; 
    private ImageView img; 
    private List<CategoryList> items; 
    private List<String> Images; 
public static final int CONNECTION_TIMEOUT = 10000; 
public static final int READ_TIMEOUT = 15000; 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.content_category); 
     Category = new ArrayList<>(); 
     items = new ArrayList<>(); 
     Images=new ArrayList<>(); 
    new getCart1().execute(); 
    } 
private class getCart1 extends AsyncTask<String, String, String> { 
    ProgressDialog pdLoading = new ProgressDialog(Category.this); 
    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("http://www.dazecorp.com/demos/Vellore_Kitchen/API/CategoryApi.php"); 

      } 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) { 
      pdLoading.dismiss(); 
      try { 
       JSONObject jObject = null; 
       try { 
        jObject = new JSONObject(result); 
       } catch (JSONException e) { 
        e.printStackTrace(); 
       } 
       String error = jObject.optString("error"); 
       if (error.equalsIgnoreCase("false")) { 
        JSONArray carts = jObject.optJSONArray("Category"); 
        for (int i = 0; i < carts.length(); i++) { 
         JSONObject object = carts.optJSONObject(i); 
         Log.d("object", object.toString()); 
         Category.add(i, object.optString("Category")); 
         Images.add(i,object.optString("CategoryImage")); 
        } 
        for (int i = 0; i < Category.size(); i++) { 
         CategoryList item = new CategoryList(Category.get(i),Images.get(i)); 
         items.add(item); 
        } 
        RecyclerView rcv=(RecyclerView)findViewById(R.id.recycler_view); 
        img=(ImageView)findViewById(R.id.Img); 
        CategoryAdapter cartAdapter = new CategoryAdapter(Category.this, items); 
        rcv.setAdapter(cartAdapter); 
       } 
      } catch (NullPointerException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
} 

CategoryAdapter.java

public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder>{ 
private List<CategoryList> CategoryList; 
    private Context context; 
    public class MyViewHolder extends RecyclerView.ViewHolder { 
     public TextView Category; 
     public ImageView imgview; 

     public MyViewHolder(View view) { 
      super(view); 
      Category = (TextView) view.findViewById(R.id.txtview); 
      imgview= (ImageView) view.findViewById(R.id.Img); 
     } 
    } 
    public CategoryAdapter(Category category, List<CategoryList> CategoryList) { 
     this.CategoryList= CategoryList; 
     this.context=context; 
    } 
    @Override 
    public CategoryAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
     View itemView = LayoutInflater.from(parent.getContext()) 
       .inflate(R.layout.category_list, parent, false); 
     return new MyViewHolder(itemView); 
    } 
    @Override 
    public void onBindViewHolder(CategoryAdapter.MyViewHolder holder, int position) { 
     CategoryList category=CategoryList.get(position); Picasso.with(context).load(CategoryList.get(position).getCategoryImage()).resize(240, 120).into(holder.imgview); holder.Category.setText(category.getCategory()); 
    } 
    @Override 
    public int getItemCount() { 
     return CategoryList.size(); 
    } 
} 

CategoryList.java

public class CategoryList { 
    private String Category; 
    private String CategoryImage; 

public CategoryList(){} 
    public CategoryList(String Category,String CategoryImage) 
    { 
     this.Category=Category; 
     this.CategoryImage=CategoryImage; 
    } 
    public String getCategory() 
    { 
     return Category; 
    } 
    public void setCategory(String Category) 
    { 
     this.Category=Category; 
    } 
    public String getCategoryImage() 
    { 
     return CategoryImage; 
    } 
    public void setCategoryImage(String CategoryImage) 
    { 
     this.CategoryImage=CategoryImage; 
    } 
} 

content_category.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" 
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:paddingLeft="@dimen/activity_horizontal_margin" 
    android:paddingRight="@dimen/activity_horizontal_margin" 
    android:paddingTop="@dimen/activity_vertical_margin" 
    android:paddingBottom="@dimen/activity_vertical_margin" 
    app:layout_behavior="@string/appbar_scrolling_view_behavior" 
    tools:showIn="@layout/activity_category" 
    tools:context="com.example.yuvaraj.vellorekitchen.Category"> 

    <android.support.v7.widget.RecyclerView 
     android:id="@+id/recycler_view" 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:scrollbars="vertical" /> 

</RelativeLayout> 

category_list.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <TextView 
     android:id="@+id/txtview" 
     android:layout_height="wrap_content" 
     android:layout_width="wrap_content" 
     /> 
     <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:id="@+id/Img"/> 

</LinearLayout> 

回答

0

問題是什麼?

  1. 如果越來越 android.view.WindowLeaked:活動類別已泄漏的窗口,這是原來此處添加

這意味着該活動顯示ProgressDialog之前退出。

  1. 誰在銷燬Category活動呢?doInBackground()中的任務可能會做錯事。 是錯誤味精說:造成:java.lang.SecurityException異常:權限被拒絕(?缺少INTERNET權限)

加入清單中

<uses-permission android:name="android.permission.INTERNET"/> 
  • json響應是{「cart」:0}。沒有「錯誤」json對象,沒有「類別」jsonarray。

  • error msg-> RecyclerView:沒有附加布局管理器;跳繩佈局

  • onPostExecute() 
    LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); 
    rcv.setLayoutManager(layoutManager); 
    

    一個LayoutManager添加這兩條線必須提供RecyclerView工作。 here

  • 在onBindViewHolder崩潰() - > java.lang.IllegalArgumentException異常:上下文不能爲空。這是因爲在構造函數中,需要將類別活動實例指定爲上下文。改變,

    public CategoryAdapter(Category category, List<CategoryList> CategoryList) { 
    this.CategoryList= CategoryList; 
    this.context = category; //here changed from context to categoty for passing context 
    

    }

  • +0

    我的問題是在回收活性。JSON表示什麼都不會通過傳遞PARAMS獲得。通過傳遞參數請求(鍵)類別(值)嘗試投擲或請求。你會得到一個json resposne。 –

    +0

    @AbYuvaRaj請檢查答案,我已經添加了點4,5 – Annada