簡體   English   中英

在recyclerview中加載JSON數據

[英]Loading JSON data in recyclerview

我希望將JSON加載到recyclerview中,但無法確定代碼有什么問題。

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>

有什么問題

  1. 如果您正在獲取android.view.WindowLeaked:“活動類別”窗口泄漏,則最初是在此處添加的

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

  1. 那么誰在破壞Category活動呢?doInBackground()內部的任務可能做錯了什么。 是的,錯誤消息表示:原因:java.lang.SecurityException:權限被拒絕(缺少INTERNET權限?)

添加清單

<uses-permission android:name="android.permission.INTERNET"/>
  1. json響應為{“ cart”:0}。 沒有“錯誤” json對象,沒有“類別” jsonarray。

  2. 錯誤消息-> RecyclerView:未附加布局管理器; 跳過布局

在這兩行中添加

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

必須提供LayoutManager才能使RecyclerView起作用。 這里

  1. 在onBindViewHolder()-> java.lang.IllegalArgumentException時崩潰:上下文不能為null。 這是因為在構造函數中,需要將類別活動實例分配為上下文。 在某一方面的變化,

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

    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM