0

I'm trying to do a JSON project in Android. This is my code.

For some reason the data isn't displayed in the TextBox as it runs. I'm not sure where I made it wrong.

This is the url from where am trying to grab data: http://cocoalabs.in/demo/ego/index.php/home/read_all_users

Am trying to grab 4 strings and display them to TextViews

This is my code:

MainActivity.Java

public class MainActivity extends Activity
{

static String CocoaInfo="http://cocoalabs.in/demo/ego/index.php/home/read_all_users";
static String clfName = "";
static String cllName = "";
static String clLocation = "";
static String clPh1 = "";


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

    //To perform background tasks, like grabbing info from website and write it to GUI
    new MyAsyncTask().execute();
}

public class MyAsyncTask extends AsyncTask<String, String, String>
{

    @Override
    protected String doInBackground(String... strings)
    {
        /*Get HTTP client that scores streaming uploads & Downloads
        Here download RESTful information from CocoaLabs URL*/
        DefaultHttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());

        /*Use POST method to grab from data from URL*/
        HttpPost httpPost = new HttpPost(CocoaInfo);

        /*Define type of service we're using - JSON service*/
        httpPost.setHeader("Content-type", "application/json");

        /*To Read data from URL*/
        InputStream inputStream = null;

        /*To hold all the data we get from URL*/
        String result = null;

        try
        {
            /*Asking for a response from the web service*/
            HttpResponse response = httpClient.execute(httpPost);

            /*Has the content from URL along with header and other info*/
            HttpEntity entity = response.getEntity();

            /*Get the main content from the URL*/
            inputStream = entity.getContent();

            /*Read data from the stream until buffer is full. Helps to grab in bunch*/
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"),8);

            /*Creating StringBuilder to store the read data*/
            StringBuilder theStringBuilder = new StringBuilder();

            /*For storing the read line*/
            String line = null;

            /*Read all the data from buffer until nothing is left*/
            while((line = reader.readLine())!=null)
            {
                /*Append each line to the Builder object*/
                theStringBuilder.append(line + "\n");
            }

            /*After finishing reading all the data*/
            result = theStringBuilder.toString();

        }

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

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

        finally
        {
            try
            {
                /*Close the InputStream*/
                if (inputStream!=null)
                    inputStream.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }

        /*Create JSON object to hold a bunch of key-value pairs from the JSON source*/
        JSONObject jsonObject;

        /*To print all the information we downloaded in the LogCat for debugging*/
        Log.v("JSONParser RESULT ", result);


        try
        {
            /*Get the JSON object with all the data*/
            jsonObject = new JSONObject(result);

            clfName = jsonObject.getString("fname");
            cllName = jsonObject.getString("lname");
            clLocation = jsonObject.getString("location");
            clPh1 = jsonObject.getString("ph1");

            Log.v("JSONParser RESULT", clfName);
            Log.v("JSONParser RESULT", cllName);
            Log.v("JSONParser RESULT", clLocation);
            Log.v("JSONParser RESULT", clPh1);

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

        return result;

    }

    //This method is called after all background tasks are done
    /*Writes all the information to the TextViews layout*/
    @Override
    protected void onPostExecute(String result)
    {
        /*Find the buttons on the screen*/
        TextView fNameTV = (TextView) findViewById(R.id.fNameTV);
        TextView lNameTV = (TextView) findViewById(R.id.lNameTV);
        TextView locationTV = (TextView) findViewById(R.id.locationTV);
        TextView ph1TV = (TextView) findViewById(R.id.ph1TV);

        /*Change the value to be displayed on TextViews*/
        fNameTV.setText("First Name is" +clfName);
        lNameTV.setText("Last Name is" +cllName);
        locationTV.setText("Location is" +clLocation);
        ph1TV.setText("Phone Number is" +clPh1);

    }
}

}

1
  • what is the logcat out put Commented Dec 2, 2014 at 9:20

5 Answers 5

5

That's because the given json is an array an not an object.

You need to convert if to an array before and iterate it:

JSONArray myArray = new JSONArray(result);

instead of

jsonObject = new JSONObject(result);

To iterate the array a simple for should do it:

  for( i=0;i<myArray.length();i++){
    JSONObject anObjectOfTheArray= myArray.getJSONObject(i);
    Log.v("CONTENT",anObjectOfTheArray.getString("uname"));
   }
Sign up to request clarification or add additional context in comments.

Comments

4

Try something like below:

try {
  JSONArray main = new JSONArray(responsestring);

  for( i=0;i<main.length();i++){
    JSONObject mainobj = main.getJSONObject(i);
    String uid = mainobj.getString("uid");
    String uname = mainobj.getString("uname");
   }
  } catch (JSONException e) {
       e.printStackTrace();
 }

2 Comments

Thank you for the fine answer. This was the simplest workaround. :)
Move the mainobj declaration outside of loop
0
    Actually that url contains JSONARRAY and inside jsonobject

    To get the jsonobject in the JSON array

         JSONObject object = jsonarray.getJSONObject(index);


    To get the values from JSON object

    Json values should be Key and value pair format 

        JSONObject myJson = new JSONObject(myJsonString);

        String name = myJson.get("name");

    **Example**

     String s = "{menu:{\"1\":\"sql\", \"2\":\"android\", \"3\":\"mvc\"}}";
        JSONObject jObject  = new JSONObject(s);
        JSONObject  menu = jObject.getJSONObject("menu");

        Map<String,String> map = new HashMap<String,String>();
        Iterator iter = menu.keys();
        while(iter.hasNext()){
            String key = (String)iter.next();
            String value = menu.getString(key);
            map.put(key,value);
        }
**FOR your thing, You have to do like this**

JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(inedx);
String uid= jObj.getString("uid");

call this in iteration for total number of objects.

Comments

0

I think from your end all the codes are correct but there is some problem with the Json you received. Can you please show the logcat message after running your app. I found that it gives Json exception. You need to check the json.

Comments

-1

Using this follwing class to get JSONObject :

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {
    static InputStream is = null;
    static JSONObject jarray = null;
    static String json = "";
    String result = null;

    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        System.out.println(url);
        try {
            System.out.println("httpGet:" + httpGet);
            HttpResponse response = client.execute(httpGet);
            System.out.println("response" + response);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(content));
                String line;
                while ((line = reader.readLine()) != null) {
                    builder.append(line);
                    result = builder.toString();
                    System.out.println(builder.toString());

                }
            } else {
                Log.e("==>", "Failed to download file");
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            jarray = new JSONObject(result);
        } catch (JSONException e1) {
            Log.e("JSON Parser", "Error parsing data " + e1.toString());
        }
        // return JSON String
        return jarray;

    }
}

put the following code in your do in background...

JSONObject c = JSONParser.getJSONFromUrl("put your url here");

try {
clfName= c.getString("fname");
cllName= c.getString("lname");
clLocation= c.getString("location");
clph1 = c.getString("ph1");

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.