user3006788
user3006788

Reputation: 165

android + json + how to display the extracted data in a list and when it clicked display the data in a single row?

i am creating a simple android app that get data from a webserver in json type and display it in a listView than when i select a row it must display the specified data in a single row but the problem is that the system show an error to the selected item to display it in the other activity.

can anyone help me ???

the error is in the jsonActivityHttpClient class in the onPostExectute method, it do not take the list "finalResult" neither:

 new String[] { PLACE_NAME_TAG, LATITUDE_TAG,LONGITUDE_TAG, POSTAL_CODE_TAG }

JSONParserHandler

package com.devleb.jsonparsingactivitydemo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.impl.client.BasicResponseHandler;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

public class JSONParserHandler implements ResponseHandler<List<String>> {

    public static List<String> finalResult;

    public static final String PLACE_NAME_TAG = "placeName";
    public static final String LONGITUDE_TAG = "lng";
    public static final String LATITUDE_TAG = "lat";
    private static final String ADMIN_NAME_TAG = "adminCode3";
    public static final String POSTAL_CODE_TAG = "postalcode";
    private static final String POSTALCODE = "postalcodes";

    @Override
    public List<String> handleResponse(HttpResponse response)
            throws ClientProtocolException, IOException {
        // TODO Auto-generated method stub

        finalResult = new ArrayList<String>();
        String JSONResponse = new BasicResponseHandler()
                .handleResponse(response);

        try {

            JSONObject jsonObject = (JSONObject) new JSONTokener(JSONResponse)
                    .nextValue();

            JSONArray PostalCodes = jsonObject.getJSONArray(POSTALCODE);

            for (int i = 0; i < PostalCodes.length(); i++) {
                JSONObject postalCode = (JSONObject) PostalCodes.get(i);


                String name = postalCode.getString(PLACE_NAME_TAG);
                String lat = postalCode.getString(LATITUDE_TAG);
                String lng = postalCode.getString(LONGITUDE_TAG);
                String postal = postalCode.getString(POSTAL_CODE_TAG);


                List<String>tmlResult =  new ArrayList<String>();

                tmlResult.add(name);
                tmlResult.add(lat);
                tmlResult.add(lng);
                tmlResult.add(postal);

                finalResult.addAll(tmlResult);




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

        return finalResult;
    }
}

JsonActivityHttpClient

package com.devleb.jsonparsingactivitydemo;

import java.io.IOException;
import java.util.List;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;

import android.app.ListActivity;
import android.content.Intent;
import android.net.http.AndroidHttpClient;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class JsonActivityHttpClient extends ListActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new HTTPGetTask().execute();
    }

    private class HTTPGetTask extends AsyncTask<Void, Void, List<String>> {

        private static final String USER_NAME = "devleb";

        private static final String URL = "http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username="
                + USER_NAME;

        AndroidHttpClient mClient = AndroidHttpClient.newInstance("");

        @Override
        protected List<String> doInBackground(Void... arg0) {
            // TODO Auto-generated method stub

            HttpGet request = new HttpGet(URL);

            JSONParserHandler responseHandler = new JSONParserHandler();
            try {

                return mClient.execute(request, responseHandler);

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return null;

        }

        protected void onPostExecute(Void result) {
            // TODO Auto-generated method stub

            if (null != mClient) {

                mClient.close();


                ListAdapter adapter = new SimpleAdapter(
                        JsonActivityHttpClient.this, finalResult,
                        R.layout.list_item, new String[] { PLACE_NAME_TAG, LATITUDE_TAG,
                                LONGITUDE_TAG, POSTAL_CODE_TAG }, new int[] { R.id.countryname,
                                R.id.lat, R.id.lng, R.id.postalcode });

                setListAdapter(adapter);
            }

                //setListAdapter(new ArrayAdapter<String>(
                    //  JsonActivityHttpClient.this, R.layout.list_item, result));

            }

        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.json_activity_http_client, menu);
        return true;
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        super.onListItemClick(l, v, position, id);


        String place_name = ((TextView) v.findViewById(R.id.countryname)).getText().toString();
        String lat = ((TextView) v.findViewById(R.id.lat)).getText().toString();
        String lng = ((TextView) v.findViewById(R.id.lng)).getText().toString();
        String postal_code = ((TextView) v.findViewById(R.id.postalcode)).getText().toString();


        Intent in = new Intent(getBaseContext(), RowItem.class);
        in.putExtra(PLACE_NAME_TAG, value)





    }

}

MainActivity

package com.devleb.jsonparsingactivitydemo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

    final @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final Button bntLoad = (Button) findViewById(R.id.btnload);

        bntLoad.setOnClickListener(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public void onClick(View arg0) {
        // TODO Auto-generated method stub

        startActivity(new Intent(getBaseContext(), JsonActivityHttpClient.class));
    }

}

RowItem

package com.devleb.jsonparsingactivitydemo;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class RowItem extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.row_item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.row_item, menu);
        return true;
    }

}

Upvotes: 0

Views: 256

Answers (1)

Shayan Pourvatan
Shayan Pourvatan

Reputation: 11948

i see 2 problem in your code:

1- you define your AsyncTask class like

AsyncTask<Void, Void, List<String>>

but you get Void on onPostExecute method, so you need change

protected void onPostExecute(Void result)

to

protected void onPostExecute(List<String> result)

2- you try access to finalResult on onPostExecute, bu you define that as static on JSONParserHandler so if you want access that you need :

JSONParserHandler.finalResult

but as you return that on doInBackground method so you can access that with:

result

that you get in onPostExecute.

then you need check result that is equal to null or not, because you return null after catch

your onPostExecute must be like:

protected void onPostExecute(List<String> result) {
            // TODO Auto-generated method stub

            if (null != mClient) {

                mClient.close();

             if (result != null)
             {
                ListAdapter adapter = new SimpleAdapter(
                        JsonActivityHttpClient.this, result,
                        R.layout.list_item, new String[] { PLACE_NAME_TAG, LATITUDE_TAG,
                                LONGITUDE_TAG, POSTAL_CODE_TAG }, new int[] { R.id.countryname,
                                R.id.lat, R.id.lng, R.id.postalcode });

                setListAdapter(adapter);
            }
            else
                // do any thing you want for error happened
            }

Upvotes: 2

Related Questions