-4

I have such json:

[
   {
      "bank":{
         "central_office_address":"ddd",
         "license":"12312312",
         "location_id":3,
         "name":"prior",
         "tax_number":"12312312",
         "year_of_foundation":1987
      }
   }
]

and i try to parse it like here: http://p-xr.com/android-tutorial-how-to-parse-read-json-data-into-a-android-listview/

i do this in education and learning-testing interests.

my activity:

package com.example.tespapp;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView tvHello;

    private static String url = "http://localhost/denwer/banks.json";

    // JSON Node names


    JSONArray contacts = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tvHello = (TextView) findViewById(R.id.textView1);



    }

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

    public void onClick(View v){
        tvHello.setText("Hello Kitty!");



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

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

        // getting JSON string from URL
        JSONObject json = jParser.getJSONFromUrl(url);


    }





}

JSONParser is same as in link below....

But i can't parse or even see it.... On click my app crashes(

In catlog i see:

04-05 16:30:43.713: E/Trace(1218): error opening trace file: No such file or directory (2)
04-05 16:30:44.943: D/libEGL(1218): loaded /system/lib/egl/libEGL_emulation.so
04-05 16:30:44.953: D/(1218): HostConnection::get() New Host Connection established 0x2a149640, tid 1218
04-05 16:30:45.113: D/libEGL(1218): loaded /system/lib/egl/libGLESv1_CM_emulation.so
04-05 16:30:45.123: D/libEGL(1218): loaded /system/lib/egl/libGLESv2_emulation.so
04-05 16:30:45.433: W/EGL_emulation(1218): eglSurfaceAttrib not implemented
04-05 16:30:45.803: D/OpenGLRenderer(1218): Enabling debug mode 0
04-05 16:31:29.633: D/AndroidRuntime(1218): Shutting down VM
04-05 16:31:29.633: W/dalvikvm(1218): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
04-05 16:31:29.703: E/AndroidRuntime(1218): FATAL EXCEPTION: main
04-05 16:31:29.703: E/AndroidRuntime(1218): java.lang.IllegalStateException: Could not execute method of the activity
04-05 16:31:29.703: E/AndroidRuntime(1218):     at android.view.View$1.onClick(View.java:3599)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at android.view.View.performClick(View.java:4204)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at android.view.View$PerformClick.run(View.java:17355)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at android.os.Handler.handleCallback(Handler.java:725)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at android.os.Handler.dispatchMessage(Handler.java:92)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at android.os.Looper.loop(Looper.java:137)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at android.app.ActivityThread.main(ActivityThread.java:5041)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at java.lang.reflect.Method.invokeNative(Native Method)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at java.lang.reflect.Method.invoke(Method.java:511)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at dalvik.system.NativeStart.main(Native Method)
04-05 16:31:29.703: E/AndroidRuntime(1218): Caused by: java.lang.reflect.InvocationTargetException
04-05 16:31:29.703: E/AndroidRuntime(1218):     at java.lang.reflect.Method.invokeNative(Native Method)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at java.lang.reflect.Method.invoke(Method.java:511)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at android.view.View$1.onClick(View.java:3594)
04-05 16:31:29.703: E/AndroidRuntime(1218):     ... 11 more
04-05 16:31:29.703: E/AndroidRuntime(1218): Caused by: android.os.NetworkOnMainThreadException
04-05 16:31:29.703: E/AndroidRuntime(1218):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at java.net.InetAddress.getAllByName(InetAddress.java:214)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at com.example.tespapp.JSONParser.getJSONFromUrl(JSONParser.java:38)
04-05 16:31:29.703: E/AndroidRuntime(1218):     at com.example.tespapp.MainActivity.onClick(MainActivity.java:68)
04-05 16:31:29.703: E/AndroidRuntime(1218):     ... 14 more
04-05 16:31:32.023: I/Process(1218): Sending signal. PID: 1218 SIG: 9

also i try other json, other link....

brabertaser19
  • 5,678
  • 16
  • 78
  • 184

2 Answers2

1

Your root problem here is this :

android.os.NetworkOnMainThreadException

You cannot perform long-running network operations on the UI thread in android. The OS is preventing you from doing so, which is preventing you from getting the json object in the first place, which causing all of the other exceptions to be thrown.

You need to create an AsyncTask (or some other type of thread) in which to handle your network operations. Then, you create an instance of that class and call the execute() method on it in the main thread.

Here's the doc for AsyncTasks

drew moore
  • 31,565
  • 17
  • 75
  • 112
1

Just for the test / code to run: (not recommended on a real project)

Try to test the code on an emulator/device with android OS lower than 4+ where is added not allowing connections on the main UI thread! This is visible by log line Caused by: android.os.NetworkOnMainThreadException


Real solution:

You need to add an AsyncTask or a Thread and perform the connection in that:

look here: AsyncTask Android example

To make it work change

public void onClick(View view){ 
    new LongOperation().execute("");
}

And also add an inner class:

private class LongOperation extends AsyncTask<String, Void, JSONObject> {

      @Override
      protected JSONObject doInBackground(String... params) {
          // Hashmap for ListView
          ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
          try {
             // Creating JSON Parser instance
             JSONParser jParser = new JSONParser();

             // getting JSON string from URL
             JSONObject json = jParser.getJSONFromUrl(url);
          } catch(Exception ex) { // many diffent exceptions better handle seperatelly
              Log.e("error", "error", ex);
              return null;
          }

            return json;
      }      

      @Override
      protected void onPostExecute(JSONObject result) {

            // do smth with the result
            String str = (json == null)?"json = null":json.toString(4);
            tvHello.setText(str);
      }

}   
Community
  • 1
  • 1
madlymad
  • 6,367
  • 6
  • 37
  • 68