0

我可以獲取我的Json數據但我無法加載RecyclerView。我使用Logcat來檢查數據是否被提取,我可以看到Json數據。 我的代碼如下。獲取Json數據,但不能加載

Category.java

public class Category extends AppCompatActivity { 
    public List<String> Category; 
    public RecyclerView rcv; 
    public ImageView img; 
    public List<CategoryList> items; 
    public List<String> Images; 

public CategoryAdapter cartAdapter; 
JSONObject jsonObject = new JSONObject(); 
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<>(); 


    rcv=(RecyclerView)findViewById(R.id.recycler_view); 
    img=(ImageView)findViewById(R.id.Img); 
    CategoryAdapter cartAdapter; 
    cartAdapter = new CategoryAdapter(Category.this, items); 
    rcv.setLayoutManager(new LinearLayoutManager(Category.this)); 
    rcv.setAdapter(cartAdapter); 
    new getCart().execute(); 
    } 
private class getCart 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("POST"); 
       conn.setDoInput(true); 
       conn.setDoOutput(true); 

       conn.setDoInput(true); 
       conn.setDoOutput(true); 

       Uri.Builder builder = new Uri.Builder().appendQueryParameter("request", "Category"); 
       String query = builder.build().getEncodedQuery(); 

       OutputStream os = conn.getOutputStream(); 
       BufferedWriter writer = new BufferedWriter(
         new OutputStreamWriter(os, "UTF-8")); 
       writer.write(query); 
       writer.flush(); 
       writer.close(); 
       os.close(); 
       conn.connect(); 
      } catch (IOException e1) { 
       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(); 
      Log.d("result", result); 


      String error = jsonObject.optString("error"); 
      if (error.equalsIgnoreCase("false")) { 
       JSONArray carts = jsonObject.optJSONArray("Details"); 

       for (int i = 0; i < carts.length(); i++) 
       { 

        JSONObject object = carts.optJSONObject(i); 

        Log.d("object", object.toString()); 

        Category.set(i, object.optString("Category")); 
        Images.set(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); 
        Log.d("items",items.toString()); 
       } 

       cartAdapter.notifyDataSetChanged(); 
      } 

     } 

    } 
} 

CategoryAdapter.java

public class CategoryAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> { 
private Context context; 
private LayoutInflater inflater; 
List<CategoryList> items; 
CategoryList current; 
int currentPos=0; 

class MyHolder extends RecyclerView.ViewHolder{ 

    TextView CategoryName; 
    ImageView CategoryImage; 


    // create constructor to get widget reference 
    public MyHolder(View itemView) { 
     super(itemView); 
     CategoryName= (TextView) itemView.findViewById(R.id.txtview); 
     CategoryImage= (ImageView) itemView.findViewById(R.id.Img); 
    } 

} 

public CategoryAdapter(Context context, List<CategoryList> items){ 
    this.context=context; 
    inflater= LayoutInflater.from(context); 
    this.items=items; 
} 

// Inflate the layout when viewholder created 
@Override 
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { 
    View view=inflater.inflate(R.layout.category_list, 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; 
    CategoryList current=items.get(position); 
    myHolder.CategoryName.setText(current.getCategory()); 

    // load image into imageview using glide 
    Glide.with(context).load("http://www.dazecorp.com/demos/Vellore_Kitchen/API/CategoryApi.php" + current.getCategoryImage()) 
      .into(myHolder.CategoryImage); 

} 

// return total item from List 
@Override 
public int getItemCount() { 
    return (null!= items ? items.size():0); 
} 

}

CategoryList.java

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


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="100dp" 
 
     android:layout_width="100dp 
 
     " 
 
     android:layout_gravity="center_horizontal" /> 
 
     <ImageView 
 
      android:layout_width="100dp" 
 
      android:layout_height="100dp" 
 
      android:id="@+id/Img" 
 

 
      android:layout_gravity="center_horizontal" /> 
 

 
</LinearLayout>

回答

0
  1. 在onPostExecute(),結果是字符串,需要做任何處理之前轉換爲JSONObject的。

    try { 
        jsonObject = new JSONObject(result); 
    } catch (JSONException e) { 
        e.printStackTrace(); 
    } 
    
    String error = jsonObject.optString("error"); 
    
  2. 沒有JSON對象「錯誤」,所以不要在onPostExecute檢查錯誤() 或者評論檢查。

    //if (error.equalsIgnoreCase("false")) { 
    
  3. 不存在響應不jasonArray 「詳細信息」,它是 「細節」(小寫字母d)。因此它更改爲細節

    JSONArray carts = jsonObject.optJSONArray("details"); 
    
  4. 然後錯誤MSG-> java.lang.IndexOutOfBoundsException:無效索引0,大小爲0在

    Category.set(i, object.optString("Category")); 
    Images.set(i, object.optString("CategoryImage")); 
    

因爲沒有前添加的元素。所以改變它添加。

Category.add(i, object.optString("Category")); 
Images.add(i, object.optString("CategoryImage")); 

//Category.set(i, object.optString("Category")); 
//Images.set(i, object.optString("CategoryImage")); 
  • 然後顯示java.lang.NullPointerException:嘗試調用虛擬方法notifyDataSetChanged()上在cartAdapter.notifyDataSetChanged空對象引用();.這是因爲全球的CategoryAdapter cartAdapter;沒有初始化,因爲onCreate()中有另一個本地範圍,它具有局部範圍。所以註釋掉局部聲明中的onCreate()

    //CategoryAdapter cartAdapter; 
    
  • +0

    完成所有5個點。問題仍然存在。 –

    +0

    @AbYuvaRaj請提供詳細信息,是什麼問題?你可以在你的另一篇文章中使用修改後的適配器類。 – Annada