安卓:JSON来的ListView [英] Android: JSON to ListView

查看:216
本文介绍了安卓:JSON来的ListView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的PHP一个JSON传递给我的Andr​​oid应用程序。那么Android将填充JSON成的ListView 。该JSON已成功传递给我的Andr​​oid应用程序。但问题是,它一直就扔 NullPointerException异常给我。 IM都强调了,因为我已经花了很多次找我已经做了错误。下面是codeS:

 进口的java.util.ArrayList;
进口的java.util.List;进口org.apache.http.NameValuePair;
进口org.apache.http.message.BasicNameValuePair;
进口org.json.JSONArray;
进口org.json.JSONException;
进口org.json.JSONObject;进口android.app.Activity;
进口android.os.Bundle;
进口android.view.LayoutInflater;
进口android.view.View;
进口android.view.ViewGroup;
进口android.widget.ArrayAdapter;
进口android.widget.ImageView;
进口android.widget.ListView;
进口android.widget.TextView;
进口android.widget.Toast;公共类PlacesActivity延伸活动{清单<&地方GT;模型=新的ArrayList<&地方GT;();
PlacesAdapter适配器=新PlacesAdapter();
@燮pressWarnings(静态访问)
@覆盖
公共无效的onCreate(捆绑savedInstanceState){
    LV的ListView =(ListView控件)findViewById(R.id.placesListView);
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.places);    ArrayList的<&的NameValuePair GT; postParameters =新的ArrayList<&的NameValuePair GT;();
    postParameters.add(新BasicNameValuePair(请求,request_for_places));    串响应=无效;    尝试{
        响应= CustomHttpClient.executeHttpPost(http://www.test.com/requestPlaces.php,postParameters);
        字符串资源=响应;        尝试{
            JSONArray ARR =新JSONArray(RES);
            的for(int i = 0; I< arr.length();我++)
            {
                JSONObject的jsonObj = arr.getJSONObject(I)
                地方newPlace =新的地方();
                newPlace.setPlace(jsonObj.optString(\"placeID\"),jsonObj.optString(\"placeName\"),jsonObj.optString(\"placeType\"),jsonObj.optString(\"placeLat\"),jsonObj.optString(\"placeLng\"),jsonObj.optString(\"placePict\"));
                model.add(newPlace);
            }        }赶上(JSONException E){
            Toast.makeText(getApplicationContext(),:,Toast.LENGTH_LONG错误JSONException!).show();
        }        lv.setAdapter(适配器);
    }赶上(例外五){
        Toast.makeText(getApplicationContext(),E +,Toast.LENGTH_LONG).show();
    }
}类PlacesAdapter扩展ArrayAdapter<&地方GT;
{
    PlacesAdapter()
    {
        超(PlacesActivity.this,android.R.layout.simple_list_item_1,模型);
    }    公共查看getView(INT位置,查看convertView,父母的ViewGroup)
    {
        查看排= convertView;
        占位符持有人= NULL;        如果(行== NULL)
        {
            LayoutInflater吹气= getLayoutInflater();
            行= inflater.inflate(R.layout.row,父母,假);
            持有人=新的占位符(行);
        }
        其他
        {
            支架=(预留)row.getTag();
        }        holder.populateFrom(model.get(位置));        返回行;
    }
}静态类的占位符{    私人TextView的地名= NULL;
    私人TextView的placeType = NULL;
    私人ImageView的图标= NULL;    占位符(查看行){
        地名=(TextView中)row.findViewById(R.id.placeName);
        placeType =(TextView中)row.findViewById(R.id.placeType);
        图标=(ImageView的)row.findViewById(R.id.icon);
    }    无效populateFrom(宿P){
        placeName.setText(p.getPlaceName());
        placeType.setText(p.getType());        如果(p.getType()。等于(教育)){
            icon.setImageResource(R.drawable.ball_red);
        }
        否则,如果(p.getType()。等于(闲)){
            icon.setImageResource(R.drawable.ball_yellow);
        }
        其他{
            icon.setImageResource(R.drawable.ball_green);
        }        }
    }
}

这是JSON从PHP返回

  [{placeID:P0001,地名:英迪国际University\",\"placeType\":\"Education\",\"placeLat\":\"2.813997\",\"placeLng\":\"101.758229\",\"placePict\":\"http:\\/\\/test.com\\/placesImage\\/inti_iu.JPG\"},
{placeID:P0002,地名:汝来国际College\",\"placeType\":\"Education\",\"placeLat\":\"2.814179\",\"placeLng\":\"101.7700107\",\"placePict\":\"http:\\/\\/test.com\\/placesImage\\/nilai_uc.jpg\"}]

这是我的 Places.java

 公共类的地方{私人静态字符串地名;
私人静态字符串placeImg;
私人静态字符串placeLat;
私人静态字符串placeLng;
私人静态字符串placeType;
私人静态字符串placeID;公共场所()
{
   placeID =;
}
//设置方法
公共静态无效setPlace(字符串place_id,PLACE_NAME字符串,字符串place_type,字符串place_lat,字符串place_lng,字符串place_img){
    Places.placeName = PLACE_NAME;
    Places.placeID = place_id;
    Places.placeImg = place_img;
    Places.placeLat = place_lat;
    Places.placeLng = place_lng;
    Places.placeType = place_type;
}//获取方法
公共静态字符串getPlaceName(){
    返回地名;
}公共静态字符串getPlaceID(){
    返回placeID;
}公共静态字符串GETIMG(){
    返回placeImg;
}公共静态字符串getLat(){
    返回placeLat;
}公共静态字符串getLng(){
    返回placeLng;
}公共静态字符串的getType(){
    返回placeType;
}}

编辑:下面的logcat

  02-17 17:10:03.595:W / System.err的(1994年):显示java.lang.NullPointerException
02-17 17:10:03.615:W / System.err的(1994):在com.application.fyp.PlacesActivity.onCreate(PlacesActivity.java:50)
02-17 17:10:03.615:W / System.err的(1994):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072)
02-17 17:10:03.615:W / System.err的(1994):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1836)
02-17 17:10:03.615:W / System.err的(1994):在android.app.ActivityThread.startActivityNow(ActivityThread.java:1692)
02-17 17:10:03.625:W / System.err的(1994):在android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
02-17 17:10:03.625:W / System.err的(1994):在android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
02-17 17:10:03.625:W / System.err的(1994):在android.widget.TabHost $ IntentContentStrategy.getContentView(TabHost.java:656)
02-17 17:10:03.625:W / System.err的(1994):在android.widget.TabHost.setCurrentTab(TabHost.java:326)
02-17 17:10:03.625:W / System.err的(1994):在android.widget.TabHost $ 2.onTabSelectionChanged(TabHost.java:132)
02-17 17:10:03.625:W / System.err的(1994):在android.widget.TabWidget $ TabClickListener.onClick(TabWidget.java:458)
02-17 17:10:03.625:W / System.err的(1994):在android.view.View.performClick(View.java:2533)
02-17 17:10:03.625:W / System.err的(1994):在android.view.View $ PerformClick.run(View.java:9320)
02-17 17:10:03.635:W / System.err的(1994):在android.os.Handler.handleCallback(Handler.java:587)
02-17 17:10:03.635:W / System.err的(1994):在android.os.Handler.dispatchMessage(Handler.java:92)
02-17 17:10:03.635:W / System.err的(1994):在android.os.Looper.loop(Looper.java:150)
02-17 17:10:03.635:W / System.err的(1994):在android.app.ActivityThread.main(ActivityThread.java:4385)
02-17 17:10:03.635:W / System.err的(1994):在java.lang.reflect.Method.invokeNative(本机方法)
02-17 17:10:03.635:W / System.err的(1994):在java.lang.reflect.Method.invoke(Method.java:507)
02-17 17:10:03.635:W / System.err的(1994):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:849)
02-17 17:10:03.635:W / System.err的(1994):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
02-17 17:10:03.645:W / System.err的(1994):在dalvik.system.NativeStart.main(本机方法)


解决方案

我觉得这行的原因NPE。

  adapter.add(newPlace);

您错过了初始化的 PlacesAdapter适配器;

 适配器=新PlacesAdapter();

更新:

这么多错误,

第一:我上面提到的,

二:

 列表<&地方GT;模型=新的ArrayList<&地方GT;();

因此​​, adapter.add(newPlace); 此行应该是 model.add(newPlace);

第三:

有什么用适配器?意味着你在哪里设置适配器?任何的ListView GridView的还是?

问题看上去基本,你要看一看有关列表显示JSON数据..

的一些基本教程

编辑:

1

 列表<&地方GT;模型=新的ArrayList<&地方GT;();
PlacesAdapter适配器=新PlacesAdapter();

应该是

 列表<&地方GT;模型=新的ArrayList<&地方GT;();
PlacesAdapter适配器;

2

 的ListView LV =(ListView控件)findViewById(R.id.placesListView);
super.onCreate(savedInstanceState);
的setContentView(R.layout.places);

应该是

  super.onCreate(savedInstanceState);
的setContentView(R.layout.places);
LV的ListView =(ListView控件)findViewById(R.id.placesListView);

3。

  lv.setAdapter(适配器);

应该是,

 适配器=新PlacesAdapter();
lv.setAdapter(适配器);

谢谢..

I am trying to pass a JSON from my PHP to my Android app. Then the Android will populate the JSON into a ListView. The JSON has successfully been passed to my Android app. But the problem is, it keeps on throwing NullPointerException to me. Im all stressed out as I've been spending a lot of times looking for the error I've done. Below are the codes:

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

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

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class PlacesActivity extends Activity {

List<Places> model = new ArrayList<Places>();
PlacesAdapter adapter = new PlacesAdapter();


@SuppressWarnings("static-access")
@Override
public void onCreate(Bundle savedInstanceState) {
    ListView lv = (ListView) findViewById(R.id.placesListView);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.places);

    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("request","request_for_places"));

    String response = null;

    try{
        response = CustomHttpClient.executeHttpPost("http://www.test.com/requestPlaces.php", postParameters);
        String res = response;

        try{
            JSONArray arr = new JSONArray(res);
            for(int i = 0; i < arr.length(); i++)
            {
                JSONObject jsonObj = arr.getJSONObject(i);
                Places newPlace = new Places();
                newPlace.setPlace(jsonObj.optString("placeID"),jsonObj.optString("placeName"),jsonObj.optString("placeType"),jsonObj.optString("placeLat"),jsonObj.optString("placeLng"),jsonObj.optString("placePict"));
                model.add(newPlace);
            }

        }catch(JSONException e){
            Toast.makeText(getApplicationContext(), "Error : JSONException!", Toast.LENGTH_LONG).show();
        }

        lv.setAdapter(adapter);


    }catch(Exception e){
        Toast.makeText(getApplicationContext(), e+"", Toast.LENGTH_LONG).show();
    }
}

class PlacesAdapter extends ArrayAdapter<Places>
{
    PlacesAdapter()
    {
        super(PlacesActivity.this,android.R.layout.simple_list_item_1,model);
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
        View row = convertView;
        PlaceHolder holder = null;

        if(row == null)
        {
            LayoutInflater inflater = getLayoutInflater();
            row = inflater.inflate(R.layout.row, parent,false);
            holder = new PlaceHolder(row);
        }
        else
        {
            holder = (PlaceHolder)row.getTag();
        }

        holder.populateFrom(model.get(position));

        return row;
    }
}

static class PlaceHolder{

    private TextView placeName = null;
    private TextView placeType = null;
    private ImageView icon = null;

    PlaceHolder(View row){
        placeName = (TextView)row.findViewById(R.id.placeName);
        placeType =  (TextView)row.findViewById(R.id.placeType);
        icon = (ImageView)row.findViewById(R.id.icon);
    }

    void populateFrom(Places p){
        placeName.setText(p.getPlaceName());
        placeType.setText(p.getType());

        if(p.getType().equals("Education")){
            icon.setImageResource(R.drawable.ball_red);
        }
        else if (p.getType().equals("Leisure")){
            icon.setImageResource(R.drawable.ball_yellow);
        }
        else{
            icon.setImageResource(R.drawable.ball_green);
        }

        }
    }
}

