0

I am having a class for MapActivity I parse the webservice and I get a arraylist as a return value. I want that arraylist in OnCreate method to pass to next Intent by clicking onto Button

My Code is:

package com.demo.map;

import java.util.ArrayList;

import android.app.ActionBar;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;

import com.demo.map.R;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MainActivity extends Fragment{

private GoogleMap mMap;
private String[] places = {"ATM|Hospital|Police|Restaurant"};
public LocationManager locationManager;
public Location loc;
Place placeDetail;

public static final String TAG = "MainActivity";

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    //super.onCreate(savedInstanceState);
    final View v = inflater.inflate(R.layout.activity_sub_main, container, false);

    mMap = ((SupportMapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();


    locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);

    String provider = locationManager.getBestProvider(new Criteria(), false);

    Location location = locationManager.getLastKnownLocation(provider);

    if (location == null)
    {
        locationManager.requestLocationUpdates(provider, 0, 0, listener);
    }
    else
    {
        loc = location;
        new GetPlaces(getActivity(), places[0].toLowerCase().replace("-", "_")).execute();
        Log.e(TAG, "location : " + location);
    }



    Button camera_btn = (Button) v.findViewById(R.id.map_activity_cam_button);

    camera_btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            Intent i = new Intent(getActivity(),Compass.class);
               // pass arraylist by clicking on this button. I want resulted arraylist from doInBackground.. i.e. *findplaces*
            startActivity(i);

        }
    });
    return v;

}   

private class GetPlaces extends AsyncTask<Void, Void, ArrayList<Place>> {

    private ProgressDialog dialog;
    private Context context = getActivity();
    private String places;

    public GetPlaces(Activity act, String places) {
        this.context = act;
        this.places = places;
    }

    @Override
    protected void onPostExecute(ArrayList<Place> result) {
        super.onPostExecute(result);
        if (dialog.isShowing()) {
            dialog.dismiss();
        }
        for (int i = 0; i < result.size(); i++)
        {
            mMap.addMarker(new MarkerOptions()
                    .title(result.get(i).getName())
                    .position(new LatLng(result.get(i).getLatitude(), result.get(i).getLongitude()))
                    .icon(BitmapDescriptorFactory.fromResource(R.drawable.google_pin_new))
                    .snippet(result.get(i).getVicinity()));
        }
        CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(new LatLng(result.get(0).getLatitude(), result.get(0).getLongitude()))
                // Sets the center of the map to Mountain View
                .zoom(14) // Sets the zoom
                .tilt(30) // Sets the tilt of the camera to 30 degrees
                .build(); // Creates a CameraPosition from the builder
        mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        dialog = new ProgressDialog(context);
        dialog.setCancelable(false);
        dialog.setMessage("Loading..");
        dialog.isIndeterminate();
        dialog.show();
    }

    @Override
    protected ArrayList<Place> doInBackground(Void... arg0) {
        PlacesService service = new PlacesService(
                "AIzaSyAmllugM0BoCNosipmHpw1picM2a1XNOEA");
        ArrayList<Place> findPlaces = service.findPlaces(loc.getLatitude(), // 28.632808
                loc.getLongitude(), places); // 77.218276

        for (int i = 0; i < findPlaces.size(); i++) {

            placeDetail = findPlaces.get(i);
            Log.e(TAG, "places : " + placeDetail.getName());
        }
        return findPlaces;
    }

}

private LocationListener listener = new LocationListener() {

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }

    @Override
    public void onLocationChanged(Location location) {
        Log.e(TAG, "location update : " + location);
        loc = location;
        locationManager.removeUpdates(listener);
    }
};

    }

Place class

