-2

I have tried to Parse JSON from URL.This is my code where it calls JSONParser class.While running this it TOAST a MESSAGE "MAIN" where i have toasted it in catch block.

MainActivity.java

    Button click;
    TextView tv;
    JSONParser jsonParser;
    private static String url="http://webtest.freevar.com/brand.php";
    private static final String TAG_SUCCESS="success";
    private static final String TAG_RESULT="result";
    private static final String TAG_MODELNAME="F_MOB_MODEL_NAME";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    click=(Button)findViewById(R.id.button1);
    tv=(TextView)findViewById(R.id.textView1);
    click.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Brand_list();
        }
    });

    }


    public void Brand_list(){

        List<NameValuePair> params = new ArrayList<NameValuePair>();

        params.add(new BasicNameValuePair("bname","BRAND_HTC"));


        try{
        JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
        Log.d("Response",json.toString());
        try {
            int success=json.getInt(TAG_SUCCESS);
        if(success==1){
            Log.d("success",json.toString());


            try{


                JSONArray result=json.getJSONArray(TAG_RESULT);
                for(int i=0;i<result.length();i++){
                    JSONObject get=result.getJSONObject(i);
                    String name=get.getString(TAG_MODELNAME);
                    tv.append("F_MOB_MODEL_NAME"+name+"\n");

                }   }
            catch(Exception e){
            Toast.makeText(getApplicationContext(), "error1", 400).show();  
            }
            }
                }
        catch (JSONException ej) {
            // TODO Auto-generated catch block
            ej.printStackTrace();
            Toast.makeText(getApplicationContext(), "error", 300).show();   
        }
        }
        catch(RuntimeException eq){
            Toast.makeText(getApplicationContext(), "main", Toast.LENGTH_LONG).show();

        }




    }

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

JSONParser.java

    static InputStream isdata = null;
    static JSONObject jObj = null;
    static String json = "";


    public JSONParser() 
    {

    }


    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params) {


        try {


            if(method == "POST")
            {

                DefaultHttpClient httpClient = new DefaultHttpClient();
                HttpPost httpPost = new HttpPost(url);

                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                isdata = httpEntity.getContent();

                }


            else if(method == "GET"){

                DefaultHttpClient httpClient = new DefaultHttpClient();
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

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

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

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


        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }


        return jObj;

    }
}

Check the Link where i am getting my response

http://www.webtest.freevar.com/brand.php


This is my LOG CAT


06-05 13:58:35.106: W/asset(20165): Copying FileAsset 0x455d0708 (zip:/data/app/com.example.brand-2.apk:/resources.arsc) to buffer size 2276 to make it aligned. 06-05 13:58:35.516: I/Adreno-EGL(20165): : EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.082_msm8974_refs/tags/AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.082__release_AU () 06-05 13:58:35.516: I/Adreno-EGL(20165): OpenGL ES Shader Compiler Version: E031.24.00.06 06-05 13:58:35.516: I/Adreno-EGL(20165): Build Date: 02/18/14 Tue 06-05 13:58:35.516: I/Adreno-EGL(20165): Local Branch: 06-05 13:58:35.516: I/Adreno-EGL(20165): Remote Branch: refs/tags/AU_LINUX_ANDROID_KK_3.5_RB1.04.04.02.006.082 06-05 13:58:35.516: I/Adreno-EGL(20165): Local Patches: NONE 06-05 13:58:35.516: I/Adreno-EGL(20165): Reconstruct Branch: NOTHING 06-05 13:58:39.116: E/AndroidRuntime(20165): FATAL EXCEPTION: main 06-05 13:58:39.116: E/AndroidRuntime(20165): Process: com.example.brand, PID: 20165 06-05 13:58:39.116: E/AndroidRuntime(20165): java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference 06-05 13:58:39.116: E/AndroidRuntime(20165): at com.example.brand.MainActivity.Brand_list(MainActivity.java:88) 06-05 13:58:39.116: E/AndroidRuntime(20165): at com.example.brand.MainActivity$1.onClick(MainActivity.java:43) 06-05 13:58:39.116: E/AndroidRuntime(20165): at android.view.View.performClick(View.java:4480) 06-05 13:58:39.116: E/AndroidRuntime(20165): at android.view.View$PerformClick.run(View.java:18686) 06-05 13:58:39.116: E/AndroidRuntime(20165): at android.os.Handler.handleCallback(Handler.java:733) 06-05 13:58:39.116: E/AndroidRuntime(20165): at android.os.Handler.dispatchMessage(Handler.java:95) 06-05 13:58:39.116: E/AndroidRuntime(20165): at android.os.Looper.loop(Looper.java:157) 06-05 13:58:39.116: E/AndroidRuntime(20165): at android.app.ActivityThread.main(ActivityThread.java:5872) 06-05 13:58:39.116: E/AndroidRuntime(20165): at java.lang.reflect.Method.invoke(Native Method) 06-05 13:58:39.116: E/AndroidRuntime(20165): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858) 06-05 13:58:39.116: E/AndroidRuntime(20165): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674)