This is the JSON returned from PHP:

[{"placeID":"p0001","placeName":"INTI International University","placeType":"Education","placeLat":"2.813997","placeLng":"101.758229","placePict":"http:\/\/test.com\/placesImage\/inti_iu.JPG"},
{"placeID":"p0002","placeName":"Nilai International College","placeType":"Education","placeLat":"2.814179","placeLng":"101.7700107","placePict":"http:\/\/test.com\/placesImage\/nilai_uc.jpg"}]

This is my Places.java

public class Places{

private static String placeName;
private static String placeImg;
private static String placeLat;
private static String placeLng;
private static String placeType;
private static String placeID;

public Places()
{
   placeID = "";
}


//set method
public static void setPlace(String place_id, String place_name, String place_type, String place_lat, String place_lng, String place_img) {
    Places.placeName = place_name;
    Places.placeID = place_id;
    Places.placeImg = place_img;
    Places.placeLat = place_lat;
    Places.placeLng = place_lng;
    Places.placeType = place_type;
}



//get methods
public static String getPlaceName(){
    return placeName;
}

public static String getPlaceID(){
    return placeID;
}

public static String getImg(){
    return placeImg;
}

public static String getLat(){
    return placeLat;
}

public static String getLng(){
    return placeLng;
}

public static String getType(){
    return placeType;
}

}

