简体   繁体   English

在JSON ListView中重复相同的数据

[英]Repeating Same Data in JSON ListView

I have a Custom ListView Retrieving data from Mysql database by JSON but The Problem is the list view is showing only one entry repeatedly. 我有一个自定义ListView,通过JSON从Mysql数据库中检索数据,但问题是列表视图仅重复显示一个条目。 How Should I get this fixed ? 我应该如何解决这个问题?

Here is my code 这是我的代码

package com.example.monsterking.blood;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;


public class all_donors extends Fragment {

String myJSON;
private ProgressDialog pDialog;
private static final String TAG_RESULTS = "result";
private static final String TAG_NAME = "Name";
private static final String TAG_BLOOD = "Blood";
private static final String TAG_AREA = "Area";
private static final String TAG_MOBILE = "Mobile";
private static final String TAG_LASTDONATED = "LastDonated";
private static final String TAG_EMAIL = "Email";
private static final String TAG_GENDER = "Gender";
private static final String TAG_DISTRICT = "District";

Button call;
SwipeRefreshLayout mSwipeRefreshLayout;

JSONArray donors = null;

ArrayList<HashMap<String, String>> donorList;
HashMap<String, String> persons = new HashMap<String, String>();
ListView list;

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

    View myFragmentView = inflater.inflate(R.layout.activity_all_donors, container, false);

    list = (ListView) myFragmentView.findViewById(R.id.listViewAll);


    donorList = new ArrayList<HashMap<String, String>>();


    mSwipeRefreshLayout = (SwipeRefreshLayout) myFragmentView.findViewById(R.id.swifeRefresh);
    mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {

            getData();


        }
    });


    return myFragmentView;

}


