PARSing JSON для ListView - PullRequest
       5

PARSing JSON для ListView

2 голосов
/ 16 июня 2011

Хорошо, я просмотрел множество примеров PARSing моих результатов JSON, но безуспешно. У меня есть пример JSON ниже, я не хочу информацию о статусе или геолокации прямо сейчас. Я просто хочу использовать объект станции и выбрать некоторые вещи из массива для отображения в моем ListView в виде списка. Я не понимаю никакой документации там.

Может ли кто-нибудь предоставить простой пример того, как читать JSON и помещать его в ListView. Это было бы очень полезно. На самом деле у меня нет кода, так как у меня ничего не получалось.

{
"status": {
    "error": "NO",
    "code": 200,
    "description": "none",
    "message": "Request ok"
},
"geoLocation": {
    "city_id": "147",
    "city_long": "Saint-Laurent",
    "region_short": "QC",
    "region_long": "Quebec",
    "country_long": "Canada",
    "country_id": "43",
    "region_id": "35"
},
"stations": [
    {
        "country": "Canada",
        "reg_price": "N\/A",
        "mid_price": "N\/A",
        "pre_price": "N\/A",
        "diesel_price": "N\/A",
        "address": "3885, Boulevard de la C\u00f4te-Vertu",
        "diesel": "0",
        "id": "33862",
        "lat": "45.492367",
        "lng": "-73.710915",
        "station": "Shell",
        "logo": "http:\/\/www.mygasfeed.com\/img\/station-logo\/logo-shell.png",
        "region": "Quebec",
        "city": "Saint-Laurent",
        "reg_date": "N\/A",
        "mid_date": "N\/A",
        "pre_date": "N\/A",
        "diesel_date": "N\/A",
        "distance": "1.9km"
    }
]

Ответы [ 3 ]

6 голосов
/ 16 июня 2011

Сначала проанализируйте ваш объект JSON следующим образом:

String str_json = "your json string";
try {
    JSONObject obj = new JSONObject(str_json);
    JSONArray stations = obj.getJSONArray("stations");
    //etc etc...

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

Затем проанализируйте этот JSONArray в ArrayList созданных вами пользовательских объектов Station, например:

public class Station {

    public String country;
    public int reg_price;
    // etc etc...
}

Поместите элементы из JSONArray в ваш ArrayList:

ArrayList<Station> stationsArrList = new ArrayList<Station>();

int len = stations.size();    
for ( int i = 0; i < len; i++ ){
    JSONObject stationObj = stations.getJSONObject(i);
    Station station = new Station();

    for ( int j = 0; j < stationObj.len(); j++ ){
        //add items from stationObj to station
    }
    stationsArrList.add(station);
}

Затем создайте адаптер (если вы хотите, чтобы отображалось более двух частей информации):

public class StationListAdapter extends BaseAdapter {
    private static ArrayList<Station> stationArrayList;

    private LayoutInflater inflator;

    public StationListAdapter(Context context, ArrayList<Station> results) {
        stationArrayList = results;
        inflator = LayoutInflater.from(context);
    }

    public int getCount() {
        if (stationArrayList == null)
            return 0;
        else
            return stationArrayList.size();
    }

    public Object getItem(int position) {
        try {
            return stationArrayList.get(position);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder holder;
        if (convertView == null) {
            convertView = inflator.inflate(R.layout.list_item_station, null);
            holder = new ViewHolder();
            holder.country = (TextView) convertView.findViewById(R.id.station_listview_item_one);
            holder.reg_price = (TextView) convertView.findViewById(R.id.station_listview_item_two);
            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        holder.country.setText(stationArrayList.get(position).getCountry());
        holder.reg_price.setText( stationArrayList.get(position).getRegPrice());

        return convertView;
    }

    static class ViewHolder {
        TextView country;
        TextView reg_price;
        //etc
    }
}

В адаптере вы будете использовать XML-макет списка, который вы определили для каждой строки списка.

Наконец, вы получаете ссылку на список и добавляете данные по основному коду активности:

stationList = (ListView) findViewById(R.id.station_list_view);
stationListAdapter = new StationListAdapter(this, stationsArrList);
stationList.setAdapter(stationListAdapter);
3 голосов
/ 16 июня 2011

Вот пример того, как вы будете анализировать массив и отображать его в виде списка. Я не включил xml, но довольно просто описать просмотр списка и многострочный результат, содержащий поля txt для страны и адреса (или любого другого):

 String[] from = new String[] {"row_1", "row_2"};
 int[] to = new int[] { R.id.country, R.id.address};
 List<HashMap<String, String>> fillMaps = new ArrayList<HashMap<String, String>>();

try {
     JSONObject obj = new JSONObject(jsonString);
     JSONArray stations = obj.getJSONArray("stations");
     Log.i(TAG,"Number of entries " + stations.length());
     for (int j = 0; j < stations.length(); j++) {
             JSONObject jsonObject = stations.getJSONObject(j);
             HashMap<String, String> map = new HashMap<String, String>();
             map.put("row_1", jsonObject.getString("country"));
             map.put("row_2", jsonObject.getString("address"));

             fillMaps.add(map);
     }
 } catch (Exception e) {
        e.printStackTrace();
 }

 SimpleAdapter adapter = new SimpleAdapter(context, fillMaps, R.layout.result, from, to);
 mListView.setAdapter(adapter);
0 голосов
/ 24 апреля 2013
public class JSONParsingExampleActivity extends Activity {
/** Called when the activity is first created. */

 private ArrayList<String> id;
 private ArrayList<String> name;
 private ArrayList<String> email;
 private ArrayList<String> address;
 private ArrayList<String> gender;
 private ArrayList<String> mobile;
 private ArrayList<String> home;
 private ArrayList<String> office;
 ListView view;
 ProgressDialog mDialog=null;       // Thread code
 private Runnable viewOrders;   // Thread code
 private Thread thread1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    id=new ArrayList<String>();
    name=new ArrayList<String>();
    email=new ArrayList<String>();
    address=new ArrayList<String>();
    gender=new ArrayList<String>();
    mobile=new ArrayList<String>();
    home=new ArrayList<String>();
    office=new ArrayList<String>();
    view = (ListView)findViewById(R.id.listview);
    mDialog=new ProgressDialog(this);   // Thread code
    mDialog.setMessage("Loading....");


    viewOrders =new Runnable()  // Thread code
    {
        public void run()       // Thread code
        {
            Json_function();
            runOnUiThread(returnRes);
        }
    };
    thread1=new Thread(null,viewOrders,"Bacground");
    thread1.start();
    mDialog.show();
}

private Runnable returnRes=new Runnable()   // Thread code
{

    @Override
    public void run()   // Thread code 
    {
    mDialog.cancel();

        for(int i=0;i<id.size();i++)
        {
            System.out.println("==========================");
            System.out.println("id : - " +id.get(i));
            System.out.println("name : - " +name.get(i));
            System.out.println("email : - " +email.get(i));
            System.out.println("address : - " +address.get(i));
            System.out.println("gender : - " +gender.get(i));
            System.out.println("mobile : - " +mobile.get(i));
            System.out.println("home : - " +home.get(i));
            System.out.println("office : - " +office.get(i));
        }   

        ArrayAdapter<String> adapter= new ArrayAdapter<String>(JSONParsingExampleActivity.this, android.R.layout.simple_list_item_1, name);

        view.setAdapter(new CustomAdapter(JSONParsingExampleActivity.this));        
    }       
};

private void Json_function() 
{
    String result=null;

    try
    {
        result=getDataFromWebService("http://api.androidhive.info/contacts/");
        System.out.println("length old--> " +result);
    }
    catch(Exception e)
    {

    }
    try
    {
        JSONObject json_data=new JSONObject(result);
        JSONArray json_array=json_data.getJSONArray("contacts");
        System.out.println("json array length : - " +json_array.length());

        for(int i=0;i<json_array.length();i++)
        {
            json_data=json_array.getJSONObject(i);

            id.add(json_data.getString("id"));
            name.add(json_data.getString("name"));
            email.add(json_data.getString("email"));
            address.add(json_data.getString("address"));
            gender.add(json_data.getString("gender"));

            String str= json_data.getString("phone");
            JSONObject json_data1 = new JSONObject(str);

            mobile.add(json_data1.getString("mobile"));
            home.add(json_data1.getString("home"));
            office.add(json_data1.getString("office"));
        }
    }
    catch(Exception e1)
    {
        e1.printStackTrace();
    }
}

public static String getDataFromWebService(String strUrl)
{
    StringBuffer strBuffer=new StringBuffer();
    InputStream is=null;

    try
    {
        System.out.println("getdata from web service url:--> " +strUrl);

        HttpClient httpclient=new DefaultHttpClient();
        HttpPost httppost=new HttpPost(strUrl);

        HttpResponse httpresponse=httpclient.execute(httppost);
        HttpEntity httpentity=httpresponse.getEntity();

        is=httpentity.getContent();

        int in=httpresponse.getStatusLine().getStatusCode();
        System.out.println("Response code:--> " +in);
    }
    catch(Exception e)
    {
        Log.e("log_tag", "Eroor in http connection" +e.toString());
    }
    try
    {
        int ch;

        while((ch=is.read())!=-1)
            strBuffer.append((char)ch);

        is.close();
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    return strBuffer.toString();
}

    public class CustomAdapter extends BaseAdapter {
    private Context mContext;
    Application app;
    private LayoutInflater inflater=null;

    public CustomAdapter(Context c) {
        mContext = c;
         inflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }   

    public int getCount() {
        return id.size();
    }

    public Object getItem(int position) {
        return null;
    }

    public long getItemId(int position) {
        return 0;
    }

    // create a new ImageView for each item referenced by the Adapter
    public View getView(int position, View convertView, ViewGroup parent) {

        View vi=convertView;
        if (convertView == null)        
             vi = inflater.inflate(R.layout.list, null);


        TextView txt=(TextView)vi.findViewById(R.id.txtview_id);
        TextView txt1=(TextView)vi.findViewById(R.id.txtview_name);
        TextView txt2=(TextView)vi.findViewById(R.id.txtview_email);
        TextView txt3=(TextView)vi.findViewById(R.id.txtview_address);
        TextView txt4=(TextView)vi.findViewById(R.id.txtview_gender);
        TextView txt5=(TextView)vi.findViewById(R.id.txtview_mobile);
        TextView txt6=(TextView)vi.findViewById(R.id.txtview_home);
        TextView txt7=(TextView)vi.findViewById(R.id.txtview_office);

        txt.setText("Id : " + id.get(position));
        txt1.setText("Name : " + name.get(position));
        txt2.setText("Email : " + email.get(position));
        txt3.setText("Address : " + address.get(position));
        txt4.setText("Gender : " + gender.get(position));
        txt5.setText("Mobile : " + mobile.get(position));
        txt6.setText("Home : " + home.get(position));
        txt7.setText("Office : " + office.get(position));

        return vi;
    };
}
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...