public class Place {
private String id;
private String icon;
private String name;
private String vicinity;
private Double latitude;
private Double longitude;

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getIcon() {
    return icon;
}

public void setIcon(String icon) {
    this.icon = icon;
}

public Double getLatitude() {
    return latitude;
}

public void setLatitude(Double latitude) {
    this.latitude = latitude;
}

public Double getLongitude() {
    return longitude;
}

public void setLongitude(Double longitude) {
    this.longitude = longitude;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getVicinity() {
    return vicinity;
}

public void setVicinity(String vicinity) {
    this.vicinity = vicinity;
}

static Place jsonToPontoReferencia(JSONObject pontoReferencia) {
    try {
        Place result = new Place();
        JSONObject geometry = (JSONObject) pontoReferencia.get("geometry");
        JSONObject location = (JSONObject) geometry.get("location");
        result.setLatitude((Double) location.get("lat"));
        result.setLongitude((Double) location.get("lng"));
        result.setIcon(pontoReferencia.getString("icon"));
        result.setName(pontoReferencia.getString("name"));
        result.setVicinity(pontoReferencia.getString("vicinity"));
        result.setId(pontoReferencia.getString("id"));
        return result;
    } catch (JSONException ex) {
        Logger.getLogger(Place.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

@Override
public String toString() {
    return "Place{" + "id=" + id + ", icon=" + icon + ", name=" + name + ", latitude=" + latitude + ", longitude=" + longitude + '}';
}

}

PlaceService Class

public class PlacesService {

private String API_KEY;

public PlacesService(String apikey) {
    this.API_KEY = apikey;
}

public void setApiKey(String apikey) {
    this.API_KEY = apikey;
}

public ArrayList<Place> findPlaces(double latitude, double longitude,
        String placeSpacification) {

    String urlString = makeUrl(latitude, longitude, placeSpacification);

    try {
        String json = getJSON(urlString);

        System.out.println(json);
        JSONObject object = new JSONObject(json);
        JSONArray array = object.getJSONArray("results");

        ArrayList<Place> arrayList = new ArrayList<Place>();
        for (int i = 0; i < array.length(); i++) {
            try {
                Place place = Place
                        .jsonToPontoReferencia((JSONObject) array.get(i));
                Log.v("Places Services ", "" + place);
                arrayList.add(place);
            } catch (Exception e) {
            }
        }
        return arrayList;
    } catch (JSONException ex) {
        Logger.getLogger(PlacesService.class.getName()).log(Level.SEVERE,
                null, ex);
    }
    return null;
}

// https://maps.googleapis.com/maps/api/place/search/json?location=28.632808,77.218276&radius=500&types=atm&sensor=false&key=apikey
private String makeUrl(double latitude, double longitude, String place) {
    StringBuilder urlString = new StringBuilder(
            "https://maps.googleapis.com/maps/api/place/search/json?");

    if (place.equals("")) {
        urlString.append("&location=");
        urlString.append(Double.toString(latitude));
        urlString.append(",");
        urlString.append(Double.toString(longitude));
        urlString.append("&radius=1000");
        // urlString.append("&types="+place);
        urlString.append("&sensor=false&key=" + API_KEY);
    } else {
        urlString.append("&location=");
        urlString.append(Double.toString(latitude));
        urlString.append(",");
        urlString.append(Double.toString(longitude));
        urlString.append("&radius=1000");
        urlString.append("&types=" + place);
        urlString.append("&sensor=false&key=" + API_KEY);
    }
    return urlString.toString();
}

protected String getJSON(String url) {
    return getUrlContents(url);
}

private String getUrlContents(String theUrl) {
    StringBuilder content = new StringBuilder();

    try {
        URL url = new URL(theUrl);
        URLConnection urlConnection = url.openConnection();
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(urlConnection.getInputStream()), 8);
        String line;
        while ((line = bufferedReader.readLine()) != null) {
            content.append(line + "\n");
        }
        bufferedReader.close();
    }catch (Exception e) {
        e.printStackTrace();
    }
    return content.toString();
}
}
Mitesh Shah
  • 1,729
  • 2
  • 19
  • 37

3 Answers3

3

For this you have two options

1.Write the Listenr for the Button in the OnPostExecute of your AsynchTask and pass the data to Another Activity or..

2.take your result variable as global and Write a method in getCallback() or something like that in your activity and it call this method in your onPostExecute by using your Activity object in Constructor and in that method write Button click functionality..

if you write the button outside at the time doinBackground() you don't have the data so it will pass the null to another Activity.

design your place class like this for parcelable..

public class Place implements Parcelable {
private String id;
private String icon;
private String name;
private String vicinity;
private Double latitude;
private Double longitude;

public Place() {
    // TODO Auto-generated constructor stub
}

public Place(Parcel in) {
    setId(in.readString());
    setIcon(in.readString());
    setName(in.readString());
    setVicinity(in.readString());
    setLatitude(in.readDouble());
    setLongitude(in.readDouble());
}

@Override
public int describeContents() {
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {
    dest.writeString(getId());
    dest.writeString(getIcon());
    dest.writeString(getName());
    dest.writeString(getVicinity());
    dest.writeDouble(getLatitude());
    dest.writeDouble(getLongitude());
}

public String getId() {
    return id;
}

public void setId(String id) {
    this.id = id;
}

public String getIcon() {
    return icon;
}

public void setIcon(String icon) {
    this.icon = icon;
}

public Double getLatitude() {
    return latitude;
}

public void setLatitude(Double latitude) {
    this.latitude = latitude;
}

public Double getLongitude() {
    return longitude;
}

public void setLongitude(Double longitude) {
    this.longitude = longitude;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getVicinity() {
    return vicinity;
}

public void setVicinity(String vicinity) {
    this.vicinity = vicinity;
}

static Place jsonToPontoReferencia(JSONObject pontoReferencia) {
    try {
        Place result = new Place();
        JSONObject geometry = (JSONObject) pontoReferencia.get("geometry");
        JSONObject location = (JSONObject) geometry.get("location");
        result.setLatitude((Double) location.get("lat"));
        result.setLongitude((Double) location.get("lng"));
        result.setIcon(pontoReferencia.getString("icon"));
        result.setName(pontoReferencia.getString("name"));
        result.setVicinity(pontoReferencia.getString("vicinity"));
        result.setId(pontoReferencia.getString("id"));
        return result;
    } catch (JSONException ex) {
        Logger.getLogger(Place.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
}

@Override
public String toString() {
    return "Place{" + "id=" + id + ", icon=" + icon + ", name=" + name
            + ", latitude=" + latitude + ", longitude=" + longitude + '}';
}

public static final Parcelable.Creator<Place> CREATOR = new Parcelable.Creator<Place>() {

    @Override
    public Place createFromParcel(Parcel in) {
        return new Place(in);
    }

    @Override
    public Place[] newArray(int size) {
        return new Place[size];
    }

};
}
kalyan pvs
  • 14,486
  • 4
  • 41
  • 59
0

Why dont you define findPlaces global to the whole class

public class MainActivity extends Fragment{
ArrayList<Place> findPlaces;
private GoogleMap mMap;
private String[] places = {"ATM|Hospital|Police|Restaurant"};
public LocationManager locationManager;
public Location loc;
Place placeDetail;

    Button camera_btn = (Button) v.findViewById(R.id.map_activity_cam_button);

    camera_btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub

            Intent i = new Intent(getActivity(),Compass.class);
               // pass arraylist by clicking on this button. I want resulted arraylist from doInBackground.. i.e. *findplaces*
            startActivity(i);

        }
    });
    return v;

}   

doInBackground() Method

 @Override
protected ArrayList<Place> doInBackground(Void... arg0) {
    PlacesService service = new PlacesService(
            "AIzaSyAmllugM0BoCNosipmHpw1picM2a1XNOEA");
  findPlaces = service.findPlaces(loc.getLatitude(), // 28.632808
            loc.getLongitude(), places); // 77.218276

    for (int i = 0; i < findPlaces.size(); i++) {

        placeDetail = findPlaces.get(i);
        Log.e(TAG, "places : " + placeDetail.getName());
    }
    return findPlaces;
}

}

Jitender Dev
  • 6,907
  • 2
  • 24
  • 35
0

If your agenda is to find the places then move on to next activity, then why dont you initiate fetching of places when user click on button, and navigating to next activity through post excute once required data is available.

    camera_btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // TODO Auto-generated method stub
        new GetPlaces(getActivity(), places[0].toLowerCase().replace("-", "_")).execute();
        }
    });

    private class GetPlaces extends AsyncTask<Void, Void, ArrayList<Place>> {
        @Override
    protected void onPostExecute(ArrayList<Place> result) {

       // Your code for data processing, once its complete then start new activity
       Intent i = new Intent(getActivity(),Compass.class);
       startActivity(i);


     }
   }

Hope this helps.

Techfist
  • 4,314
  • 6
  • 22
  • 32
  • How can I pass that arraylist to intent.. because Intent have method putStringArrayListExtra and my arraylist is place not string?? – Mitesh Shah Nov 13 '13 at 07:03
  • Couple of things,over data passing between activity. 1. You can only pass those data which actualy implements Parcelable, this mechanism OS uses to squzee the data at one end,and to recreate at other,hence said no other data can be passed via intent which are not parcelable or of premitive types. 2. for passing data through Intent you can always use option of putting extra data, or by passing data via a Mechanism called as Bundle. In your case as you are trying to pass list of type Places, its better to mark this object as static, which will enable you to use it statically from other class – Techfist Nov 13 '13 at 08:40