0

私はJsonデータを取得できますが、RecyclerViewに読み込むことはできません。 Logcatを使用して、データがフェッチされているかどうかを確認しました.iは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>

onPostExecuteで

<?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. (category_list.xml)、結果は文字列であり、任意の処理を行う前に、JSONObjectに変換する必要があります。

    try { 
        jsonObject = new JSONObject(result); 
    } catch (JSONException e) { 
        e.printStackTrace(); 
    } 
    
    String error = jsonObject.optString("error"); 
    
  2. そう)(onPostExecuteでエラーのため をご確認のいずれかのチェックをコメントしていない、何のJSONオブジェクト「エラー」はありません。

    //if (error.equalsIgnoreCase("false")) { 
    
  3. 何jasonArray "詳細" 応答ではありません、それは "詳細"(小さな文字d)です。ので、詳細

    JSONArray carts = jsonObject.optJSONArray("details"); 
    
  4. するとエラーに変更しmsg-> java.lang.IndexOutOfBoundsException:前に追加要素がないので、無効なインデックス0は、サイズが

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

で0です。だから、それを変更して追加してください。

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が仮想メソッドcartAdapter.notifyDataSetChangedでヌルオブジェクト参照にnotifyDataSetChangedを()()を呼び出すための試み;.これは、グローバルCategoryAdapter cartAdapter;ローカルスコープを持つonCreate()に別のローカル宣言があるため、初期化されていません。だから、のonCreate内のローカル宣言()すべての5点を完了

    //CategoryAdapter cartAdapter; 
    
  • +0

    コメント。それでも問題は存在します。 –

    +0

    @AbYuvaRaj詳細をお知らせください。何が問題なのですか?別の投稿から変更されたアダプタクラスを使用することができます。 – Annada

    関連する問題