Search code examples
androidjsonandroid-intentandroid-broadcastreceiver

Error receiving broadcast Intent { act=location_update flg=0x10 (has extras) } with JSONObject


I'm trying to parse a JSONObject inside a BroadcastReceiver ,and my app keeps crushing showing me this error Error receiving broadcast Intent { act=location_update flg=0x10 (has extras) } on line 122 (JSONObject jsonObject= new JSONObject(json_string);) Though , when I remove all the parsing part everything goes well. Here is the necessary code :

@Override
protected void onResume() {
    super.onResume();
    if(broadcastReceiver == null){
        broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                try {
                    getJSON();
                    JSONObject jsonObject= new JSONObject(json_string);
                    JSONArray jsonArray = jsonObject.getJSONArray("response");

                    int i=0 ;
                    Double latitude, longitude;
                    while (i<jsonArray.length()){
                        JSONObject jo= jsonArray.getJSONObject(i);
                        latitude = jo.getDouble("latitude");
                        longitude = jo.getDouble("longitude");
                        map.addMarker(new MarkerOptions()
                                .position(new LatLng(latitude,longitude))
                                .icon(BitmapDescriptorFactory.fromResource(R.drawable.taxi))
                                .title("taxi"));
                        i++;
                } }catch (JSONException e) {
                    e.printStackTrace();
                }

                lngg= intent.getDoubleExtra("longitude",-1);
                latt= intent.getDoubleExtra("latitude",-1);

                map.addMarker(new MarkerOptions()
                        .position(new LatLng(latt,lngg))
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.locationpeople1))
                        .title("I am here "));
            }
        };
    }
    registerReceiver(broadcastReceiver, new IntentFilter("location_update"));

}

public void getJSON(){
new BackgroundTask().execute();

}


class BackgroundTask extends AsyncTask<Void,Void,String>{
    String JSON_STRING;
    String json_url ;
    @Override
    protected void onPreExecute() {

        json_url="http://frequentative-hicko.000webhostapp.com/A.php";
    }

    @Override
    protected String doInBackground(Void... voids) {

        try {
            URL url = new URL(json_url);
            HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader= new BufferedReader( new InputStreamReader(inputStream));
            StringBuilder stringBuilder= new StringBuilder();
            while( (JSON_STRING = bufferedReader.readLine()) != null ){

             stringBuilder.append(JSON_STRING+"\n");
            }
            bufferedReader.close();
            inputStream.close();
            httpURLConnection.disconnect();
            return stringBuilder.toString().trim();




        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
       // TextView textView =(TextView) findViewById(R.id.textView2);
       // textView.setText(result); //JSON Format
        json_string=result;
    }
}
public  void parseJSON(View view){
  if(json_string == null){
      Toast.makeText(getApplicationContext(),"Aucun taxi n'est disponible pour l'instant",Toast.LENGTH_LONG);
  }
  }
}

Solution

  • I don't know when you send your broadcast, but here's the problem: when you call your getJSON you're telling android to run an instance of your BackgroundTask in another thread. So he executes your

    JSONObject jsonObject= new JSONObject(json_string); // and all the rest
    

    before your getJSON() finishes. Please try to move all your logic that is after getJSON() to your onPostExecute()

    Something like this:

    @Override
    protected void onPostExecute(String result) {
       // This is called when you finish your background task
       // so here is the right place to parse your json response and add yout markers :)
        json_string=result;
        try {
            JSONObject jsonObject= new JSONObject(json_string);
            JSONArray jsonArray = jsonObject.getJSONArray("response");
    
            int i=0 ;
            Double latitude, longitude;
            while (i<jsonArray.length()){
                JSONObject jo= jsonArray.getJSONObject(i);
                latitude = jo.getDouble("latitude");
                longitude = jo.getDouble("longitude");
                map.addMarker(new MarkerOptions()
                        .position(new LatLng(latitude,longitude))
                        .icon(BitmapDescriptorFactory.fromResource(R.drawable.taxi))
                        .title("taxi"));
                i++;
            }
    
        } catch (JSONException e) {
            e.printStackTrace();
        }
    
    }
    

    And in your onReceive something like this:

    @Override
    public void onReceive(Context context, Intent intent) {
    
        getJSON();
        lngg= intent.getDoubleExtra("longitude",-1);
        latt= intent.getDoubleExtra("latitude",-1);
    
        map.addMarker(new MarkerOptions()
                .position(new LatLng(latt,lngg))
                .icon(BitmapDescriptorFactory.fromResource(R.drawable.locationpeople1))
                .title("I am here "));
    }