0

I would like to parse a json, I've managed to parse it in the onCreate but the app shows a blank screen for about 5-6 secs, so I've thought that i'll do some doInBackground and show a progressbar until the parsing is done.. but the app keeps on crashing with the OutOfBoundsExeption...

Here's my code :

public class MainActivity extends Activity {

private ArrayList<LatLng> markers = new ArrayList<LatLng>();
private LocationManager locationManager;

TextView text, distance, metric, warningTxt, speedTxt, kmh;
public double lat, lon;
private Location nearest;
private ArrayList<Location> cameras;

String answerstr;

public EditText editt;
public ImageView sign;

JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog progressBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
            .permitAll().build();
    StrictMode.setThreadPolicy(policy);
    text = (TextView) findViewById(R.id.text);

    new DownloadJSON().execute();

    cameras = new ArrayList<Location>();
    LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    LocationListener mlocListener = new MyLocationListener();

    mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
            mlocListener);
    mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
            0, mlocListener);

}

private class DownloadJSON extends AsyncTask<Void, Void, Void> {
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        progressBar = new ProgressDialog(MainActivity.this);
        progressBar.setTitle("Çek 1.5 JSON");
        progressBar.setMessage("Jsondan veriler çekiliyor...");
        progressBar.setIndeterminate(false);
        progressBar.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        jsonarray = JSONParser
                .getJSONfromURL("https://dl.dropboxusercontent.com/s/84el6b3mpgat7uj/aggie.json");

        try {
            for (int i = 0; i < jsonarray.length(); i++) {
                JSONObject row;
                row = jsonarray.getJSONObject(i);

                Location currentLoc;
                String camera;
                double lat, lon;

                camera = row.getString("name");
                lat = row.getDouble("latitude");
                lon = row.getDouble("longitude");
                currentLoc = new Location(camera);

                currentLoc.setLatitude(lat);
                currentLoc.setLongitude(lon);
                cameras.add(currentLoc);

            }
        } catch (NullPointerException ex) {
            ex.printStackTrace();
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(Void args) {

        progressBar.dismiss();
    }
}

public void sortByLocation(Location mycurrentlocation) {
    boolean swapped = true;
    while (swapped) {
        swapped = false;
        for (int i = 1; i < cameras.size(); i++) {
            if (cameras.get(i - 1).distanceTo(mycurrentlocation) > cameras
                    .get(i).distanceTo(mycurrentlocation)) {
                Location tmp = cameras.get(i);
                cameras.set(i, cameras.get(i - 1));
                cameras.set(i - 1, tmp);
                swapped = true;
            }
        }
    }
}

public Location getNearest() {
    nearest = cameras.get(0);
    return nearest;
}

// handles the menu.

public class MyLocationListener implements LocationListener

{

    @Override
    public void onLocationChanged(Location loc)

    {
        lat = loc.getLatitude();
        lon = loc.getLongitude();

        Location currentLocation = new Location("Current");
        currentLocation.setLatitude(lat);
        currentLocation.setLongitude(lon);
        LatLng tmp = new LatLng(loc.getLatitude(), loc.getLongitude());

        sortByLocation(currentLocation);
        text.setText(getNearest().getProvider());

        if (currentLocation.distanceTo(getNearest()) < 1000) {
            text.setTextColor(Color.RED);

        }

        else {

        }
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

}

}

And this is my logcat :

08-20 21:51:06.256: E/AndroidRuntime(26236): java.lang.IndexOutOfBoundsException:     Invalid index 0, size is 0
08-20 21:51:06.256: E/AndroidRuntime(26236):    at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
08-20 21:51:06.256: E/AndroidRuntime(26236):    at java.util.ArrayList.get(ArrayList.java:308)
08-20 21:51:06.256: E/AndroidRuntime(26236):    at com.finlaysmith.MotorcycleParking.MainActivity.getNearest(MainActivity.java:190)
08-20 21:51:06.256: E/AndroidRuntime(26236):    at com.finlaysmith.MotorcycleParking.MainActivity$MyLocationListener.onLocationChanged(MainActivity.java:217)
08-20 21:51:06.256: E/AndroidRuntime(26236):    at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:279)
08-20 21:51:06.256: E/AndroidRuntime(26236):    at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:208)
08-20 21:51:06.256: E/AndroidRuntime(26236):    at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:224)
08-20 21:51:06.256: E/AndroidRuntime(26236):    at android.os.Handler.dispatchMessage(Handler.java:102)
08-20 21:51:06.256: E/AndroidRuntime(26236):    at android.os.Looper.loop(Looper.java:136)
08-20 21:51:06.256: E/AndroidRuntime(26236):    at android.app.ActivityThread.main(ActivityThread.java:5001)
08-20 21:51:06.256: E/AndroidRuntime(26236):    at java.lang.reflect.Method.invokeNative(Native Method)
08-20 21:51:06.256: E/AndroidRuntime(26236):    at java.lang.reflect.Method.invoke(Method.java:515)
08-20 21:51:06.256: E/AndroidRuntime(26236):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
08-20 21:51:06.256: E/AndroidRuntime(26236):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
David
  • 11
  • 1
  • 5

