【问题标题】:Android: JSON to ListViewAndroid:JSON 到 ListView
【发布时间】:2012-02-17 08:52:36
【问题描述】:

我正在尝试将 JSON 从我的 PHP 传递到我的 Android 应用程序。然后 Android 会将 JSON 填充到 ListView 中。 JSON 已成功传递到我的 Android 应用程序。但问题是,它不断向我抛出NullPointerException。由于我花了很多时间寻找我所犯的错误,我都感到压力很大。以下是代码:

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);
        }

        }
    }
}

这是 PHP 返回的 JSON

[{"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"}]

这是我的 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 下面

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)

【问题讨论】:

  • NPE 扔到哪里去了?
  • PlacesActivity 在外部 try-catch 语句上。我无法找出导致 NPE 的原因。
  • 只需给出堆栈跟踪
  • 非常感谢 LogCat 输出
  • 适配器 = 新 PlacesAdapter();请将此行添加到您的 on create mehtod 中。

标签: android json listview


【解决方案1】:

我认为这条线会导致 NPE..

adapter.add(newPlace);

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

adapter = new PlacesAdapter();

更新:

很多错误,

首先:我上面提到过,

第二:

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

所以,adapter.add(newPlace); 这一行应该是,model.add(newPlace);

第三:

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

问题看起来很基础,你必须看看一些关于在列表上显示json数据的基本教程..

编辑:

1.

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

应该是

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

2.

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

应该是

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

3.

lv.setAdapter(adapter);

应该是,

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

谢谢..

【讨论】:

  • 尝试初始化,当我尝试运行它时,它导致整个程序崩溃。
  • 您好,我已经进行了相应的更改,仍然得到 NPE。你能帮我看看需要做的任何可能的改变吗?
  • 进行了必要的更改,但仍然抛出 NPE。我认为这是由 lv.setAdapter(adapter) 引起的,知道吗? :(
  • 看看这个例子Android Putting Custom Objects in ListView 并按照上面提到的那样制作适配器。
【解决方案2】:

我稍微更改了您的代码,但我让它可以使用此代码。

public class MainActivity extends Activity {

List<Places> model;
PlacesAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ListView lv = (ListView) findViewById(R.id.listView1);

    model = new ArrayList<Places>();
    adapter = new PlacesAdapter();
    try {
        List<NameValuePair> pairs = new ArrayList<NameValuePair>();
        pairs.add(new BasicNameValuePair("whatever", "XXXX"));
        JSONArray jArray = connectToServer("http://www.example.com/get.php", pairs);
        try {
            for (int i = 0; i < jArray.length(); i++) {
                JSONObject jsonObj = jArray.getJSONObject(i);
                Places newPlace = new Places();
                Places.setPlace(jsonObj.optString("name"),
                        jsonObj.optString("name"),
                        jsonObj.optString("name"),
                        jsonObj.optString("name"),
                        jsonObj.optString("name"),
                        jsonObj.optString("name"));
                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(MainActivity.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.textView1);
        placeType = (TextView) row.findViewById(R.id.textView1);
        icon = (ImageView) row.findViewById(R.id.imageView1);
    }

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

        if (Places.getType().equals("Education")) {
            icon.setImageResource(R.drawable.ic_launcher);
        } else if (Places.getType().equals("Leisure")) {
            icon.setImageResource(R.drawable.ic_launcher);
        } else {
            icon.setImageResource(R.drawable.ic_launcher);
        }

    }
}

public static JSONArray connectToServer(String address, List<NameValuePair> valuePairs) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(address);
    try {           
        httppost.setEntity(new UrlEncodedFormEntity(valuePairs));
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStream is = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"UTF8"),8);
        StringBuilder sb = new StringBuilder();
        sb.append(reader.readLine() + "\n");
        String line="0";
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        String result = sb.toString();
        JSONArray array = new JSONArray(result);
        return array;
    } catch(Exception e){
        Log.e("log_tag", "Error converting result "+e.toString());
        return null;
    }
}
}

希望这会有所帮助!

编辑:改为 ListView 而不是 ListActivity!

【讨论】:

  • 嗨,我似乎在您的代码段中找不到 setListAdapter(adapter) 方法。
  • 在这个例子中我改为 ListActivity 所以如果你保持你的列表视图它应该和 lv.setAdapter(adapter);
  • 你好,我在一个新项目上尝试了你的代码,结果它返回 NullPointerException ...你能把整个项目发给我吗? :(
  • 当然,这里是源文件的链接:link@Matt_K
【解决方案3】:

我已经放弃了这种方式来做我应该做的事情,并最终尝试了另一种方式。

Creating ListView based on JSON Object 上的教程是一个很好的教程。

最后,感谢帮助过我的人,给您带来的麻烦深表歉意。

【讨论】:

    【解决方案4】:

    你的例外来自这个

         holder = (PlaceHolder)row.getTag();
    

    因为你没有初始化标签并且返回 null 所以在

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

    改变它,让它变成那样

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

    而且它会起作用

    【讨论】:

      猜你喜欢
      • 2012-05-22
      • 1970-01-01
      • 2016-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多