简体   繁体   中英

Loading JSON data in recyclerview

I want my JSON to load in a recyclerview but can't figure what problem with the code.

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>

What is the issue?

  1. If your are getting android.view.WindowLeaked: Activity Category has leaked window, that was originally added here

That means the activity is exited before showing the ProgressDialog.

  1. Who is destroying the Category activity then?The task inside doInBackground() could be doing something wrong. Yes the error msg says: Caused by: java.lang.SecurityException: Permission denied (missing INTERNET permission?)

Add in manifest

<uses-permission android:name="android.permission.INTERNET"/>
  1. json response is {"cart":0}. There is no "error" json object, no "Category" jsonarray.

  2. error msg-> RecyclerView: No layout manager attached; skipping layout

Add this two lines in

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

A LayoutManager must be provided for RecyclerView to function. here

  1. crash at onBindViewHolder() ->java.lang.IllegalArgumentException: Context must not be null. This is because in constructor, need to assign categoty activity instance as context. change in,

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM