我的RecyclerView活动显示空白活动

时间:2017-09-12 06:18:05

标签: android mysql json android-recyclerview android-cardview

我开发了一个应用程序,通过查看教程(简化编码)显示使用RecyclerView和卡片视图制作的列表.cardview有两个文本视图和一个图像视图。我想从mysql数据库和图像URL获取数据使用毕加索加载到图像视图。我的应用程序正在运行但没有显示任何内容,并带有错误响应。

我的应用程序gradle文件是

apply plugin: 'com.android.application'

android {
    compileSdkVersion 24
    buildToolsVersion "26.0.0"
    defaultConfig {
        applicationId "com.example.selvam.listapp"
        minSdkVersion 14
        targetSdkVersion 24
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:24.2.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.2'
    compile 'com.android.support:recyclerview-v7:24.2.1'
    compile 'com.android.support:cardview-v7:24.2.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.android.volley:volley:1.0.0'



    testCompile 'junit:junit:4.12'
}

我的recycler_view xml文件是

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.selvam.listapp.MainActivity">
    <android.support.v7.widget.RecyclerView
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:id="@+id/myRecyclerView"
        tools:layout_constraintTop_creator="1"
        tools:layout_constraintRight_creator="1"
        android:layout_marginStart="8dp"
        android:layout_marginEnd="8dp"
        app:layout_constraintRight_toRightOf="parent"
        tools:layout_constraintLeft_creator="1"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"></android.support.v7.widget.RecyclerView>

</android.support.constraint.ConstraintLayout>

我的card_view 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="wrap_content"
    android:weightSum="1">
<android.support.v7.widget.CardView
    android:layout_width="match_parent"
    android:layout_height="219dp"
    android:layout_weight="0.16">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="40sp"
            android:id="@+id/tvName"
            />
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="40sp"
            android:id="@+id/tvPrice"
            />

        <ImageView
            android:id="@+id/imageView"
            android:layout_width="309dp"
            android:layout_height="148dp"
            android:layout_marginLeft="30dp"
            android:layout_marginStart="30dp"/>


    </LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>

&#39;我要列出的项目&#39;在课堂上

package com.example.selvam.listapp;

/**
 * Created by SELVAM on 11-09-2017.
 */

public class ListItems {
    private  String name;
    private  String price;
    private  String image;

    public ListItems(String name,String price,String image) {
        this.image=image;
        this.price=price;
        this.name=name;

    }

    public String getName() {
        return name;
    }

    public String getPrice() {
        return price;
    }

    public String getImage() {
        return image;
    }


}

我的Recycler适配器

package com.example.selvam.listapp;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import java.util.List;

/**
 * Created by SELVAM on 11-09-2017.
 */

public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {

    private List<ListItems> listItems;
    private Context context;

    public RecyclerAdapter(List<ListItems> listItems, Context context) {
        this.listItems = listItems;
        this.context = context;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_view,parent);
        return new ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        ListItems item=listItems.get(position);
        holder.tvName.setText(item.getName());
        holder.tvPrice.setText(item.getPrice());
        Picasso.with(context).load(item.getImage()).into(holder.imageView);


    }


    @Override
    public int getItemCount() {
        return listItems.size();
    }
    public class ViewHolder extends RecyclerView.ViewHolder {
        public TextView tvName;
        public TextView tvPrice;
        public ImageView imageView;
        public ViewHolder(View itemView) {
            super(itemView);
            tvName=(TextView)itemView.findViewById(R.id.tvName);
            tvPrice=(TextView)itemView.findViewById(R.id.tvPrice);
            imageView=(ImageView)itemView.findViewById(R.id.imageView);
        }
    }
}

我使用volley进行json解析的主要活动是

package com.example.selvam.listapp;

import android.app.ProgressDialog;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private static final String URL_LIST="http://192.168.28.2/signup/activities/getDataToListview.php";

    private RecyclerView recyclerView;
    private RecyclerView.Adapter adapter;
    private List<ListItems> listitems;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView=(RecyclerView)findViewById(R.id.myRecyclerView);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        listitems=new ArrayList<>();
        loadRecyclerView();

    }
    public void loadRecyclerView(){
        final ProgressDialog progressDialog=new ProgressDialog(this);
        progressDialog.setMessage("loading lists...");
        progressDialog.show();
        StringRequest stringRequest=new StringRequest(Request.Method.GET, URL_LIST, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                progressDialog.dismiss();
                try {
                    JSONObject jsonObject=new JSONObject(response);
                   JSONArray array=jsonObject.getJSONArray("list");

                    for(int i=0;i<array.length();i++){
                        JSONObject js=array.getJSONObject(i);
                        ListItems item=new ListItems(
                                js.getString("name"),js.getString("price"),js.getString("image")
                        );
                        listitems.add(item);
                    }
                    adapter=new RecyclerAdapter(listitems,getApplicationContext());
                    recyclerView.setAdapter(adapter);



                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();
                        Toast.makeText(getApplicationContext(),"lists cannot be displayed",Toast.LENGTH_SHORT).show();

                    }
                }
        );
        RequestQueue requestQueue= Volley.newRequestQueue(this);
        requestQueue.add(stringRequest);


    }
           }

我从mysql数据库输出的json是

{"list":[{"name":"messi","price":"hundred","image":"http:\/\/192.168.28.2\/img\/messi.jpeg"},{"name":"goat","price":"twohundred","image":"http:\/\/192.168.28.2\/img\/goat.jpg"},{"name":"cristiano","price":"threehundred","image":"http:\/\/192.168.28.2\/img\/cr7.jpg"}]}

我搜索并尝试了很多。请帮我搞错。提前致谢

2 个答案:

答案 0 :(得分:0)

试试吧!

第1步:检查recyclerView = 0dp 宽度。尝试更改= “match_parent”。如果不起作用,请尝试Step2

第2步:尝试以下代码:

public void loadRecyclerView(){
final ProgressDialog progressDialog=new ProgressDialog(this);
progressDialog.setMessage("loading lists...");
progressDialog.show();
adapter=new RecyclerAdapter(listitems,getApplicationContext());
recyclerView.setAdapter(adapter);
JsonObjectRequest getRequest = new JsonObjectRequest(Request.Method.GET, url, null,
new Response.Listener<JSONObject>() 
{
    @Override
    public void onResponse(JSONObject response) {   
                    // display response     
        Log.d("Response", response.toString());
        try {
               JSONArray array=response.getJSONArray("list");

                for(int i=0;i<array.length();i++){
                    JSONObject js=array.getJSONObject(i);
                    ListItems item=new ListItems(
                            js.getString("name"),js.getString("price"),js.getString("image")
                    );
                    listitems.add(item);
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
adapter.notifyDataSetChanged(); 

    }
}, 
new Response.ErrorListener() 
{
     @Override
     public void onErrorResponse(VolleyError error) {            
        Log.d("Error.Response", response);
   }
}
);

RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(getRequest);
}

答案 1 :(得分:0)

在适配器中设置列表。 将此方法添加到适配器

public void setItems(List<ListItems> list) {
this.list = list;
}

并像这样称呼它

adapter.setItems(list);
adapter.notifyDataSetChanged();