-1

I have an async task that fetches a JSON array from a url and then parses it to a String.

My problem is that i cannot move the fetched data from URL to my Google Maps activity (Map Activity). When i tried Intent in Asynctask i could not make it.

Please help!! Thanks in advance

Async Task:

package com.example.panos.fleet_management;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;

import org.json.JSONException;
import org.json.JSONObject;

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.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.json.JSONArray;
import org.json.JSONException;


import static android.app.PendingIntent.getActivity;
import static android.content.ContentValues.TAG;
import static android.support.v4.content.ContextCompat.startActivity;

/**
 * Created by panos on 18/8/2018.
 */
public class MapRequest extends AsyncTask<Void,Void, Void> {

    String data="";
String dataParsed="";
String singleParsed="";
double lon[],lat[];
String reg;

private Context context;

public MapRequest(Context context){
    this.context=context;
}

@Override
    protected Void doInBackground(Void... params) {

        try {
        URL url= new URL("xxx.xxx");
        HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
        InputStream inputStream= httpURLConnection.getInputStream() ;
        BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(inputStream));
        String line= "";
        while(line != null) {
            line = bufferedReader.readLine();
            data=data + line;
        }

        JSONArray JA=new JSONArray(data);
        for (int i=0;i<JA.length();i++){
            JSONObject JO= (JSONObject) JA.get(i);
            singleParsed="Registration:"+ JO.get("Registration") + "\n"+
                         "Longitude:"+ JO.get("Longitude") + "\n"+
                         "Latitude:"+ JO.get("Latitude") + "\n";
            dataParsed= dataParsed + singleParsed + "\n";
        }

    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return null;
}

@Override
    protected void onPostExecute(Void aVoid) {

    super.onPostExecute(aVoid);
    Intent intent = new Intent(context, MapActivity.class);
    intent.putExtra("dat",dataParsed);
}
}

JSON File

[{
    "Registration": "YHB6595",
    "Longitude": "11.00000000",
    "Latitude": "3.00000000"
}, {
    "Registration": "YMK3540",
    "Longitude": "41.00000000",
    "Latitude": "2.00000000"
}]

Map Activity :

package com.example.panos.fleet_management;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

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.Iterator;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Map;
import java.util.Map.Entry;

import static com.example.panos.fleet_management.R.id.map;


public class MapActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;    

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(map);
        mapFragment.getMapAsync(this);
        new MapRequest(this).execute();

    }

    @Override
        public void onMapReady (GoogleMap googleMap){
        mMap = googleMap;

    // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(40,41);
        LatLng location2 = new LatLng(11,41);

        mMap.addMarker(new MarkerOptions().position(sydney).title(getIntent().getStringExtra("dat")));
        mMap.addMarker(new MarkerOptions().position(location2).title("dsader"));


        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
}

}
pit
  • 11
  • 6
  • show the code for how you are trying to fetch that data and where you have called your asynctask – Vivek Mishra Aug 31 '18 at 05:15
  • @pit ,i have check your code you haven't call Async Task properly.Please call like new MapRequest().execute(); Then it should work – Suman Aug 31 '18 at 05:34
  • Well if it was right you wouldn't have asked question here :) – Vivek Mishra Aug 31 '18 at 12:22
  • @VivekMishra The reason I have removed the code that i was trying to fetch data is because it was wrong. I used in method: onPostexecute on Asynctask code like this : Intent intent = new Intent(MapRequest.this,MapActivity.class); intent.putExtra("dataparsed", dataParsed); startActivity(intent); but i had error "Cannot resolve constructor intent" in the first line.. Also tried several other solutions in intent like getApplicationContext() but i could not move the variables. – pit Aug 31 '18 at 12:26
  • move your move camera code in some method and call that method from post executeof your asynctask.https://stackoverflow.com/questions/14419417/how-to-call-activity-method-in-an-asynctask – Vivek Mishra Aug 31 '18 at 17:41
  • Tried that but I still don't understand how the async values can be passed to the mapactivity – pit Sep 01 '18 at 20:59

2 Answers2

0

First, why you have the Volley imports and you're not using them? It's a very simple way to get data from network asynchronously, without the AsyncTask and right from your Activity.

Also you're creating the Intent and doing nothing with it. If you insist in using it the way you are, use the Intent to send a LocalBroadcastManager and register the receiver for it in your activity where the map is

sebasira
  • 1,739
  • 1
  • 22
  • 41
  • Thanks for your answer.Volley imports were not used because i tried that way before async task and could not work. I found a more simple answer. I just changed mMap variable from Mapactivity to public static and then i accesed it from Asynctask onPostecute and then placed the values that i wanted from doInbackground() to the mMap variable. – pit Sep 02 '18 at 19:07
-1

At last I found a very simple answer to my question. The only thing that i needed to do was to make mMap variable public static and then access it from onPostexecute and put the data there.

pit
  • 11
  • 6