edit:logcat below

02-17 17:10:03.595: W/System.err(1994): java.lang.NullPointerException
02-17 17:10:03.615: W/System.err(1994):     at  com.application.fyp.PlacesActivity.onCreate(PlacesActivity.java:50)
02-17 17:10:03.615: W/System.err(1994):     at  android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1072)
02-17 17:10:03.615: W/System.err(1994):     at  android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1836)
02-17 17:10:03.615: W/System.err(1994):     at      android.app.ActivityThread.startActivityNow(ActivityThread.java:1692)
02-17 17:10:03.625: W/System.err(1994):     at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
02-17 17:10:03.625: W/System.err(1994):     at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
02-17 17:10:03.625: W/System.err(1994):     at     android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:656)
02-17 17:10:03.625: W/System.err(1994):     at android.widget.TabHost.setCurrentTab(TabHost.java:326)
02-17 17:10:03.625: W/System.err(1994):     at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:132)
02-17 17:10:03.625: W/System.err(1994):     at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:458)
02-17 17:10:03.625: W/System.err(1994):     at android.view.View.performClick(View.java:2533)
02-17 17:10:03.625: W/System.err(1994):     at android.view.View$PerformClick.run(View.java:9320)
02-17 17:10:03.635: W/System.err(1994):     at android.os.Handler.handleCallback(Handler.java:587)
02-17 17:10:03.635: W/System.err(1994):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-17 17:10:03.635: W/System.err(1994):     at android.os.Looper.loop(Looper.java:150)
02-17 17:10:03.635: W/System.err(1994):     at android.app.ActivityThread.main(ActivityThread.java:4385)
02-17 17:10:03.635: W/System.err(1994):     at java.lang.reflect.Method.invokeNative(Native Method)
02-17 17:10:03.635: W/System.err(1994):     at java.lang.reflect.Method.invoke(Method.java:507)
02-17 17:10:03.635: W/System.err(1994):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:849)
02-17 17:10:03.635: W/System.err(1994):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:607)
02-17 17:10:03.645: W/System.err(1994):     at dalvik.system.NativeStart.main(Native Method)

解决方案

I think this line cause NPE..

adapter.add(newPlace);

You missed to initialize PlacesAdapter adapter;

adapter = new PlacesAdapter();

Updated:

So many mistakes,

First: I mentioned above,

Second:

List<Places> model = new ArrayList<Places>();

So, adapter.add(newPlace); this line should be, model.add(newPlace);

Third:

Whats the use of Adapter? means where you set adapter? Any ListView or GridView?

Question looks basic, you have to take a look at some basic tutorial about display json data on list..

EDIT:

1.

List<Places> model = new ArrayList<Places>();
PlacesAdapter adapter = new PlacesAdapter();

it should be

List<Places> model = new ArrayList<Places>();
PlacesAdapter adapter;

2.

ListView lv = (ListView) findViewById(R.id.placesListView);
super.onCreate(savedInstanceState);
setContentView(R.layout.places);

it should be

super.onCreate(savedInstanceState);
setContentView(R.layout.places);
ListView lv = (ListView) findViewById(R.id.placesListView);

3.

lv.setAdapter(adapter);

it should be,

adapter = new PlacesAdapter();
lv.setAdapter(adapter);

Thanks..

这篇关于安卓:JSON来的ListView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