Skip to content Skip to sidebar Skip to footer

Android Studio Unable To Plot Marker Using Json

I am trying to plot marker using json in which marker is not showing.here is my code of map activity. public class MapsActivity extends FragmentActivity implements OnMapReadyCallba

Solution 1:

Your issue is on retriveAndAddMarker. You're making a call using network thread that supposed to be run using AsyncTask.

Network operations can involve unpredictable delays. To prevent this from causing a poor user experience, always perform network operations on a separate thread from the UI. The AsyncTask class provides one of the simplest ways to fire off a new task from the UI thread - Android Developers [Perform Network Operations on a Separate Thread]

You can try adding this snippet:

privateclassRetrieveMarkerTaskextendsAsyncTask<StringBuilder, Void, StringBuilder> {

    private Context context;

    publicRetrieveMarkerTask(Context context){
        this.context = context;
    }

    @Overrideprotected StringBuilder doInBackground(StringBuilder... stringBuilders) {
        HttpURLConnectionconn=null;
        finalStringBuilderjson=newStringBuilder();
        try {
            //connect to the web serviceURLurl=newURL("http://www.loofre.com/api-for-webservice/?debug=true&action=getLocations");
            conn = (HttpURLConnection) url.openConnection();
            InputStreamReaderin=newInputStreamReader(conn.getInputStream());
            //This will read the json data into string builderint read;
            char[] buff = newchar[1024];
            while ((read = in.read(buff)) != -1) {
                json.append(buff, 0, read);
            }
        } catch (IOException e) {
            returnnull;
        } finally {
            if (conn != null)
                conn.disconnect();

        }
        return json;
    }

    @OverrideprotectedvoidonPostExecute(StringBuilder stringBuilder) {
        super.onPostExecute(stringBuilder);

        if(null != stringBuilder){
            try {
                ((MapsActivity)context).createMarkerFromJson(stringBuilder.toString());
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }
}

And in your retriveAndAddMarker(), remove all those lines inside this method and replace with line below.

protectedvoidretriveAndAddMarker (){
    //remove all the previous codenew RetrieveMarkerTask(this).execute();
}

Note: I simply created the AsyncTask based on your code, so I am not sure if it is working or not. You need to debug it on your own.

Post a Comment for "Android Studio Unable To Plot Marker Using Json"