0

I am new to android I am using the following code to parse the data and connect with the database and hence get the value present in the database which is present in the server.

The code which I am using is :-

package com.example.library;

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

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
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 jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    public JSONObject getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();          

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

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();         <------Here
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
   /* public void writeJSON() {
          JSONObject object = new JSONObject();
          try {
            object.put("name", "Prathamesh");
            object.put("score", new Integer(200));
            object.put("current", new Double(152.32));
            object.put("nickname", "Programmer");
          } catch (JSONException e) {
            e.printStackTrace();
          }
          System.out.println(object);
        } 
*/
}

I am using another code to use the value of json and display it.It is as follows:-

package com.example.library;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

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


public class SecondActivity extends Activity 
{

//url to make request
private static String url = "http://192.168.0.100:3000/users.json";

// JSON Node names
private static final String TAG_ID = "id";
private static final String TAG_FIRST = "first_name";
private static final String TAG_MIDDLE = "middle_name";
private static final String TAG_LAST = "last_name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_MOBILE = "mobile";

private static final String TAG_USERS = "user";

// users JSONArray
JSONArray users = null;



        @Override

    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tab_test1);


        // Hashmap for ListView
          ArrayList<HashMap<String, String>> userList = new ArrayList<HashMap<String, String>>();

            // Creating JSON Parser instance
            JSONParser jParser = new JSONParser();

            // getting JSON string from URL
            JSONObject json = jParser.getJSONFromUrl(url); <---url I am using is http://192.168.0.100:3000/users.json

            try {
                // Getting Array of Contacts
            users = json.getJSONArray(TAG_USERS);

                // looping through All Contacts
                for(int i = 0; i < users.length(); i++){
                    JSONObject c = users.optJSONObject(i);

                    // Storing each json item in variable
                    String id = c.getString(TAG_ID);
                    String first = c.getString(TAG_FIRST);
                    String middle = c.getString(TAG_MIDDLE);
                    String last = c.getString(TAG_LAST);
                    String email = c.getString(TAG_EMAIL);
                    String address = c.getString(TAG_ADDRESS);
                    String mobile = c.getString(TAG_MOBILE);




                    // creating new HashMap

                    HashMap<String, String> map = new HashMap<String, String>();

                    // adding each child node to HashMap key => value
                    map.put(TAG_ID, id);
                    map.put(TAG_FIRST, first);
                    map.put(TAG_MIDDLE,middle);
                    map.put(TAG_LAST, last);
                    map.put(TAG_ADDRESS, address);
                    map.put(TAG_MOBILE, mobile);
                    map.put(TAG_EMAIL, email);

                    // adding HashList to ArrayList
                    userList.add(map);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }

    }

My error log file is:-

04-30 16:24:05.697: E/AndroidRuntime(687): FATAL EXCEPTION: main
04-30 16:24:05.697: E/AndroidRuntime(687): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.library/com.example.library.SecondActivity}: java.lang.IllegalArgumentException: HTTP entity may not be null
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.app.ActivityThread.startActivityNow(ActivityThread.java:1487)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:127)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:339)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:654)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.widget.TabHost.setCurrentTab(TabHost.java:326)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.widget.TabHost$2.onTabSelectionChanged(TabHost.java:132)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.widget.TabWidget$TabClickListener.onClick(TabWidget.java:456)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.view.View.performClick(View.java:2485)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.view.View$PerformClick.run(View.java:9080)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.os.Handler.handleCallback(Handler.java:587)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.os.Handler.dispatchMessage(Handler.java:92)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.os.Looper.loop(Looper.java:123)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.app.ActivityThread.main(ActivityThread.java:3683)
04-30 16:24:05.697: E/AndroidRuntime(687):  at java.lang.reflect.Method.invokeNative(Native Method)
04-30 16:24:05.697: E/AndroidRuntime(687):  at java.lang.reflect.Method.invoke(Method.java:507)
04-30 16:24:05.697: E/AndroidRuntime(687):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-30 16:24:05.697: E/AndroidRuntime(687):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-30 16:24:05.697: E/AndroidRuntime(687):  at dalvik.system.NativeStart.main(Native Method)
04-30 16:24:05.697: E/AndroidRuntime(687): Caused by: java.lang.IllegalArgumentException: HTTP entity may not be null
04-30 16:24:05.697: E/AndroidRuntime(687):  at org.apache.http.util.EntityUtils.toString(EntityUtils.java:110)
04-30 16:24:05.697: E/AndroidRuntime(687):  at org.apache.http.util.EntityUtils.toString(EntityUtils.java:146)
04-30 16:24:05.697: E/AndroidRuntime(687):  at com.example.library.JSONParser.getJSONFromUrl(JSONParser.java:55)
04-30 16:24:05.697: E/AndroidRuntime(687):  at com.example.library.SecondActivity.onCreate(SecondActivity.java:51)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
04-30 16:24:05.697: E/AndroidRuntime(687):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)

While using the code json = sb.toString(); I am get the value.whereas json is calling some values from the database from the second code.

Please help me and let me know if there is anything wrong with the code

6
  • 1
    What is error? put logs here.. Commented Apr 30, 2013 at 9:44
  • @PankajKumar There is no such error.Just not getting any value in json = sb.toString(); Hence debugger stops at this point Commented Apr 30, 2013 at 9:47
  • @PeeVee Are you sure the charset is correct what is the url you are requesting? Commented Apr 30, 2013 at 9:50
  • @Emil The charset according to me is correct and the url I am requesting is url = "192.168.0.100:3000/users.json" Commented Apr 30, 2013 at 9:54
  • @PeeVee That is a private IP, can't do anything with that. But I believe that the JSON encoding should probably be UTF-8. Commented Apr 30, 2013 at 10:02

3 Answers 3

1
String retSrc = EntityUtils.toString(httpEntity); 
           // parsing JSON
JSONObject json = new JSONObject(retSrc); //Convert String to JSON Object

instead of

  try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();         <------Here
   } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
   }

Edit: I was aspectin you method will look like:

public JSONArray getJSONFromUrl(String url) {
     JSONArray json = null;
    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);

        HttpResponse httpResponse = httpClient.execute(httpGet);
        if (httpResponse != null && httpResponse.getStatusLine().getStatusCode() == 200) {
            HttpEntity httpEntity = httpResponse.getEntity();
            String retSrc = EntityUtils.toString(httpEntity); 
           // parsing JSON
            json = new JSONArray(retSrc); //Convert String to JSON Object
        }


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


    // return JSON String
    return json;

}
Sign up to request clarification or add additional context in comments.

27 Comments

now I am getting a null value at jObj = new JSONObject(json);
In the snippet I provided for you json is already a JsonObject. Can you check the vaule of "retSrc"
Please check the above edited question.If i make changes to Json.java it is giving error in other files
It stops (debugger) at JSONObject json = jParser.getJSONFromUrl(url); in the sondactivity.java
I see and what's the error? You can retrieve it through logcat
|
0

You can also use:

final String result = EntityUtils.toString(httpEntity);

instead of:

json = sb.toString();

Comments

0

My hunch is the charset is wrong, JSON should usually be in UTF-8, try :

BufferedReader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"), 1024);

Also increase the buffer size from 8 to 1024.

1 Comment

now I am getting a null value at jObj = new JSONObject(json);

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.