protected void showList() {
    if (TAG_RESULTS != null) {
        donorList.clear();
        try {
            JSONObject jsonObj = new JSONObject(myJSON);
            donors = jsonObj.getJSONArray(TAG_RESULTS);

            for (int i = 0; i < donors.length(); i++) {
                JSONObject c = donors.getJSONObject(i);
                String Name = c.getString(TAG_NAME);
                String Blood = c.getString(TAG_BLOOD);
                String Area = c.getString(TAG_AREA);
                String Mobile = c.getString(TAG_MOBILE);
                String LastDonated = c.getString(TAG_LASTDONATED);
                String Email = c.getString(TAG_EMAIL);
                String District = c.getString(TAG_DISTRICT);
                String Gender = c.getString(TAG_GENDER);


                persons.put(TAG_NAME, Name);
                persons.put(TAG_BLOOD, Blood);
                persons.put(TAG_AREA, Area);
                persons.put(TAG_MOBILE, Mobile);
                persons.put(TAG_LASTDONATED, LastDonated);
                persons.put(TAG_EMAIL, Email);
                persons.put(TAG_DISTRICT, District);
                persons.put(TAG_GENDER, Gender);
                donorList.add(persons);


            }



        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        // stopping swipe refresh
        mSwipeRefreshLayout.setRefreshing(false);
        Log.e("ServiceHandler", "Couldn't get any data from the url");
    }

}

public void getData() {
    class GetDataJSON extends AsyncTask<String, Void, String> {

        /**
         * Before starting background thread Show Progress Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(all_donors.this.getActivity());
            pDialog.setMessage("Loading. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(true);
            pDialog.show();
        }

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


            DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
            HttpPost httppost = new HttpPost("http://monsterking.hol.es/fetchAll.php");

            // Depends on your web service
            httppost.setHeader("Content-type", "application/json");

            InputStream inputStream = null;
            String result = null;


            try {

                HttpResponse response = httpclient.execute(httppost);

                HttpEntity entity = response.getEntity();

                inputStream = entity.getContent();
                // json is UTF-8 by default
                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                StringBuilder sb = new StringBuilder();

                String line = null;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }

                result = sb.toString();
            } catch (Exception e) {
                // Oops
            } finally {
                try {
                    if (inputStream != null) inputStream.close();
                } catch (Exception squish) {
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            pDialog.dismiss();
            myJSON = result;
            showList();
            mSwipeRefreshLayout.setRefreshing(false);
            list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {


                    // Launching new Activity on selecting single List Item
                    Intent i = new Intent(getActivity().getApplicationContext(), donor_details.class);
                    // sending data to new activity

                    startActivity(i);


                }
            });

            CustomAdapter cus = new CustomAdapter(all_donors.this.getActivity(), donorList);
            list.setAdapter(cus);
        }

    }
    GetDataJSON g = new GetDataJSON();
    g.execute();
}

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        getData();
    } else {
        // fragment is no longer visible
    }
}

public class CustomAdapter extends BaseAdapter {
    LayoutInflater mInlfater;
    ArrayList<HashMap<String, String>> donorList ;

    public CustomAdapter(Context context, ArrayList<HashMap<String, String>> donorList) {
        mInlfater = LayoutInflater.from(context);
        this.donorList = donorList;

    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return donorList.size();
    }

    @Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder holder;
        if (convertView == null) {
            convertView = mInlfater.inflate(R.layout.donor_list, null);
            holder = new ViewHolder();

            holder.call = (Button) convertView.findViewById(R.id.listcall);
            holder.name = (TextView)convertView.findViewById(R.id.name);
            holder.blood = (TextView)convertView.findViewById(R.id.blood);
            holder.area = (TextView)convertView.findViewById(R.id.area);
            convertView.setTag(holder);

        } else {
            holder = (ViewHolder) convertView.getTag();
        }


        HashMap<String,String> map = donorList.get(position);
        holder.name.setText(map.get(TAG_NAME));
        holder.blood.setText(map.get(TAG_BLOOD));
        holder.area.setText(map.get(TAG_AREA));


        holder.call.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i = new Intent(getActivity().getApplicationContext(), login.class);
                startActivity(i);
            }
        });
        return convertView;
    }

    private class ViewHolder {
        Button call;
        TextView name,blood,area;
        }
    }

}

Here is the Output 这是输出

在此处输入图片说明

在您的showList方法中persons = new HashMap<String, String>()在开始的for循环下添加persons = new HashMap<String, String>()

Modify your showList method like below 修改您的showList方法,如下所示

protected void showList() {
    if (TAG_RESULTS != null) {
        donorList.clear();
        try {
            JSONObject jsonObj = new JSONObject(myJSON);
            donors = jsonObj.getJSONArray(TAG_RESULTS);

            for (int i = 0; i < donors.length(); i++) {
                JSONObject c = donors.getJSONObject(i);
                String Name = c.getString(TAG_NAME);
                String Blood = c.getString(TAG_BLOOD);
                String Area = c.getString(TAG_AREA);
                String Mobile = c.getString(TAG_MOBILE);
                String LastDonated = c.getString(TAG_LASTDONATED);
                String Email = c.getString(TAG_EMAIL);
                String District = c.getString(TAG_DISTRICT);
                String Gender = c.getString(TAG_GENDER);

                persons = new HashMap<String, String>();
                persons.put(TAG_NAME, Name);
                persons.put(TAG_BLOOD, Blood);
                persons.put(TAG_AREA, Area);
                persons.put(TAG_MOBILE, Mobile);
                persons.put(TAG_LASTDONATED, LastDonated);
                persons.put(TAG_EMAIL, Email);
                persons.put(TAG_DISTRICT, District);
                persons.put(TAG_GENDER, Gender);
                donorList.add(persons);


            }



        } catch (JSONException e) {
            e.printStackTrace();
        }
    } else {
        // stopping swipe refresh
        mSwipeRefreshLayout.setRefreshing(false);
        Log.e("ServiceHandler", "Couldn't get any data from the url");
    }

}

on the function 在功能上

@Override
    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

you are returning the position itself will i don't think this is your problem .. but you should return 'donorList.get(position);' 您正在返回职位本身,我不认为这是您的问题..但您应该返回'donorList.get(position);'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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