Android在RecyclerView中将数据从json显示到cardview

时间:2022-02-08 03:45:14

I want to display data from webservice to cardview in recycleviewer. It had already success to display data. But it only display one data, although it has a lot of data to display. Can you help me to solve this problem? Thank you

我想在recycleviewer中显示从webservice到cardview的数据。它已经成功显示数据。但它只显示一个数据,尽管它有很多数据要显示。你能帮我解决这个问题吗?谢谢

Seller.java

Seller.java

public class Seller {
    String penjual,image,alamat,telp;

    public String getPenjual() {
        return penjual;
    }

    public void setPenjual(String penjual) {
        this.penjual = penjual;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getAlamat() {
        return alamat;
    }

    public void setAlamat(String alamat) {
        this.alamat = alamat;
    }

    public String getTelp() {
        return telp;
    }

    public void setTelp(String telp) {
        this.telp = telp;
    }
}

SellerAdapter.Java

SellerAdapter.Java

import android.content.Context;
import android.support.v7.widget.CardView;
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.amobi.lomapodfix.R;
import com.amobi.lomapodfix.model.Seller;
import com.squareup.picasso.Picasso;

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

/**
 * Created by Nicky-PC on 5/4/2016.
 */
public class SellerAdapter extends RecyclerView.Adapter<SellerAdapter.PersonViewHolder> {

    List<Seller> sellers;
    Context context;
    public SellerAdapter(Context context,List<Seller> sellers)
    {
        this.sellers=sellers;
        this.context=context;
    }

    public void setGridData(List<Seller> mGridData)
    {
        this.sellers=mGridData;
        notifyDataSetChanged();
    }
    @Override
    public PersonViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_toko, parent, false);
        PersonViewHolder pvh = new PersonViewHolder(v);
        return pvh;
    }

    @Override
    public void onBindViewHolder(PersonViewHolder holder, int i) {
        holder.Seller.setText(sellers.get(i).getPenjual());
        holder.Address.setText(sellers.get(i).getAlamat());
        holder.Telp.setText(sellers.get(i).getTelp());
        Picasso.with(context).load(sellers.get(i).getImage()).fit().into(holder.image);
    }

    @Override
    public int getItemCount() {
        return sellers.size();
    }

    public static class PersonViewHolder extends RecyclerView.ViewHolder {
        CardView cv;
        TextView Seller;
        TextView Address;
        TextView Telp;
        ImageView image;

        PersonViewHolder(View itemView) {
            super(itemView);
            cv = (CardView)itemView.findViewById(R.id.cv);
            Seller = (TextView)itemView.findViewById(R.id.lvSeller);
            Address = (TextView)itemView.findViewById(R.id.lvAlamat);
            Telp = (TextView)itemView.findViewById(R.id.lvAlamat);
            image= (ImageView)itemView.findViewById(R.id.person_photo);
        }
    }
    @Override
    public void onAttachedToRecyclerView(RecyclerView recyclerView) {
        super.onAttachedToRecyclerView(recyclerView);
    }
}

DogFragment.java

DogFragment.java

import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.amobi.lomapodfix.JSONParser;
import com.amobi.lomapodfix.MainActivity;
import com.amobi.lomapodfix.R;
import com.amobi.lomapodfix.adapter.SellerAdapter;
import com.amobi.lomapodfix.model.Seller;

import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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

/**
 * A simple {@link Fragment} subclass.
 */
public class DogFragment extends Fragment {

    SellerAdapter mGridadapter;
    JSONParser jParser= new JSONParser();
    ArrayList<HashMap<String, String>> nameList;
    JSONArray names=null;
    RecyclerView data;
    List<Seller> mgridData;
    ProgressDialog pDialog;
    private static final String URL_TEST_ANJING = "http://lomapod.azurewebsites.net/readSellerAnjing.php";
    private static final String TAG_PESAN = "message";
    private static final String TAG_HASIL = "result";
    private static final String TAG_ID = "id_penjual";
    private static final String TAG_SELLER= "nama_toko";
    private static final String TAG_ALAMAT= "alamat_toko";
    private static final String TAG_TELP= "no_telp";
    private static final String TAG_IMAGE= "image_name";
    private RecyclerView.LayoutManager layoutManager;


    public DogFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View rootView=inflater.inflate(R.layout.fragment_dog, container, false);
        data=(RecyclerView) rootView.findViewById(R.id.rv);
        layoutManager = new LinearLayoutManager(getActivity());
        data.setLayoutManager(layoutManager);
        mgridData=new ArrayList<>();
        mGridadapter=new SellerAdapter(getActivity(),mgridData);