3 Answers3

0
  • This could be the issue for you too:

Line -> JSONArray jArray=new JSONArray(result); giving nullpointer exception

Convert result to JSONObject before converting to JSONArray

  • Note that your JSON structure is bad:

    "anykey": [//this key is missing, so you cannot directly convert to JSONobject { "longitude": 4.424652, "latitude": 49.534077, "name": "Zone Danger 130 kmh", "free_bikes": "1", "empty_slots": "130", "id": "" }, { "longitude": 5.387198, "latitude": 45.173737, "name": "Zone Danger 130 kmh", "free_bikes": "1", "empty_slots": "130", "id": "" },....

use this to convert to JsonObject then to Json Array

 httpclient = new DefaultHttpClient();
            httppost = new HttpPost("https://dl.dropboxusercontent.com/s/84el6b3mpgat7uj/aggie.json");
            response = httpclient.execute(httppost);    // Execute HTTP Post Request
            inputStream = response.getEntity().getContent();
            String result=null;

            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream,         "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line=null;
            while((line=reader.readLine())!= null){
                sb.append(line+"\n");
            }

            inputStream.close();
            result=sb.toString();

 jObject = new JSONObject(result.trim());
        Iterator<?> keys = jObject.keys();

        while( keys.hasNext() ){
            String key = (String)keys.next();
            if( jObject.get(key) instanceof JSONObject ){

            }
        }
  • Please initialize ArrayList before you use it

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);
        text = (TextView) findViewById(R.id.text);
        cameras = new ArrayList<Location>();// before you start asynctask
        new DownloadJSON().execute();
    
  • Another thing I noticed: Please use getter/setter to access the private variable cameras, from inside the AsyncTask class.

Community
  • 1
  • 1
hrishitiwari
  • 634
  • 7
  • 15
  • share logcat so we can see where its crashing – hrishitiwari Aug 20 '14 at 19:45
  • i've put it my logcat! – David Aug 20 '14 at 19:55
  • You are initializing the cameras List after executing the Asynctask in Oncreate...thats the issue i think – hrishitiwari Aug 20 '14 at 20:09
  • It's logical don't you think ? – David Aug 20 '14 at 20:11
  • No because you are using cameras inside your Asynctask doinbackground...you should initialize it before you use it – hrishitiwari Aug 20 '14 at 20:12
  • When I parse the json inside the onCreate, everything works fine.. I don't ssee how can I initialize it before.. – David Aug 20 '14 at 20:15
  • see the updated answer, its just a matter of putting cameras = new ArrayList....before .execute() – hrishitiwari Aug 20 '14 at 20:17
  • I guess the only option is to debug line by line inside doinbackground...or put logs at every step to see why cameras is never filled with the json values – hrishitiwari Aug 20 '14 at 20:22
  • Here's something weird 08-20 22:25:30.636: W/System.err(32615): org.json.JSONException: No value for name 08-20 22:25:30.636: W/System.err(32615): at org.json.JSONObject.get(JSONObject.java:355) 08-20 22:25:30.636: W/System.err(32615): at org.json.JSONObject.getString(JSONObject.java:515) 08-20 22:25:30.636: W/System.err(32615): at com.finlaysmith.MotorcycleParking.MainActivity$DownloadJSON.doInBackground(MainActivity.java:131) there is a "name" in the json file.. – David Aug 20 '14 at 20:26
  • I think ur JSON array doesnt have a key ("somekey" outside the first [ bracket). For that case use this solution: http://stackoverflow.com/questions/9151619/java-iterate-over-jsonobject/10593838#10593838 – hrishitiwari Aug 20 '14 at 20:30
  • where contents will be the string you get back from the URL – hrishitiwari Aug 20 '14 at 20:31
  • what do you mean? Sorry my english is bit bad! – David Aug 20 '14 at 20:34
  • i've tried everything and it just won't work for some reason! – David Aug 20 '14 at 20:53
0

try this,

  JSONArray jsonObject = new  JSONArray("https://dl.dropboxusercontent.com/s/84el6b3mpgat7uj/aggie.json");
  JSONArray jArray= jsonObject.getJSONArray(0);
  for (int i = 0; i <jArray.length(); i++){   ...  }
hari
  • 1,874
  • 1
  • 16
  • 10
-1

try this: your problem caused by this line:

 08-20 21:51:06.256: E/AndroidRuntime(26236):    at com.finlaysmith.MotorcycleParking.MainActivity$MyLocationListener.onLocationChanged(MainActivity.java:217)

(MainActivity.java:217)

so i think you must set listener after you are sure the array has been filled

 @Override
protected void onPostExecute(Void args) {

    progressBar.dismiss();

LocationManager mlocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

LocationListener mlocListener = new MyLocationListener();

mlocManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
        mlocListener);
mlocManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
        0, mlocListener);
}
mmlooloo
  • 18,937
  • 5
  • 45
  • 64