4 Answers4

0

Its fast better yo use volley then to make manual httprequest ...volley can do all these nasty stuff for you.

Android volley is a networking library was introduced to make networking calls much easier, faster without writing tons of code. By default all the volley network calls works asynchronously, so we don’t have to worry about using asynctask anymore.

Volley comes with lot of features. Some of them are

  1. Request queuing and prioritization
  2. Effective request cache and memory management
  3. Extensibility and customization of the library to our needs
  4. Cancelling the requests

you can get more details on volley at http://www.androidhive.info/2014/05/android-working-with-volley-library-1/

and http://www.androidhive.info/2014/09/android-json-parsing-using-volley/

kumar kundan
  • 2,027
  • 1
  • 27
  • 41
0

Use some libraries to parse the json dont parse it yourself. Use something like gson https://github.com/google/gson and here is a example to fetch json from a rest service and parse it using gson http://kylewbanks.com/blog/Tutorial-Android-Parsing-JSON-with-GSON

Kalyan
  • 612
  • 6
  • 20
0

Make an HTTP request with android Here , check the first answer .

For networking you can use AsyncTask(as inner class) that will run it in a separate thread as follows :

 @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
       new BrandListTask().execute();
    }
});

}


   public class BrandListTask extends AsyncTask<String,Void,String>{

  @Override
    protected String doInBackground(String... params) {
       List<NameValuePair> params = new ArrayList<NameValuePair>();

       params.add(new BasicNameValuePair("bname","BRAND_HTC"));


      try{
       JSONObject json = jsonParser.makeHttpRequest(url, "POST", params);
    Log.d("Response",json.toString());
         try {
            int success=json.getInt(TAG_SUCCESS);
             if(success==1){
    Log.d("success",json.toString());


            try{

           JSONArray result=json.getJSONArray(TAG_RESULT);
             for(int i=0;i<result.length();i++){
                 JSONObject get=result.getJSONObject(i);
                   String name=get.getString(TAG_MODELNAME);
                   tv.append("F_MOB_MODEL_NAME"+name+"\n");

            }

  }  catch(Exception e){
  // use Log.d("","");  here , you cannot Toast from inside a background thread
        //Toast.makeText(getApplicationContext(), "error1", 400).show();  
        }
     }
            }catch (JSONException ej) {
        // TODO Auto-generated catch block
        ej.printStackTrace();
        //Toast.makeText(getApplicationContext(), "error", 300).show(); 
    // use Log.d("","");  here , you cannot Toast from inside a background thread  
    }
    }
    catch(RuntimeException eq){
        //Toast.makeText(getApplicationContext(), "main",  Toast.LENGTH_LONG).show();
    // use Log.d("","");  here , you cannot Toast from inside a background thread

      }
     }
 return null;
    }

   protected void onPostExecute(String s) { 
        super.onPostExecute(s);
    }
  }    //end of inner class

Also , if(method == "POST") ? No !

if(method.equals("POST"))

Community
  • 1
  • 1
devcodes
  • 1,038
  • 19
  • 38
0

I would suggest you to use Volley Library for network calls, and then make the JSON parsing your own if the API is not so stable to produce the same kind of JSON data for every request. If you get same kind of response every time then you can use GSON or Jackson parser.

But remember to call the network not on the UI thread.