        new AmbilDataJsonAnjing().execute();
        return rootView;
    }

    public class AmbilDataJsonAnjing extends AsyncTask<String,String,String> {

        int sukses=0;

        public AmbilDataJsonAnjing() {
            pDialog = new ProgressDialog(getActivity());
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog.setMessage("Mengambil Data. Silahkan Tunggu...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }

        @Override
        protected String doInBackground(String... args) {

            List<NameValuePair> params = new ArrayList<NameValuePair>();

            try
            {
                JSONObject json = jParser.makeHttpRequest(URL_TEST_ANJING, "GET", params);
                Seller sellers=null;
                if(json != null)
                {
                    sukses = json.getInt(TAG_PESAN);
                    if(sukses == 1)
                    {
                        nameList = new ArrayList<HashMap<String,String>>();
                        Log.d("Semua Nama: ", json.toString());
                        names = json.getJSONArray(TAG_HASIL);

                        for(int i = 0; i < names.length();i++)
                        {
                            JSONObject c = names.getJSONObject(i);
                            String id = c.getString(TAG_ID);
                            String seller = c.getString(TAG_SELLER);
                            String alamat=c.getString(TAG_ALAMAT);
                            String telp=c.getString(TAG_TELP);
                            String image=c.getString(TAG_IMAGE);

                            HashMap<String,String> map = new HashMap<String,String>();

                            sellers=new Seller();
                            sellers.setPenjual(seller);
                            sellers.setAlamat(alamat);
                            sellers.setTelp(telp);
                            sellers.setImage(image);

                            map.put(TAG_ID, id);
                            map.put(TAG_SELLER,seller);
                            map.put(TAG_ALAMAT,alamat);
                            map.put(TAG_TELP,telp);
                            nameList.add(map);
                            mgridData.add(sellers);
                        }
                    }
                }
            }catch(JSONException e)
            {
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(String s) {
            pDialog.dismiss();
            RecyclerView.Adapter adapter=new SellerAdapter(getActivity(),mgridData);
            if(sukses == 1 )
            {
                mGridadapter.setGridData(mgridData);
                data.setAdapter(adapter);
            }
            else
            {
                Toast.makeText(getActivity(), "Error - No Data Available", Toast.LENGTH_SHORT).show();
            }
        }
    }

}

And I get this in android monitor

我在Android监视器中得到这个

05-04 23:35:55.874 5605-5668/com.amobi.lomapodfix D/url: http://lomapod.azurewebsites.net/readSellerAnjing.php?
05-04 23:35:55.878 5605-5605/com.amobi.lomapodfix W/FragmentManager: moveToState: Fragment state for CatFragment{a9c44708 #1 id=0x7f0d007e android:switcher:2131558526:1} not updated inline; expected state 3 found 2
05-04 23:35:55.938 5605-5605/com.amobi.lomapodfix W/EGL_emulation: eglSurfaceAttrib not implemented
05-04 23:35:55.938 5605-5605/com.amobi.lomapodfix E/RecyclerView: No adapter attached; skipping layout
05-04 23:35:55.946 5605-5605/com.amobi.lomapodfix I/dalvikvm: Could not find method android.support.v7.widget.LinearLayoutCompat.drawableHotspotChanged, referenced from method android.support.design.internal.ForegroundLinearLayout.drawableHotspotChanged
05-04 23:35:55.946 5605-5605/com.amobi.lomapodfix W/dalvikvm: VFY: unable to resolve virtual method 15705: Landroid/support/v7/widget/LinearLayoutCompat;.drawableHotspotChanged (FF)V
05-04 23:35:55.946 5605-5605/com.amobi.lomapodfix D/dalvikvm: VFY: replacing opcode 0x6f at 0x0000
05-04 23:35:55.958 5605-5608/com.amobi.lomapodfix D/dalvikvm: GC_CONCURRENT freed 374K, 8% free 55730K/60500K, paused 2ms+1ms, total 9ms
05-04 23:35:56.098 5605-5668/com.amobi.lomapodfix I/info: org.apache.http.client.methods.HttpGet@a9c7a668
05-04 23:35:56.098 5605-5668/com.amobi.lomapodfix D/Semua Nama:: {"message":1,"result":[{"no_telp":"08345678","nama_toko":"lomapod","image_name":null,"id_image":"1","no_rek":"12345","email":"sekar@gmail.com","id_penjual":"1","alamat_toko":"jl.bbbbb","kota":"Yogyakarta","nama_bank":"BBB"},{"no_telp":"0829417","nama_toko":"meow","image_name":null,"id_image":"1","no_rek":"12345","email":"nicky@gmail.com","id_penjual":"2","alamat_toko":"jl.ccccc","kota":"Yogyakarta","nama_bank":"BNI"}]}
05-04 23:35:56.682 5605-5605/com.amobi.lomapodfix W/EGL_emulation: eglSurfaceAttrib not implemented
05-04 23:35:56.702 5605-5605/com.amobi.lomapodfix I/Choreographer: Skipped 42 frames!  The application may be doing too much work on its main thread.
05-04 23:35:56.706 5605-5605/com.amobi.lomapodfix E/RecyclerView: No adapter attached; skipping layout
05-04 23:35:56.918 5605-5605/com.amobi.lomapodfix W/Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.

3 个解决方案

#1


5  

I've encountered this issue that the recycler view only displays the first item. It was because I was importing different versions of recyclerview, cardview, design and appcompat. The issue is fixed after I made the versions consistent in the app gradle, The version doesn't have to be 23.2.1 but they have to be the same for all of these.

我遇到过这个问题,回收者视图只显示第一个项目。这是因为我导入了不同版本的recyclerview,cardview,design和appcompat。在我将应用程序gradle中的版本设置为一致后,问题就解决了。版本不一定是23.2.1但是它们必须对所有这些都相同。

compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:design:23.2.1'
compile 'com.android.support:recyclerview-v7:23.2.1'
compile 'com.android.support:cardview-v7:23.2.1'

Another cause could be you are using match_parent for the height for the items in the recyclerview and the parent container of you recyclerview. This makes the first item to occupy the entire screen. Should use wrap_content or give a specific height instead.

另一个原因可能是您使用match_parent作为recyclerview中项目的高度以及recyclerview的父容器。这使得第一项占据整个屏幕。应该使用wrap_content或给出一个特定的高度。

#2


0  

Try using this in your fragment class.

尝试在片段类中使用它。

@Override
 protected void onPostExecute(String s) {
 pDialog.dismiss();

 if(sukses == 1 ) {
    if(mgridData.size()!=0){
    mGridadapter  =new SellerAdapter(getActivity(),mgridData);
    data.setAdapter(adapter);
 }
 else {
    Toast.makeText(getActivity(), "Error - No Data Available", Toast.LENGTH_SHORT).show();
      }
}

#3


0  

you need add adapter inside onCreateView() like

你需要在onCreateView()里面添加适配器

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View rootView=inflater.inflate(R.layout.fragment_dog, container, false);
        data=(RecyclerView) rootView.findViewById(R.id.rv);
        layoutManager = new LinearLayoutManager(getActivity());
        data.setLayoutManager(layoutManager);
        mgridData=new ArrayList<>();
        mGridadapter=new SellerAdapter(getActivity(),mgridData);

        data.setAdapter(mGridadapter);

        new AmbilDataJsonAnjing().execute();
        return rootView;
    }

And change onPostExecute() method

并更改onPostExecute()方法

@Override
        protected void onPostExecute(String s) {
            pDialog.dismiss();
            mGridadapter.notifyDataSetChanged();
        }

#1


5  

I've encountered this issue that the recycler view only displays the first item. It was because I was importing different versions of recyclerview, cardview, design and appcompat. The issue is fixed after I made the versions consistent in the app gradle, The version doesn't have to be 23.2.1 but they have to be the same for all of these.

我遇到过这个问题,回收者视图只显示第一个项目。这是因为我导入了不同版本的recyclerview,cardview,design和appcompat。在我将应用程序gradle中的版本设置为一致后,问题就解决了。版本不一定是23.2.1但是它们必须对所有这些都相同。

compile 'com.android.support:appcompat-v7:23.2.1'
compile 'com.android.support:design:23.2.1'
compile 'com.android.support:recyclerview-v7:23.2.1'
compile 'com.android.support:cardview-v7:23.2.1'

Another cause could be you are using match_parent for the height for the items in the recyclerview and the parent container of you recyclerview. This makes the first item to occupy the entire screen. Should use wrap_content or give a specific height instead.

另一个原因可能是您使用match_parent作为recyclerview中项目的高度以及recyclerview的父容器。这使得第一项占据整个屏幕。应该使用wrap_content或给出一个特定的高度。

#2


0  

Try using this in your fragment class.

尝试在片段类中使用它。

@Override
 protected void onPostExecute(String s) {
 pDialog.dismiss();

 if(sukses == 1 ) {
    if(mgridData.size()!=0){
    mGridadapter  =new SellerAdapter(getActivity(),mgridData);
    data.setAdapter(adapter);
 }
 else {
    Toast.makeText(getActivity(), "Error - No Data Available", Toast.LENGTH_SHORT).show();
      }
}

#3


0  

you need add adapter inside onCreateView() like

你需要在onCreateView()里面添加适配器

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View rootView=inflater.inflate(R.layout.fragment_dog, container, false);
        data=(RecyclerView) rootView.findViewById(R.id.rv);
        layoutManager = new LinearLayoutManager(getActivity());
        data.setLayoutManager(layoutManager);
        mgridData=new ArrayList<>();
        mGridadapter=new SellerAdapter(getActivity(),mgridData);

        data.setAdapter(mGridadapter);

        new AmbilDataJsonAnjing().execute();
        return rootView;
    }

And change onPostExecute() method

并更改onPostExecute()方法

@Override
        protected void onPostExecute(String s) {
            pDialog.dismiss();
            mGridadapter.notifyDataSetChanged();
        }