DroidMatt
DroidMatt

Reputation: 183

Android: JSON to ListView

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)

Upvotes: 0

Views: 2198

Answers (4)

steevoo
steevoo

Reputation: 631

your exception come from this

     holder = (PlaceHolder)row.getTag();

cos u didn't initialize tag and is return null so in

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

change it and make it like that

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

and than it will work

Upvotes: 0

DroidMatt
DroidMatt

Reputation: 183

I've given up this way of doing what I'm suppose to do and end up trying the alternative way of doing it.

The tutorial on : Creating ListView based on JSON Object is a good tutorial.

Finally, thanks to those who helped me, and sorry for the trouble.

Upvotes: 0

just_user
just_user

Reputation: 12059

I changed your code a little bit, but I got it to work with this code.

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

Hope this helps!

EDIT: Changed to ListView instead of ListActivity!

Upvotes: 1

user370305
user370305

Reputation: 109237

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..

Upvotes: 3

Related Questions