how add marker on map onmaplong click? - android

Address Dailoge This is an Fragment when I click on image another activity (Location Activity)start in which Google map open.
Here is code of Address Dailoge fragment
when map open i want show the Current Location of user and user select the location from map using map picker
when user select the Location i want to take the Addresses of the street zipcode,state,country set it to the form.
public class AddressDialog extends DialogFragment {
public interface AddressListener {
void address(Address address);
void editedAddress(Address locationModel, int index);
}
private static final String TAG = "AddressDialog";
#BindView(R.id.addresslineone)
FormAnimationView addresslineone;
private GoogleApiClient mClient;
#BindView(R.id.addresslinetwo)
FormAnimationView addresslinetwo;
#BindView(R.id.city)
FormAnimationView cityView;
#BindView(R.id.state)
FormAnimationView stateView;
#BindView(R.id.country)
FormAnimationView countryView;
private boolean isfromEdit;
#BindView(R.id.pincode)
FormAnimationView pincode;
#BindView(R.id.edit_spinner_1)
EditSpinner mEditSpinner1;
private Address address = new Address();
private AddressListener addressListener;
private int index;
#OnClick(R.id.closedialog)
public void closeClick() {
this.dismiss();
}
#BindView(R.id.searchmap)
ImageView openmap;
#OnClick(R.id.searchmap)
public void searchmapclick() {
startActivityForResult(new Intent(getActivity(), LocationActivity.class), 100);
}
#OnClick(R.id.addaddressimg)
public void addClick() {
if (addressListener != null && address != null) {
if (!TextUtils.isEmpty(mEditSpinner1.getText()) &&
!TextUtils.isEmpty(addresslineone.getText())
&& !TextUtils.isEmpty(addresslinetwo.getText())
&& !TextUtils.isEmpty(cityView.getText())
&& !TextUtils.isEmpty(stateView.getText())
&& !TextUtils.isEmpty(pincode.getText())
&& !TextUtils.isEmpty(countryView.getText())) {
//locationModel.setAddressType(mEditSpinner1.getText().toString());
//address.setCountry(addresslinetwo.getText().toString());
// address.setLocality();
//address.setLocality("");
address.setRegion(stateView.getText().toString());
address.setFormatted(addresslineone.getText().toString());
address.setFormatted(addresslinetwo.getText().toString());
address.setCountry(countryView.getText().toString());
address.setLocality(cityView.getText().toString());
// address.setState(stateView.getText().toString());
address.setPostalCode(pincode.getText().toString());
address.setStreetAddress(addresslineone.getText().toString());
address.setStreetAddress(addresslinetwo.getText().toString());
address.setType(mEditSpinner1.getText().toString());
// address.setRegion();
if (!isfromEdit) {
addressListener.address(address);
} else {
addressListener.editedAddress(address, address.getIndex());
}
this.dismiss();
} else {
Toast.makeText(getActivity(), "All fields are mandetory", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStart() {
super.onStart();
mClient.connect();
}
#Override
public void onStop() {
mClient.disconnect();
super.onStop();
}
// #Override
// public void onAttach(Context context) {
// super.onAttach(context);
// //addressListener = (AddressListener) context;
// }
public void setListener(AddressListener addressListener) {
this.addressListener = addressListener;
}
/* #NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final View view = View.inflate(getActivity(), R.layout.address_selection_view, null);
Dialog dialog = new Dialog(getActivity(), R.style.DialogFragment);
dialog.setContentView(view);
return dialog;
}*/
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
// getDialog().getWindow().getWindowStyle().gets;
View rootView = inflater.inflate(R.layout.address_selection_view, container, false);
// getDialog().setTitle("Simple Dialog");
ButterKnife.bind(this, rootView);
mClient = new GoogleApiClient
.Builder(getContext())
.addApi(Places.GEO_DATA_API)
.addApi(Places.PLACE_DETECTION_API)
.build();
try {
Address locationModel = (Address) getArguments().get("data");
if (locationModel != null) {
// getAddressDetails(locationModel.getAddress());
address.setAddressId(locationModel.getAddressId());
address.setFormatted("");
address.setCountry(addresslinetwo.getText().toString());
address.setLocality("");
address.setRegion("");
address.setPostalCode(pincode.getText().toString());
address.setStreetAddress(addresslineone.getText().toString());
address.setStreetAddress(addresslinetwo.getText().toString());
addresslineone.setText(locationModel.getStreetAddress());
addresslinetwo.setText(locationModel.getStreetAddress());
/*addresslinetwo.setText(locationModel.getCountry());*/
pincode.setText(locationModel.getPostalCode());
mEditSpinner1.setText(locationModel.getType());
countryView.setText(locationModel.getCountry());
stateView.setText(locationModel.getRegion());
cityView.setText(locationModel.getLocality());
isfromEdit = true;
}
} catch (Exception e) {
}
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
init();
}
private void init() {
addresslineone.setHintMessage("Address Line 1 (Street / landmark)");
addresslineone.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
addresslineone.setTintColor(Color.parseColor("#de3f5abd"));
addresslineone.setFontStyle("fonts/Helvetica.otf");
addresslinetwo.setHintMessage("Address Line 2 (City / Country)");
addresslinetwo.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
addresslinetwo.setTintColor(Color.parseColor("#de3f5abd"));
addresslinetwo.setFontStyle("fonts/Helvetica.otf");
pincode.setHintMessage("Post / Zip / Pin Code");
pincode.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS);
pincode.setFontStyle("fonts/Helvetica.otf");
pincode.setTintColor(Color.parseColor("#de3f5abd"));
stateView.setInputType(InputType.TYPE_CLASS_TEXT);
stateView.setHintMessage("State");
stateView.setTintColor(Color.parseColor("#de3f5abd"));
stateView.setFontStyle("fonts/Helvetica.otf");
countryView.setInputType(InputType.TYPE_CLASS_TEXT);
countryView.setHintMessage("Country");
countryView.setTintColor(Color.parseColor("#de3f5abd"));
countryView.setFontStyle("fonts/Helvetica.otf");
cityView.setInputType(InputType.TYPE_CLASS_TEXT);
cityView.setHintMessage("City");
cityView.setTintColor(Color.parseColor("#de3f5abd"));
cityView.setFontStyle("fonts/Helvetica.otf");
ListAdapter adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.edits_array_1));
mEditSpinner1.setAdapter(adapter);
}
public void getAddressDetails(String address) {
StringBuilder stringBuilder = new StringBuilder();
if (address != null) {
String[] addressSlice = address.toString().split(", ");
String country = addressSlice[addressSlice.length - 1];
if (country != null) {
addresslinetwo.setText(country);
countryView.setText(country);
}
stringBuilder.append("Country:" + country);
if (addressSlice.length > 1) {
String[] stateAndPostalCode = addressSlice[addressSlice.length - 2].split(" ");
if (stateAndPostalCode.length > 1) {
String postalCode = stateAndPostalCode[stateAndPostalCode.length - 1];
String state = "";
for (int i = 0; i < stateAndPostalCode.length - 1; i++) {
state += (i == 0 ? "" : " ") + stateAndPostalCode[i];
}
stringBuilder.append("PostalCode:" + postalCode);
stringBuilder.append("State:" + state);
if (postalCode != null) {
pincode.setText(postalCode);
}
if (state != null) {
stateView.setText("" + state);
// pincode.setText(pincode.getText() + "," + state);
}
} else {
String state = stateAndPostalCode[stateAndPostalCode.length - 1];
stringBuilder.append("State:" + state);
stateView.setText("" + state);
}
}
String city = null;
if (addressSlice.length > 2)
city = addressSlice[addressSlice.length - 3].toString();
if (city != null) {
cityView.setText("" + city);
// addresslinetwo.setText(addresslinetwo.getText() + "," + city);
stringBuilder.append("City:" + city);
}
String stAddress1 = "";
if (addressSlice.length == 4)
stAddress1 = addressSlice[0];
else if (addressSlice.length > 3) {
String stAddress2 = addressSlice[addressSlice.length - 4];
for (int i = 0; i < addressSlice.length - 4; i++) {
stAddress1 += (i == 0 ? "" : ", ") + addressSlice[i];
}
}
stringBuilder.append("Address1:" + stAddress1);
if (stAddress1 != null) {
addresslineone.setText(stAddress1);
// addresslineone.getText().replaceAll("null", "");
}
}
// if(place.getLatLng()!=null)
// {
// String latitude = "" + place.getLatLng().latitude;
// String longitude = "" + place.getLatLng().longitude;
// }
Log.e(TAG, "getAddressDetails: " + stringBuilder.toString());
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Log.e(TAG, "onActivityResult: " + requestCode);
if (requestCode == 100) {
try {
if (data.getExtras() != null && data.getExtras().getSerializable("data") != null) {
LocationModel locationModel = (LocationModel) data.getExtras().getSerializable("data");
if (locationModel != null) {
// addresslineone.setText(locationModel.getLocationname());
getAddressDetails(locationModel.getAddress());
//latitude = String.valueOf(locationModel.getLatitude());
//longitude = String.valueOf(locationModel.getLongitude());
}
}
} catch (Exception e) {
}
}
}
}
Here is the code of Location Activity
Map
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.location.places.ui.PlaceSelectionListener;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapView;
import com.google.android.gms.maps.MapsInitializer;
import com.google.android.gms.maps.OnMapReadyCallback;
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 com.planfisheye.fisheye.BaseActivity;
import com.planfisheye.fisheye.R;
import com.planfisheye.fisheye.adapters.NearByGetLocationParser;
import com.planfisheye.fisheye.adapters.PlacesAutoCompleteAdapter;
import com.planfisheye.fisheye.adapters.PlacesModel;
import com.planfisheye.fisheye.helper.CustomDialog;
import com.planfisheye.fisheye.models.LocationModel;
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.URL;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
/**
* Created by venkateshmurthy on 24/12/16.
*/
public class LocationActivity extends BaseActivity implements OnMapReadyCallback, GoogleApiClient.OnConnectionFailedListener, PlaceSelectionListener {
private static final String TAG = "LocationActivity";
MapView mapView;
GoogleMap map;
private GoogleApiClient mClient;
#BindView(R.id.autocompletesearch)
AutoCompleteTextView autoSearch;
private static final int REQUEST_SELECT_PLACE = 1000;
private LatLng latlangObj;
private String address;
private String locationname;
private CustomDialog mCustomDialog;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#OnClick(R.id.doneclick)
public void doneClick() {
if(latlangObj!=null) {
LocationModel locationModel=new LocationModel();
locationModel.setLatitude(latlangObj.latitude);
locationModel.setLongitude(latlangObj.longitude);
locationModel.setLocationname(locationname);
locationModel.setAddress(address);
Intent intent=new Intent();
intent.putExtra("data",locationModel);
setResult(13, intent);
finish();
}else {
finish();
}
overridePendingTransition(R.anim.enter, R.anim.exit);
}
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_select);
ButterKnife.bind(this);
mapView = (MapView) findViewById(R.id.mapview);
mapView.onCreate(savedInstanceState);
mCustomDialog=new CustomDialog(this);
// try {
// Intent intent = new PlaceAutocomplete.IntentBuilder
// (PlaceAutocomplete.MODE_OVERLAY)
// // .setBoundsBias(BOUNDS_MOUNTAIN_VIEW)
// .build(this);
// startActivityForResult(intent, REQUEST_SELECT_PLACE);
// } catch (GooglePlayServicesRepairableException |
// GooglePlayServicesNotAvailableException e) {
// e.printStackTrace();
// }
// PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
// getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
// autocompleteFragment.setOnPlaceSelectedListener(this);
// autocompleteFragment.setHint("Search a Location");
mClient = new GoogleApiClient
.Builder(this)
.addApi(Places.GEO_DATA_API)
.enableAutoManage(this, this)
.addApi(Places.PLACE_DETECTION_API)
.build();
mClient.connect();
autoSearch.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.autocomplete_list_item));
autoSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
autoSearch.setText("");
}
});
autoSearch.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//CommonUtils.hideKeyBoard(getActivity());
mCustomDialog.show();
final PlacesModel hm = (PlacesModel) autoSearch.getAdapter().getItem(position);
Log.e("place_id", "" + hm.getPlaceid());
// placetext.setText("" + hm.getDescription());
//AIzaSyA9_CVo9IETbjjqqBHC1eEYesVsaMPflIk
String[] codeInfo =
TextUtils.split(hm.getDescription(), ",");
// getLatLng(hm.getPlaceid());
Places.GeoDataApi.getPlaceById(mClient, hm.getPlaceid())
.setResultCallback(new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
mCustomDialog.dismiss();
if (places.getStatus().isSuccess() && places.getCount() > 0) {
final Place myPlace = places.get(0);
//getAddressDetails(myPlace);
Log.e("name", "Place found: " + myPlace.getName() + "\t" + myPlace.getAddress()+"\t"+myPlace.getLatLng());
if(myPlace.getAddress()!=null) {
address = myPlace.getAddress().toString();
}
latlangObj= myPlace.getLatLng();
locationname=hm.getDescription();
Log.e("latitude:", "" + latlangObj.latitude);
Log.e("longitude:", "" + latlangObj.longitude);
Marker marker = map.addMarker(new MarkerOptions()
.position(new LatLng(latlangObj.latitude, latlangObj.longitude))
.title("" + hm.getDescription()));
marker.showInfoWindow();
marker.setDraggable(true);
map.setOnMarkerDragListener(new GoogleMap.OnMarkerDragListener() {
#Override
public void onMarkerDragStart(Marker marker) {
}
#Override
public void onMarkerDrag(Marker marker) {
}
#Override
public void onMarkerDragEnd(Marker marker) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12.0f));
} else {
Log.e("place", "Place not found");
}
places.release();
}
});
autoSearch.setText(""+hm.getDescription());
autoSearch.setSelection(autoSearch.getText().length());
}
});
// Needs to call MapsInitializer before doing any CameraUpdateFactory calls
MapsInitializer.initialize(this);
}
#Override
public void onResume() {
mapView.onResume();
super.onResume();
}
#Override
public void onPause() {
super.onPause();
mapView.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
mapView.onDestroy();
mClient.disconnect();
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
}
#Override
public void onMapReady(GoogleMap googleMap) {
this.map = googleMap;
}
#Override
public void onPlaceSelected(Place place) {
}
#Override
public void onError(Status status) {
}
private class NearbyLatlngTask extends AsyncTask<String, Integer, String> {
String data = null;
#Override
protected String doInBackground(String... url) {
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(String result) {
GetLatLngTask parserTask = new GetLatLngTask();
// Start parsing the Google places in JSON format
// Invokes the "doInBackground()" method of the class ParseTask
parserTask.execute(result);
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class GetLatLngTask extends AsyncTask<String, Integer, List<HashMap<String, Double>>> {
JSONObject jObject;
// Invoked by execute() method of this object
#Override
protected List<HashMap<String, Double>> doInBackground(String... jsonData) {
List<HashMap<String, Double>> places = null;
NearByGetLocationParser nearPlaceJsonParser = new NearByGetLocationParser();
try {
jObject = new JSONObject(jsonData[0]);
/** Getting the parsed data as a List construct */
places = nearPlaceJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
// Executed after the complete execution of doInBackground() method
#Override
protected void onPostExecute(List<HashMap<String, Double>> list) {
// Clears all the existing markers
// mGoogleMap.clear();
if (list != null) {
for (int i = 0; i < list.size(); i++) {
// Creating a marker
MarkerOptions markerOptions = new MarkerOptions();
// Getting a place from the places list
HashMap<String, Double> hmPlace = list.get(i);
// Getting latitude of the place
double lat = hmPlace.get("lat");
// Getting longitude of the place
double lng = hmPlace.get("lng");
Log.e("lat", "lat" + lat);
Log.e("long", "long" + lng);
Toast.LENGTH_SHORT).show();
}
}
}
}
/**
* A method to download json data from url
*/
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();
// Connecting to url
urlConnection.connect();
// Reading data from url
iStream = urlConnection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line);
}
data = sb.toString();
br.close();
} catch (Exception e) {
//Log.d("Exception while downloading url", e.toString());
} finally {
iStream.close();
urlConnection.disconnect();
}
return data;
}
private void getLatLng(String placeID) {
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/details/json?placeid=" + placeID);
sb.append("&key=AIzaSyBiV3T00af_2jM0Vinlcws2Gc6K7ktVp38");
NearbyLatlngTask placesTask = new NearbyLatlngTask();
// Invokes the "doInBackground()" method of the class PlaceTask
placesTask.execute(sb.toString());
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
}

Check this,
map.setOnMapLongClickListener(new OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
addMarker();
}
});
add this is addMarker method,
private void addMarker() {
// create marker
MarkerOptions marker = new MarkerOptions().position(new LatLng(latitude, longitude)).title("Hello Maps");
googleMap.addMarker(marker);
}

Related

JSONArray not updating immediately

Whenever in my Popular Movies Udacity project, I click on a movie poster in the favorites movie collection, which is maintained as a database offline, the URL list gets updated correctly but the JSONArray made in the AsyncTask does not update immediately.
package com.example.android.popularmovies;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.example.android.popularmovies.Database.Contract;
import com.example.android.popularmovies.utilities.NetworkUtils;
import com.facebook.stetho.Stetho;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private final static String BASE_POSTER_URL = "http://image.tmdb.org/t/p/w500/";
private static String OPTION = "OPTION";
TextView mNoFavorites;
// = new JSONArray();
JSONArray favoriteJsonArray;
int optionChosen;
private ProgressBar mProgessBar;
private TextView mErrorMessage;
private Button mRetry;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private URL url;
private ArrayList<String> posterList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null)
optionChosen = savedInstanceState.getInt(OPTION);
Stetho.initializeWithDefaults(this);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.my_recycler_view);
mRecyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(this, 2);
mRecyclerView.setLayoutManager(mLayoutManager);
//mAdapter = new MainActivityAdapter(this, posterList, null);
//mRecyclerView.setAdapter(mAdapter);
mProgessBar = findViewById(R.id.progess_bar);
mErrorMessage = findViewById(R.id.error_message);
mRetry = findViewById(R.id.retry);
mNoFavorites = findViewById(R.id.no_favorites_yet);
favoriteJsonArray = new JSONArray();
tryToConnect(new View(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.preferences, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
try {
if (item.getItemId() == R.id.top_rated) {
mRecyclerView.setVisibility(View.VISIBLE);
mNoFavorites.setVisibility(View.INVISIBLE);
url = NetworkUtils.buildUrl("top_rated");
if (url != null) {
mErrorMessage.setVisibility(View.INVISIBLE);
mRetry.setVisibility(View.INVISIBLE);
new FetchMovies().execute(url, null, null);
}
optionChosen = 1;
}
if (item.getItemId() == R.id.most_popular) {
mRecyclerView.setVisibility(View.VISIBLE);
mNoFavorites.setVisibility(View.INVISIBLE);
url = NetworkUtils.buildUrl("most_popular");
if (url != null) {
mErrorMessage.setVisibility(View.INVISIBLE);
mRetry.setVisibility(View.INVISIBLE);
new FetchMovies().execute(url, null, null);
}
optionChosen = 2;
}
if (item.getItemId() == R.id.favorites) {
optionFavorites();
optionChosen = 3;
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (java.lang.NullPointerException e) {
e.printStackTrace();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onResume() {
super.onResume();
if (optionChosen == 3)
optionFavorites();
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(OPTION, optionChosen);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
/* public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore state members from saved instance
optionChosen = savedInstanceState.getInt(OPTION);
}
*/
private void optionFavorites() {
try {
String[] projection = {"movie_id", "favorite_poster_path"};
Cursor cursor = getContentResolver().query(
Contract.FavoriteMovieDatabase.CONTENT_URI,
projection,
null,
null,
null
);
ArrayList<String> posterPathArrayList = new ArrayList<>();
ArrayList<URL> urlArrayList = new ArrayList<>();
if (cursor != null && cursor.moveToFirst()) {
do {
String posterPath = cursor.getString(cursor.getColumnIndex(Contract.FavoriteMovieDatabase.FAVORITE_POSTER_PATH));
posterPathArrayList.add(BASE_POSTER_URL + posterPath);
int movieId = cursor.getInt(cursor.getColumnIndex("movie_id"));
URL favoriteURL = NetworkUtils.buildUrl("favorites", movieId);
urlArrayList.add(favoriteURL);
} while (cursor.moveToNext());
Log.d("urllist", "" + urlArrayList.toString());
new FetchFavorites().execute(urlArrayList, null, null);
mAdapter = new MainActivityAdapter(MainActivity.this, posterPathArrayList, favoriteJsonArray);
mRecyclerView.setAdapter(mAdapter);
} else {
mRecyclerView.setVisibility(View.INVISIBLE);
mNoFavorites.setVisibility(View.VISIBLE);
}
} catch (java.lang.NullPointerException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private void noConnection() {
mErrorMessage.setText(R.string.no_connection);
mErrorMessage.setVisibility(View.VISIBLE);
mRetry.setText(R.string.retry);
mRetry.setVisibility(View.VISIBLE);
}
public void tryToConnect(View v) {
try {
url = NetworkUtils.buildUrl("most_popular");
} catch (MalformedURLException e) {
e.printStackTrace();
}
if (url != null) {
mErrorMessage.setVisibility(View.INVISIBLE);
mRetry.setVisibility(View.INVISIBLE);
new FetchMovies().execute(url, null, null);
}
}
private class FetchMovies extends AsyncTask<URL, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgessBar.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(URL... params) {
URL searchUrl = params[0];
String searchResults = null;
try {
searchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);
} catch (IOException e) {
e.printStackTrace();
}
return searchResults;
}
#Override
protected void onPostExecute(String searchResults) {
mProgessBar.setVisibility(View.INVISIBLE);
try {
posterList = new ArrayList<>();
if (searchResults != null && !searchResults.equals("")) {
JSONObject jsonObject = new JSONObject(searchResults);
JSONArray pageOne = jsonObject.getJSONArray("results");
int length = pageOne.length();
for (int i = 0; i < length; i++) {
JSONObject result = pageOne.getJSONObject(i);
String posterPath = BASE_POSTER_URL + result.getString("poster_path");
posterList.add(posterPath);
}
mAdapter = new MainActivityAdapter(MainActivity.this, posterList, pageOne);
mRecyclerView.setAdapter(mAdapter);
} else noConnection();
} catch (Exception e) {
e.printStackTrace();
}
}
}
private class FetchFavorites extends AsyncTask<ArrayList<URL>, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(ArrayList<URL>... params) {
ArrayList<URL> urlArrayList = params[0];
ArrayList<String> stringArrayList = new ArrayList<>();
String searchResults;
URL searchUrl;
favoriteJsonArray = new JSONArray();
for (int i = 0; i < urlArrayList.size(); i++)
try {
searchUrl = urlArrayList.get(i);
searchResults = NetworkUtils.getResponseFromHttpUrl(searchUrl);
stringArrayList.add(searchResults);
} catch (IOException e) {
e.printStackTrace();
}
return stringArrayList;
}
#Override
protected void onPostExecute(ArrayList<String> stringArrayList) {
for (int i = 0; i < stringArrayList.size(); i++)
try {
favoriteJsonArray.put(new JSONObject(stringArrayList.get(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
urlArrayList gets updated correctly when database changes occur, but favoriteJsonArray, which is updated inside AsyncTask, does not. Why?
There are two problems in you code:
in FetchFavorites.doInBackground(), you assign a new JSONArray() to favoriteJsonArray, but your mAdapter is still hold the old reference, which is an empty JSONArray.
you didn't call mAdapter.notifyDataSetChanged() after update the favoriteJsonArray.
You can solve the problems in to ways:
do not new JSONArray() in FetchFavorites.doInBackground(), and call mAdapter.notifyDataSetChanged() after update the favoriteJsonArray, but there is still a problem, you should clear the favoriteJsonArray every time you fetch the new data, and clear a JSONArray is kind of boring (there is no clear() method).
new JSONArray(), but edit your MainActivityAdapter, add a method like setFavorites(JSONArray array), and set the new created favoriteJsonArray to it then call mAdapter.notifyDataSetChanged().

Nearby Places search gives a random result rather than a specific result

When I first run my app, on cicking on a particular Place Type, it generates every tpe of nearby place like: atm, malls, food,schools etc. within my specified mile radius.
Code for Places Activity:
package www.uneditedmap.com.locationandmap;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import java.util.List;
import www.uneditedmap.com.locationandmap.model.Places;
import www.uneditedmap.com.locationandmap.parsers.PlacesJSONParser;
public class PlacesActivity extends ListActivity {
TextView placeName;
TextView placeVicinity;
TextView placeStatus;
String locationType;
String myUrl;
ProgressDialog pDialog;
// List<FetchLocationTask> tasks;
List<Places> placesList;
String lat, lng;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_places);
// Initialize the TextView for vertical Scrolling
placeName = (TextView) findViewById(R.id.place_title);
placeVicinity = (TextView) findViewById(R.id.vicinity);
placeStatus = (TextView) findViewById(R.id.openNow);
// tasks = new ArrayList<>();
//locationFetcher();
Bundle extras = getIntent().getExtras();
if (extras != null) {
locationType = (extras.getString("TAG")).toString();
lat = extras.getString("lat").toString();
lng = extras.getString("lng").toString();
} else {
// set default value for now
locationType = "atm";
}
myUrl = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
+ lat + ","
+ lng
+ "&radius="
+ getString(R.string.radius)
+ "&types="
+ locationType
+ "&sensor=true&key="
+ getString(R.string.google_maps_key);
myUrl = myUrl.replaceAll(" ", "_");
//Log.d("generated URL: ", myUrl);
requestData(myUrl);
}
protected void updatePlaces() {
if (placesList.isEmpty()) {
Toast.makeText(getApplicationContext(), "No Result", Toast.LENGTH_LONG).show();
}
PlacesListAdapter adapter = new PlacesListAdapter(this, R.layout.item_vicinity, placesList);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_places, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.action_refresh) {
//Toast.makeText(this, locationType, Toast.LENGTH_SHORT).show();
requestData(myUrl);
}
return false;
}
private void requestData(String uri) {
/*
Methods for Volley
Comment out this block and Uncomment AsyncTask to Use the AsyncTask block
The Volley Library uses less lines of code than the AsyncTask
*/
StringRequest request = new StringRequest(uri,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
placesList = PlacesJSONParser.parseFeed(response);
updatePlaces();
pDialog.dismiss();
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError ex) {
//Toast.makeText(PlacesActivity.this, ex.getMessage(), Toast.LENGTH_LONG).show();
Toast.makeText(PlacesActivity.this, "Please Check your network connection and" +
" refresh again", Toast.LENGTH_LONG).show();
pDialog.dismiss();
}
});
// add the request to queue
RequestQueue queue = Volley.newRequestQueue(this);
queue.add(request);
pDialog = new ProgressDialog(PlacesActivity.this);
pDialog.setMessage("Loading locations..");
pDialog.setCancelable(false);
pDialog.show();
//Methods using AsyncTask, Uncomment if using AsyncTask
// FetchLocationTask myTask = new FetchLocationTask();
// myTask.execute(uri);
}
/*
Replacing the AsyncTask with Volley.
To Use the AsyncTask, Comment out the Volley Method inside the RequestData() Method
and Uncomment AsyncTask with the corresponding methods
*/
/*private class FetchLocationTask extends AsyncTask<String, String, List<Places>> {
#Override
protected void onPreExecute() {
//updatePlaces();
pDialog = new ProgressDialog(PlacesActivity.this);
pDialog.setMessage("Loading locations..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected List<Places> doInBackground(String... params) {
String content = HttpManager.getData(params[0]);
placesList = PlacesJSONParser.parseFeed(content);
Log.d("results : ", content);
return placesList;
}
#Override
protected void onPostExecute(List<Places> result) {
if (pDialog.isShowing())
pDialog.dismiss();
if (result == null) {
Toast.makeText(PlacesActivity.this, "Web service not available", Toast.LENGTH_LONG).show();
return;
}
placesList = result;
updatePlaces();
}
#Override
protected void onProgressUpdate(String... values) {
// updatePlaces(values[0]);
}
}*/
}
**Code for Restaurant.java**
package www.uneditedmap.com.locationandmap;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;
public class Restaurant extends FragmentActivity {
MyLocation mLocation;
String lat, lng;
String[] keywords;
//String restaurants;
//private int defautltId, restaurantId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_map);
// defautltId = R.drawable.ic_default;
// restaurantId = R.drawable.ic_restaurant;
keywords = getResources().getStringArray(R.array.keywords);
mLocation = new MyLocation(this);
//fetch location method
locationFetcher();
//keywords[0]
if (isOnline()) {
// Toast.makeText(getActivity().getBaseContext(), "You clicked "+ keywords[position]
// + " from " + lat + " , " + lng, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, PlacesActivity.class)
.putExtra("TAG", keywords[0])
.putExtra("lat", lat)
.putExtra("lng", lng);
startActivity(intent);
} else {
Toast.makeText(this.getBaseContext(), "Network Isn't Available", Toast.LENGTH_LONG).show();
}
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
public void locationFetcher() {
if (mLocation.canGetLocation()) {
//mLocation.getLocation();
double latitude = mLocation.getLatitude();
double longitude = mLocation.getLongitude();
lat = String.valueOf(latitude);
lng = String.valueOf(longitude);
} else {
Toast.makeText(this, "LOCATION NOT ACQUIRED,TURN ON A PROVIDER", Toast.LENGTH_SHORT).show();
}
}
}
Code for the cardview where the restaurant.java is first added to the cardview stack:
package www.uneditedmap.com.locationandmap;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by null on 28/02/2015.
*/
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.ViewHolder> {
public static String FAV = "New Activity";
List<EndangeredItem> mItems;
// LayoutInflater inflater;
private Context context;
public GridAdapter() {
super();
//inflater = LayoutInflater.from(viewGroup.getContext())
// this.context=context;
// this.mItems=mItems;
// inflater = LayoutInflater.from(context);
mItems = new ArrayList<EndangeredItem>();
EndangeredItem species = new EndangeredItem();
species.setName("Restaurant");
species.setThumbnail(R.drawable.restaurant);
mItems.add(species);
species = new EndangeredItem();
species.setName("Churches");
species.setThumbnail(R.drawable.church);
mItems.add(species);
species = new EndangeredItem();
species.setName("Laundry");
species.setThumbnail(R.drawable.laundry);
mItems.add(species);
species = new EndangeredItem();
species.setName("Schools");
species.setThumbnail(R.drawable.school);
mItems.add(species);
species = new EndangeredItem();
species.setName("Cinemas");
species.setThumbnail(R.drawable.cinema);
mItems.add(species);
species = new EndangeredItem();
species.setName("Hospitals");
species.setThumbnail(R.drawable.hospital);
mItems.add(species);
species = new EndangeredItem();
species.setName("Tech Centers");
species.setThumbnail(R.drawable.hubs);
mItems.add(species);
species = new EndangeredItem();
species.setName("Clubs");
species.setThumbnail(R.drawable.clubs);
mItems.add(species);
species = new EndangeredItem();
species.setName("Fashion House");
species.setThumbnail(R.drawable.fashion);
mItems.add(species);
species = new EndangeredItem();
species.setName("Banks");
species.setThumbnail(R.drawable.bank);
mItems.add(species);
species = new EndangeredItem();
species.setName("Atms");
species.setThumbnail(R.drawable.atm);
mItems.add(species);
species = new EndangeredItem();
species.setName("Sport Centers");
species.setThumbnail(R.drawable.sportcenters);
mItems.add(species);
species = new EndangeredItem();
species.setName("Supermarkets");
species.setThumbnail(R.drawable.supermarket);
mItems.add(species);
species = new EndangeredItem();
species.setName("Sitouts");
species.setThumbnail(R.drawable.sitouts);
mItems.add(species);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.grid_item, viewGroup, false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
#Override
public void onBindViewHolder(ViewHolder viewHolder, int i) {
EndangeredItem nature = mItems.get(i);
viewHolder.tvspecies.setText(nature.getName());
viewHolder.imgThumbnail.setImageResource(nature.getThumbnail());
}
#Override
public int getItemCount() {
return mItems.size();
}
class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnLongClickListener {
public ImageView imgThumbnail;
public TextView tvspecies;
public ViewHolder(View itemView) {
super(itemView);
context = itemView.getContext();
imgThumbnail = (ImageView) itemView.findViewById(R.id.img_thumbnail);
tvspecies = (TextView) itemView.findViewById(R.id.tv_species);
imgThumbnail.setOnClickListener(this);
//to enable user clicking long n the cardview image
imgThumbnail.setOnLongClickListener(this);
}
#Override
public void onClick(View view) {
Intent intent = null;
switch (getPosition()) {
case 0:
intent = new Intent(context, Restaurant.class);
break;
case 1:
intent = new Intent(context, TestIntent.class);
break;
case 2:
intent = new Intent(context, TestIntent.class);
break;
case 3:
intent = new Intent(context, TestIntent.class);
break;
case 4:
intent = new Intent(context, TestIntent.class);
break;
case 5:
intent = new Intent(context, TestIntent.class);
break;
case 6:
intent = new Intent(context, TestIntent.class);
break;
default:
intent = new Intent(context, MainActivity.class);
break;
}
context.startActivity(intent);
}
#Override
public boolean onLongClick(View view) {
// Intent intent;
// intent = new Intent(context, Favourites.class);
// intent.putExtra(FAV, R.id.img_thumbnail);
// context.startActivity(intent);
Toast.makeText(context, "added to favourites", Toast.LENGTH_SHORT).show();
return false;
}
}
}
My String Array:
<string-array name="keywords">
<item>Restaurants</item>
<item>Churches</item>
<item>Laundry</item>
<item>Schools</item>
<item>Cinemas</item>
<item>Hospitals</item>
<item>Tech Centers</item>
<item>Clubs</item>
<item>Fashion House</item>
<item>Banks</item>
<item>Atms</item>
<item>Sport Centers</item>
<item>Supermarkets</item>
<item>Sitouts</item>
</string-array>
Use this Google API to get food and bars around the location,
https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=ADD_LATITUDE,ADD_LONGITUDE&radius=5000&types=food,bar&sensor=true&key=YOUR_GOOGLE_MAP_BROWSER_KEY
Enable GooglePlacesAPI from Google Developers Console.
Generate Browser Key not Android Key, it will not work in this case.
Add this in your AndroidManifest.xml:
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="YOUR_API_KEY"/>
also add this permission:
<uses-permission android:name="android.permission.INTERNET" />
Response:
You will get JSON response when you enter URL in browser.
Use this as your URL String that searches for specific places.
String loginURL = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=19.9974,73.7876113&radius=2000&type=SBH&name=atm&key=API_KEY_HERE";
The problem is your Nearby Search request contains types=Restaurants, but that isn't a valid value for the types parameter. The valid values are in Table 1 of Place Types documentation. E.g. instead of Restaurants you want restaurant.
A secondary issue is that types is a deprecated parameter. You're only passing one type at a time, so you can easily switch to the fully supported type parameter. See the deprecation notice in the Place Search documentation.

SKPOITrackerManager does not detect any POIs

I have created a small Android app which should track POIs. I navigate through a route and placed 10 trackable POIs at the beginning of the route and many other trackable POIs along the whole route. As I put annotations on the trackable POIs one can see that they are created. I want to track them with SKPOITrackerManager. But none of these POIs are tracked.
I implemented the SKPOITrackerListener and onUpdatePOIsinRadius() is called the first two times without any POIs added. The third time it is called (~ 2 minutes after the app I starting) it adds many POIs. But onReceivedPOIs() does not find the POIs. It is only called once. And the List<SKDetectedPOI> only has size one with a detected POI having an ID equal to -1.
Here is my complete code, containing two Activites.
MainActivity:
package com.example.michi.mapapplication;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.StatFs;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import com.skobbler.ngx.SKDeveloperKeyException;
import com.skobbler.ngx.SKMaps;
import com.skobbler.ngx.SKMapsInitSettings;
import com.skobbler.ngx.SKPrepareMapTextureListener;
import com.skobbler.ngx.SKPrepareMapTextureThread;
import com.skobbler.ngx.map.SKMapViewStyle;
import com.skobbler.ngx.navigation.SKAdvisorSettings;
import com.skobbler.ngx.util.SKLogging;
import com.skobbler.ngx.versioning.SKMapUpdateListener;
import com.skobbler.ngx.versioning.SKVersioningManager;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MainActivity extends AppCompatActivity implements SKPrepareMapTextureListener{
private final static String TAG = "MainActivity";
private String mapResourcesDirPath = "";
public static final long KILO = 1024;
public static final long MEGA = KILO * KILO;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String applicationPath = chooseStoragePath(this);
mapResourcesDirPath = applicationPath + "/" + "SKMaps/";
new SKPrepareMapTextureThread(this, mapResourcesDirPath, "SKMaps.zip", this).start();
if (initializeLibrary(this)) {
finish();
startActivity(new Intent(this, MapActivity.class));
}
}
private boolean initializeLibrary(final Activity context) {
SKLogging.enableLogs(true);
SKMapsInitSettings initMapSettings = new SKMapsInitSettings();
initMapSettings.setMapResourcesPaths(mapResourcesDirPath,
new SKMapViewStyle(mapResourcesDirPath + "daystyle/", "daystyle.json"));
final SKAdvisorSettings advisorSettings = initMapSettings.getAdvisorSettings();
advisorSettings.setAdvisorConfigPath(mapResourcesDirPath +"/Advisor");
advisorSettings.setResourcePath(mapResourcesDirPath +"/Advisor/Languages");
advisorSettings.setLanguage(SKAdvisorSettings.SKAdvisorLanguage.LANGUAGE_DE);
advisorSettings.setAdvisorVoice("en");
initMapSettings.setAdvisorSettings(advisorSettings);
try {
SKMaps.getInstance().initializeSKMaps(context, initMapSettings);
return true;
}catch (SKDeveloperKeyException exception){
exception.printStackTrace();
return false;
}
}
public static String chooseStoragePath(Context context) {
if (getAvailableMemorySize(Environment.getDataDirectory().getPath()) >= 50 * MEGA) {
if (context != null && context.getFilesDir() != null) {
return context.getFilesDir().getPath();
}
} else {
if ((context != null) && (context.getExternalFilesDir(null) != null)) {
if (getAvailableMemorySize(context.getExternalFilesDir(null).toString()) >= 50 * MEGA) {
return context.getExternalFilesDir(null).toString();
}
}
}
SKLogging.writeLog(TAG, "There is not enough memory on any storage, but return internal memory",
SKLogging.LOG_DEBUG);
if (context != null && context.getFilesDir() != null) {
return context.getFilesDir().getPath();
} else {
if ((context != null) && (context.getExternalFilesDir(null) != null)) {
return context.getExternalFilesDir(null).toString();
} else {
return null;
}
}
}
public static long getAvailableMemorySize(String path) {
StatFs statFs = null;
try {
statFs = new StatFs(path);
} catch (IllegalArgumentException ex) {
SKLogging.writeLog("SplashActivity", "Exception when creating StatF ; message = " + ex,
SKLogging.LOG_DEBUG);
}
if (statFs != null) {
Method getAvailableBytesMethod = null;
try {
getAvailableBytesMethod = statFs.getClass().getMethod("getAvailableBytes");
} catch (NoSuchMethodException e) {
SKLogging.writeLog(TAG, "Exception at getAvailableMemorySize method = " + e.getMessage(),
SKLogging.LOG_DEBUG);
}
if (getAvailableBytesMethod != null) {
try {
SKLogging.writeLog(TAG, "Using new API for getAvailableMemorySize method !!!", SKLogging.LOG_DEBUG);
return (Long) getAvailableBytesMethod.invoke(statFs);
} catch (IllegalAccessException e) {
return (long) statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
} catch (InvocationTargetException e) {
return (long) statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
}
} else {
return (long) statFs.getAvailableBlocks() * (long) statFs.getBlockSize();
}
} else {
return 0;
}
}
#Override
public void onMapTexturesPrepared(boolean b) {
initializeLibrary(this);
}
}
MapActivity:
package com.example.michi.mapapplication;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.skobbler.ngx.SKCoordinate;
import com.skobbler.ngx.map.SKAnimationSettings;
import com.skobbler.ngx.map.SKAnnotation;
import com.skobbler.ngx.map.SKCalloutView;
import com.skobbler.ngx.map.SKCoordinateRegion;
import com.skobbler.ngx.map.SKMapCustomPOI;
import com.skobbler.ngx.map.SKMapPOI;
import com.skobbler.ngx.map.SKMapSettings;
import com.skobbler.ngx.map.SKMapSurfaceListener;
import com.skobbler.ngx.map.SKMapSurfaceView;
import com.skobbler.ngx.map.SKMapViewHolder;
import com.skobbler.ngx.map.SKPOICluster;
import com.skobbler.ngx.map.SKScreenPoint;
import com.skobbler.ngx.navigation.SKNavigationListener;
import com.skobbler.ngx.navigation.SKNavigationManager;
import com.skobbler.ngx.navigation.SKNavigationSettings;
import com.skobbler.ngx.navigation.SKNavigationState;
import com.skobbler.ngx.poitracker.SKDetectedPOI;
import com.skobbler.ngx.poitracker.SKPOITrackerListener;
import com.skobbler.ngx.poitracker.SKPOITrackerManager;
import com.skobbler.ngx.poitracker.SKTrackablePOI;
import com.skobbler.ngx.poitracker.SKTrackablePOIRule;
import com.skobbler.ngx.poitracker.SKTrackablePOIType;
import com.skobbler.ngx.routing.SKRouteInfo;
import com.skobbler.ngx.routing.SKRouteJsonAnswer;
import com.skobbler.ngx.routing.SKRouteListener;
import com.skobbler.ngx.routing.SKRouteManager;
import com.skobbler.ngx.routing.SKRouteSettings;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.Bind;
import butterknife.ButterKnife;
import static com.skobbler.ngx.map.SKMapSettings.SKMapDisplayMode.MODE_2D;
import static com.skobbler.ngx.map.SKMapSettings.SKMapDisplayMode.MODE_3D;
public class MapActivity extends AppCompatActivity implements SKMapSurfaceListener, SKRouteListener, SKNavigationListener, SKPOITrackerListener {
public static final double SOURCE_LONGITUDE = 11.5;
public static final double SOURCE_LATITUDE = 48.12;
public static final double DEST_LONGITUDE = 11.5;
public static final double DEST_LATITUDE = 51.12;
private SKNavigationManager navigationManager;
private HashMap<Integer, SKTrackablePOI> trackablePOIs;
private SKPOITrackerManager poiTrackerManager;
protected SKMapSurfaceView mapView;
#Bind(R.id.view_group_map)
protected SKMapViewHolder mapHolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
ButterKnife.bind(this);
mapHolder.setMapSurfaceListener(this);
}
#Override
protected void onPause() {
super.onPause();
mapHolder.onPause();
}
#Override
protected void onResume() {
super.onResume();
mapHolder.onResume();
}
#Override
public void onActionPan() {}
#Override
public void onActionZoom() { }
#Override
public void onSurfaceCreated(SKMapViewHolder skMapViewHolder) {
mapView = mapHolder.getMapSurfaceView();
mapView.centerMapOnPosition(new SKCoordinate(11.5, 48.12));
launchRouteCalculation();
}
#Override
public void onMapRegionChanged(SKCoordinateRegion skCoordinateRegion) {
mapView.getMapSettings().setFollowerMode(SKMapSettings.SKMapFollowerMode.NONE);
final SKCalloutView mapPopup = mapHolder.getCalloutView();
mapPopup.setTitle("Fortsetzen").setVisibility(View.VISIBLE);
mapPopup.setViewColor(Color.argb(255, 200, 200, 255));
mapPopup.setOnLeftImageClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MapActivity.this, "Left image clicked", Toast.LENGTH_SHORT).show();
mapView.getMapSettings().setFollowerMode(SKMapSettings.SKMapFollowerMode.NAVIGATION);
mapPopup.setVisibility(View.GONE);
}
});
mapPopup.showAtLocation(new SKCoordinate(23.56, 46.77), true);
}
#Override
public void onMapRegionChangeStarted(SKCoordinateRegion skCoordinateRegion) {}
#Override
public void onMapRegionChangeEnded(SKCoordinateRegion skCoordinateRegion) {}
#Override
public void onDoubleTap(SKScreenPoint skScreenPoint) {}
#Override
public void onSingleTap(SKScreenPoint skScreenPoint) {}
#Override
public void onRotateMap() {}
#Override
public void onLongPress(SKScreenPoint skScreenPoint) {}
#Override
public void onInternetConnectionNeeded() {}
#Override
public void onMapActionDown(SKScreenPoint skScreenPoint) {}
#Override
public void onMapActionUp(SKScreenPoint skScreenPoint) {}
#Override
public void onPOIClusterSelected(SKPOICluster skpoiCluster) {}
#Override
public void onMapPOISelected(SKMapPOI skMapPOI) {}
#Override
public void onAnnotationSelected(SKAnnotation skAnnotation) {
}
#Override
public void onCustomPOISelected(SKMapCustomPOI skMapCustomPOI) {}
#Override
public void onCompassSelected() {
}
#Override
public void onCurrentPositionSelected() {}
#Override
public void onObjectSelected(int i) {}
#Override
public void onInternationalisationCalled(int i) {}
#Override
public void onDebugInfo(double v, float v1, double v2) { }
#Override
public void onBoundingBoxImageRendered(int i) {}
#Override
public void onGLInitializationError(String s) {}
private void launchRouteCalculation() {
SKRouteSettings route = new SKRouteSettings();
route.setStartCoordinate(new SKCoordinate(SOURCE_LONGITUDE, SOURCE_LATITUDE));
route.setDestinationCoordinate(new SKCoordinate(DEST_LONGITUDE, DEST_LATITUDE));
route.setNoOfRoutes(1);
route.setRouteMode(SKRouteSettings.SKRouteMode.CAR_FASTEST);
route.setRouteExposed(true);
SKRouteManager.getInstance().setRouteListener(this);
SKRouteManager.getInstance().calculateRoute(route);
}
#Override
public void onRouteCalculationCompleted(SKRouteInfo skRouteInfo) {}
#Override
public void onRouteCalculationFailed(SKRoutingErrorCode skRoutingErrorCode) {}
#Override
public void onAllRoutesCompleted() {
SKNavigationSettings navigationSettings = new SKNavigationSettings();
navigationSettings.setNavigationType(SKNavigationSettings.SKNavigationType.SIMULATION);
navigationManager = SKNavigationManager.getInstance();
navigationManager.setMapView(mapView);
navigationManager.setNavigationListener(this);
navigationManager.startNavigation(navigationSettings);
initTrackablePOIs();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
startPOITracking();
}
private void initTrackablePOIs() {
Log.w(getClass().getName(), "initTrackablePOIs(): ");
trackablePOIs = new HashMap<Integer, SKTrackablePOI>();
initOnlySomePOIs();
int i = 0;
double longitude, latitude;
for (double d = 0; d < 1; d+= 0.01) {
longitude = SOURCE_LONGITUDE + d * (DEST_LONGITUDE - SOURCE_LONGITUDE);
latitude = SOURCE_LATITUDE + d * (DEST_LATITUDE - SOURCE_LATITUDE);
trackablePOIs.put(i, new SKTrackablePOI(i, 1, longitude, latitude, -1, "STREET_NAME " + i));
SKAnnotation skAnnotation = new SKAnnotation(64000 + i);
skAnnotation.setAnnotationType(SKAnnotation.SK_ANNOTATION_TYPE_MARKER);
skAnnotation.setLocation(new SKCoordinate(longitude, latitude));
mapView.addAnnotation(skAnnotation, SKAnimationSettings.ANIMATION_PIN_DROP);
i++;
}
}
private void initOnlySomePOIs() {
double longitude, latitude;
longitude = SOURCE_LONGITUDE + 0.001;
latitude = SOURCE_LATITUDE + 0.001;
trackablePOIs.put(101, new SKTrackablePOI(101, 1, longitude, latitude, -1, "STREET_NAME 101"));
SKAnnotation skAnnotation1 = new SKAnnotation(101);
skAnnotation1.setAnnotationType(SKAnnotation.SK_ANNOTATION_TYPE_MARKER);
skAnnotation1.setLocation(new SKCoordinate(longitude, latitude));
mapView.addAnnotation(skAnnotation1, SKAnimationSettings.ANIMATION_PIN_DROP);
longitude = SOURCE_LONGITUDE + 0.001;
latitude = SOURCE_LATITUDE - 0.001;
trackablePOIs.put(102, new SKTrackablePOI(102, 1, longitude, latitude, -1, "STREET_NAME 102"));
SKAnnotation skAnnotation2 = new SKAnnotation(102);
skAnnotation2.setAnnotationType(SKAnnotation.SK_ANNOTATION_TYPE_MARKER);
skAnnotation2.setLocation(new SKCoordinate(longitude, latitude));
mapView.addAnnotation(skAnnotation2, SKAnimationSettings.ANIMATION_PIN_DROP);
longitude = SOURCE_LONGITUDE - 0.001;
latitude = SOURCE_LATITUDE + 0.001;
trackablePOIs.put(103, new SKTrackablePOI(103, 1, longitude, latitude, -1, "STREET_NAME 103"));
SKAnnotation skAnnotation3 = new SKAnnotation(103);
skAnnotation3.setAnnotationType(SKAnnotation.SK_ANNOTATION_TYPE_MARKER);
skAnnotation3.setLocation(new SKCoordinate(longitude, latitude));
mapView.addAnnotation(skAnnotation3, SKAnimationSettings.ANIMATION_PIN_DROP);
longitude = SOURCE_LONGITUDE - 0.001;
latitude = SOURCE_LATITUDE - 0.001;
trackablePOIs.put(104, new SKTrackablePOI(104, 1, longitude, latitude, -1, "STREET_NAME 104"));
SKAnnotation skAnnotation4 = new SKAnnotation(104);
skAnnotation4.setAnnotationType(SKAnnotation.SK_ANNOTATION_TYPE_MARKER);
skAnnotation4.setLocation(new SKCoordinate(longitude, latitude));
mapView.addAnnotation(skAnnotation4, SKAnimationSettings.ANIMATION_PIN_DROP);
longitude = SOURCE_LONGITUDE + 0.002;
latitude = SOURCE_LATITUDE + 0.002;
trackablePOIs.put(105, new SKTrackablePOI(105, 105, longitude, latitude, -1, "STREET_NAME 105"));
SKAnnotation skAnnotation5 = new SKAnnotation(105);
skAnnotation5.setAnnotationType(SKAnnotation.SK_ANNOTATION_TYPE_MARKER);
skAnnotation5.setLocation(new SKCoordinate(longitude, latitude));
mapView.addAnnotation(skAnnotation5, SKAnimationSettings.ANIMATION_PIN_DROP);
longitude = SOURCE_LONGITUDE + 0.002;
latitude = SOURCE_LATITUDE - 0.002;
trackablePOIs.put(106, new SKTrackablePOI(106, 1, longitude, latitude, -1, "STREET_NAME 106"));
SKAnnotation skAnnotation6 = new SKAnnotation(106);
skAnnotation6.setAnnotationType(SKAnnotation.SK_ANNOTATION_TYPE_MARKER);
skAnnotation6.setLocation(new SKCoordinate(longitude, latitude));
mapView.addAnnotation(skAnnotation6, SKAnimationSettings.ANIMATION_PIN_DROP);
longitude = SOURCE_LONGITUDE - 0.002;
latitude = SOURCE_LATITUDE + 0.002;
trackablePOIs.put(107, new SKTrackablePOI(107, 1, longitude, latitude, -1, "STREET_NAME 107"));
SKAnnotation skAnnotation7 = new SKAnnotation(107);
skAnnotation7.setAnnotationType(SKAnnotation.SK_ANNOTATION_TYPE_MARKER);
skAnnotation7.setLocation(new SKCoordinate(longitude, latitude));
mapView.addAnnotation(skAnnotation7, SKAnimationSettings.ANIMATION_PIN_DROP);
longitude = SOURCE_LONGITUDE - 0.001;
latitude = SOURCE_LATITUDE - 0.001;
trackablePOIs.put(108, new SKTrackablePOI(108, 1, longitude, latitude, -1, "STREET_NAME 108"));
SKAnnotation skAnnotation8 = new SKAnnotation(108);
skAnnotation8.setAnnotationType(SKAnnotation.SK_ANNOTATION_TYPE_MARKER);
skAnnotation8.setLocation(new SKCoordinate(longitude, latitude));
mapView.addAnnotation(skAnnotation8, SKAnimationSettings.ANIMATION_PIN_DROP);
longitude = 9.767972;
latitude = 52.378958;
trackablePOIs.put(109, new SKTrackablePOI(109, 1, longitude, latitude, -1, "STREET_NAME 109"));
SKAnnotation skAnnotation9 = new SKAnnotation(109);
skAnnotation9.setAnnotationType(SKAnnotation.SK_ANNOTATION_TYPE_MARKER);
skAnnotation9.setLocation(new SKCoordinate(longitude, latitude));
mapView.addAnnotation(skAnnotation9, SKAnimationSettings.ANIMATION_PIN_DROP);
}
private void startPOITracking() {
SKTrackablePOIRule rule = new SKTrackablePOIRule();
rule.setAerialDistance(5000); // this would be our main constraint, stating that all the POIs with 5000m, aerial distance should be detected
rule.setNumberOfTurns(100); // this has to be increased – otherwise some points will be disconsidered
rule.setRouteDistance(10000);//this has to be increased as the real road route will be longer than the aerial distance
rule.setMinSpeedIgnoreDistanceAfterTurn(20); //decrease this to evaluate all candidates
rule.setMaxDistanceAfterTurn(10000); //increase this to make sure we don't exclude any candidates
rule.setEliminateIfUTurn(false); // setting this to true (default) excludes points that require us to make an U-turn to get to them
rule.setPlayAudioWarning(false);
poiTrackerManager = new SKPOITrackerManager(this);
poiTrackerManager.startPOITrackerWithRadius(1500, 0.5);
poiTrackerManager.setRuleForPOIType(SKTrackablePOIType.SPEEDCAM, rule);
}
#Override
public void onServerLikeRouteCalculationCompleted(SKRouteJsonAnswer skRouteJsonAnswer) {}
#Override
public void onOnlineRouteComputationHanging(int i) {}
#Override
public void onDestinationReached() {}
#Override
public void onSignalNewAdviceWithInstruction(String s) {}
#Override
public void onSignalNewAdviceWithAudioFiles(String[] strings, boolean b) {}
#Override
public void onSpeedExceededWithAudioFiles(String[] strings, boolean b) {}
#Override
public void onSpeedExceededWithInstruction(String s, boolean b) {}
#Override
public void onUpdateNavigationState(SKNavigationState skNavigationState) { Log.v(getClass().getName(), "onUpdateNavigationState: " + skNavigationState.toString());}
#Override
public void onReRoutingStarted() {}
#Override
public void onFreeDriveUpdated(String s, String s1, SKNavigationState.SKStreetType skStreetType, double v, double v1) {}
#Override
public void onViaPointReached(int i) {}
#Override
public void onVisualAdviceChanged(boolean b, boolean b1, SKNavigationState skNavigationState) {}
#Override
public void onTunnelEvent(boolean b) {}
#Override
public void onFcdTripStarted(String s) {}
#Override
public void onUpdatePOIsInRadius(double latitude, double longitude, int radius) {
Log.i(getClass().getName(), "onUpdatePOIsInRadius(): ");
// set the POIs to be tracked by the POI tracker
for (SKTrackablePOI skTrackablePOI : trackablePOIs.values()) {
Log.i(getClass().getName(), "onUpdatePOIsInRadius() skTrackablePOI: " + skTrackablePOI);
}
poiTrackerManager.setTrackedPOIs(SKTrackablePOIType.SPEEDCAM, new ArrayList<SKTrackablePOI>(trackablePOIs.values()));
}
#Override
public void onReceivedPOIs(SKTrackablePOIType type, List<SKDetectedPOI> detectedPois) {
Log.i(getClass().getName(), "onReceivedPOIs() detectedPois.size(): " + detectedPois.size());
if (detectedPois.size() == 1 && detectedPois.get(0).getPoiID() == -1) {
return;
}
for (SKDetectedPOI skDetectedPOI : detectedPois) {
Log.i(getClass().getName(), "onReceivedPOIs() skDetectedPOI: " + skDetectedPOI);
SKAnnotation skAnnotation = new SKAnnotation(skDetectedPOI.getPoiID());
skAnnotation.setAnnotationType(SKAnnotation.SK_ANNOTATION_TYPE_GREEN);
skAnnotation.setLocation(trackablePOIs.get(skDetectedPOI.getPoiID()).getCoordinate());
mapView.addAnnotation(skAnnotation, SKAnimationSettings.ANIMATION_PIN_DROP);
}
}
}
I don't know why the tracker isn't working. :(
The rules are OK.
You'll need to modify your logic to something similar to the demo project:
(the following code is to be added in the demo project, MapActivity.java, the onAllRoutesCompleted callback, the currentMapOption == MapOption.POI_TRACKING branch)
poiTrackingManager.startPOITrackerWithRadius(10000, 0.5);
// set warning rules for trackable POIs
// SKTrackablePOIType myType =SKTrackablePOIType.forInt(1000);
SKTrackablePOIRule rule = new SKTrackablePOIRule();
rule.setAerialDistance(5000); // this would be our main constraint, stating that all the POIs with 5000m, aerial distance should be detected
rule.setNumberOfTurns(100); // this has to be increased – otherwise some points will be disconsidered
rule.setRouteDistance(10000);//this has to be increased as the real road route will be longer than the aerial distance
rule.setMinSpeedIgnoreDistanceAfterTurn(20); //decrease this to evaluate all candidates
rule.setMaxDistanceAfterTurn(10000); //increase this to make sure we don't exclude any candidates
rule.setEliminateIfUTurn(false); // setting this to true (default) excludes points that require us to make an U-turn to get to them
rule.setPlayAudioWarning(false);
poiTrackingManager.setRuleForPOIType(SKTrackablePOIType.SPEEDCAM, rule);
launchNavigation();
In onUpdatePOIsInRadius you have to make the "refreshed" POI list available to the tracker. This callback will be triggered by the tracker once the refreshMargin condition is reached.
#Override
public void onUpdatePOIsInRadius(double latitude, double longitude, int radius) {
// set the POIs to be tracked by the POI tracker
// SKTrackablePOIType myType =SKTrackablePOIType.forInt(1000);
poiTrackingManager.setTrackedPOIs(SKTrackablePOIType.SPEEDCAM,
new ArrayList<SKTrackablePOI>(trackablePOIs.values()));
}
In onReceivedPOIs you'll get information about the POIs that were detected:
public void onReceivedPOIs(SKTrackablePOIType type, List<SKDetectedPOI> detectedPois) {
//add code here to handle the detected POIs
}
I've edited the vanilla demo project with the above code (with the default definition of points to track) and I get lots of notifications.
Depending on the "density" of your tracked POIs, you might want to reduce the refreshMargin (and trigger POI set updates more often) - i.e. poiTrackerManager.startPOITrackerWithRadius(5000, 0.1);
Also see http://sdkblog.skobbler.com/detecting-tracking-pois-in-your-way/ for more insights into the POI tracking functionality

Facebook friendliest is not retrieving

I am using the scrumptious documentation to show to those friends who are using my application. I have followed the tutorials here
https://developers.facebook.com/docs/android/scrumptious/show-friends?locale=en_GB
I have tried every combination but it is not retrieving the friends who are using my application
I have used three class
scrumptious.java
public class ScrumptiousApplication extends Application {
private List<GraphUser> selectedUsers;
public List<GraphUser> getSelectedUsers() {
return selectedUsers;
}
public void setSelectedUsers(List<GraphUser> selectedUsers) {
this.selectedUsers = selectedUsers;
}
}
Selectionfragment.java
package com.example.facebooknew;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.HttpMethod;
import com.facebook.Request;
import com.facebook.RequestAsyncTask;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionDefaultAudience;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.internal.SessionTracker;
import com.facebook.internal.Utility;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphObjectList;
import com.facebook.model.GraphUser;
import com.facebook.widget.LoginButton;
import com.facebook.widget.ProfilePictureView;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class SelectionFragment extends Fragment{
/* In this fragment the data from the user profile is returned like profile , name etc
* (non-Javadoc)
* #see android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater, android.view.ViewGroup, android.os.Bundle)
*/
private static final String TAG = "SelectionFragment";
private static final List<String> PERMISSIONS = Arrays.asList(
"email","user_location");
private static final int REAUTH_ACTIVITY_CODE = 100;
private ProfilePictureView profilePictureView;
private TextView userNameView;
private TextView firstName;
private TextView lastName;
private TextView Location;
private UiLifecycleHelper uiHelper;
private List<GraphUser> selectedUsers;
private ListView listView;
private List<BaseListElement> listElements;
private static final String FRIENDS_KEY = "friends";
private TextView userInfoTextView;
private Button sendRequestButton;
private String requestId;
private Session.StatusCallback callback = new Session.StatusCallback() {
#Override
public void call(final Session session, final SessionState state, final Exception exception) {
onSessionStateChange(session, state, exception);
}
};
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Check for an incoming notification. Save the info
Uri intentUri = getActivity().getIntent().getData();
if (intentUri != null) {
String requestIdParam = intentUri.getQueryParameter("request_ids");
if (requestIdParam != null) {
String array[] = requestIdParam.split(",");
requestId = array[0];
Log.i(TAG, "Request id: "+requestId);
Toast.makeText(getActivity().getApplicationContext(),requestId, Toast.LENGTH_LONG).show();
}
}
}
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.selection, container, false);
// Find the user's profile picture custom view
profilePictureView = (ProfilePictureView) view.findViewById(R.id.selection_profile_pic);
profilePictureView.setCropped(true);
// Find the user's name view
userNameView = (TextView) view.findViewById(R.id.selection_user_name);
firstName= (TextView) view.findViewById(R.id.selection_first_name);
//lastName = (TextView) view.findViewById(R.id.selection_last_name);
//Location = (TextView) view.findViewById(R.id.selection_location);
//userInfoTextView = (TextView) view.findViewById(R.id.userInfoTextView);
sendRequestButton=(Button) view.findViewById(R.id.sendRequestButton);
uiHelper = new UiLifecycleHelper(getActivity(), callback);
uiHelper.onCreate(savedInstanceState);
Session session = Session.getActiveSession();
if (session != null && session.isOpened()) {
// Get the user's data
makeMeRequest(session);
}
sendRequestButton.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
sendRequestDialog();
}
});
// Find the list view
listView = (ListView) view.findViewById(R.id.selection_list);
// Set up the list view items, based on a list of
// BaseListElement items
listElements = new ArrayList<BaseListElement>();
// Add an item for the friend picker
listElements.add(new PeopleListElement(0));
// Set the list view adapter
listView.setAdapter(new ActionListAdapter(getActivity(),
R.id.selection_list, listElements));
if (savedInstanceState != null) {
// Restore the state for each list element
for (BaseListElement listElement : listElements) {
listElement.restoreState(savedInstanceState);
}
}
return view;
}
private void makeMeRequest(final Session session) {
// Make an API call to get user data and define a
// new callback to handle the response.
Request request = Request.newMeRequest(session,
new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
// If the response is successful
if (session == Session.getActiveSession()) {
if (user != null) {
// Set the id for the ProfilePictureView
// view that in turn displays the profile picture.
profilePictureView.setProfileId(user.getId());
// Set the Textview's text to the user's name.
userNameView.setText(user.getName());
//firstName.setText(user.getFirstName());
//lastName.setText(user.getLastName());
//Location.setText(user.getProperty("email").toString());
}
}
if (response.getError() != null) {
// Handle errors, will do so later.
}
}
});
request.executeAsync();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REAUTH_ACTIVITY_CODE) {
uiHelper.onActivityResult(requestCode, resultCode, data);
} else if (resultCode == Activity.RESULT_OK) {
// Do nothing for now
}else if (resultCode == Activity.RESULT_OK &&
requestCode >= 0 && requestCode < listElements.size()) {
listElements.get(requestCode).onActivityResult(data);
}
}
private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
if (session != null && session.isOpened()) {
// Get the user's data.
if (state.isOpened() && requestId != null) {
getRequestData(requestId);
}
if (state.isOpened()) {
sendRequestButton.setVisibility(View.VISIBLE);
} else if (state.isClosed()) {
sendRequestButton.setVisibility(View.INVISIBLE);
}
makeMeRequest(session);
}
}
#Override
public void onResume() {
super.onResume();
uiHelper.onResume();
}
#Override
public void onSaveInstanceState(Bundle bundle) {
super.onSaveInstanceState(bundle);
for (BaseListElement listElement : listElements) {
listElement.onSaveInstanceState(bundle);
}
uiHelper.onSaveInstanceState(bundle);
}
#Override
public void onPause() {
super.onPause();
uiHelper.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
uiHelper.onDestroy();
}
private interface MyGraphLanguage extends GraphObject {
// Getter for the ID field
String getId();
// Getter for the Name field
String getName();
}
private class ActionListAdapter extends ArrayAdapter<BaseListElement> {
private List<BaseListElement> listElements;
public ActionListAdapter(Context context, int resourceId,
List<BaseListElement> listElements) {
super(context, resourceId, listElements);
this.listElements = listElements;
// Set up as an observer for list item changes to
// refresh the view.
for (int i = 0; i < listElements.size(); i++) {
listElements.get(i).setAdapter(this);
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater =
(LayoutInflater) getActivity()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.listitem, null);
}
BaseListElement listElement = listElements.get(position);
if (listElement != null) {
view.setOnClickListener(listElement.getOnClickListener());
ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView text1 = (TextView) view.findViewById(R.id.text1);
TextView text2 = (TextView) view.findViewById(R.id.text2);
if (icon != null) {
icon.setImageDrawable(listElement.getIcon());
}
if (text1 != null) {
text1.setText(listElement.getText1());
}
if (text2 != null) {
text2.setText(listElement.getText2());
}
else{
Toast.makeText(getActivity().getApplicationContext(),"No data received " ,Toast.LENGTH_LONG).show();
}
}
return view;
}
}
/* It is private class used to populate the friend and bring up the friends list*/
private class PeopleListElement extends BaseListElement {
public PeopleListElement(int requestCode) {
super(getActivity().getResources().getDrawable(R.drawable.add_friends),
getActivity().getResources().getString(R.string.action_people),
getActivity().getResources().getString(R.string.action_people_default),
requestCode);
}
/* this event will trigger the picker activity*/
#Override
protected View.OnClickListener getOnClickListener() {
return new View.OnClickListener() {
#Override
public void onClick(View view) {
// Do nothing for now
startPickerActivity(PickerActivity.FRIEND_PICKER, getRequestCode());
}
};
}
private void setUsersText() {
String text = null;
if (selectedUsers != null) {
// If there is one friend
if (selectedUsers.size() == 1) {
text = String.format(getResources()
.getString(R.string.single_user_selected),
selectedUsers.get(0).getName());
} else if (selectedUsers.size() == 2) {
// If there are two friends
text = String.format(getResources()
.getString(R.string.two_users_selected),
selectedUsers.get(0).getName(),
selectedUsers.get(1).getName());
} else if (selectedUsers.size() > 2) {
// If there are more than two friends
text = String.format(getResources()
.getString(R.string.multiple_users_selected),
selectedUsers.get(0).getName(),
(selectedUsers.size() - 1));
}
}
if (text == null) {
// If no text, use the placeholder text
text = getResources()
.getString(R.string.action_people_default);
}
// Set the text in list element. This will notify the
// adapter that the data has changed to
// refresh the list view.
setText2(text);
}
#Override
protected void onActivityResult(Intent data) {
selectedUsers = ((ScrumptiousApplication) getActivity()
.getApplication())
.getSelectedUsers();
setUsersText();
notifyDataChanged();
}
#Override
protected void onSaveInstanceState(Bundle bundle) {
if (selectedUsers != null) {
bundle.putByteArray(FRIENDS_KEY,
getByteArray(selectedUsers));
}
}
private byte[] getByteArray(List<GraphUser> users) {
// convert the list of GraphUsers to a list of String
// where each element is the JSON representation of the
// GraphUser so it can be stored in a Bundle
List<String> usersAsString = new ArrayList<String>(users.size());
for (GraphUser user : users) {
usersAsString.add(user.getInnerJSONObject().toString());
}
try {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
new ObjectOutputStream(outputStream).writeObject(usersAsString);
return outputStream.toByteArray();
} catch (IOException e) {
Log.e(TAG, "Unable to serialize users.", e);
}
return null;
}
private List<GraphUser> restoreByteArray(byte[] bytes) {
try {
#SuppressWarnings("unchecked")
List<String> usersAsString =
(List<String>) (new ObjectInputStream
(new ByteArrayInputStream(bytes)))
.readObject();
if (usersAsString != null) {
List<GraphUser> users = new ArrayList<GraphUser>
(usersAsString.size());
for (String user : usersAsString) {
GraphUser graphUser = GraphObject.Factory
.create(new JSONObject(user),
GraphUser.class);
users.add(graphUser);
}
return users;
}
} catch (ClassNotFoundException e) {
Log.e(TAG, "Unable to deserialize users.", e);
} catch (IOException e) {
Log.e(TAG, "Unable to deserialize users.", e);
} catch (JSONException e) {
Log.e(TAG, "Unable to deserialize users.", e);
}
return null;
}
#Override
protected boolean restoreState(Bundle savedState) {
byte[] bytes = savedState.getByteArray(FRIENDS_KEY);
if (bytes != null) {
selectedUsers = restoreByteArray(bytes);
setUsersText();
return true;
}
return false;
}
}
/* This function is responsible for launching the freind picker activity*/
private void startPickerActivity(Uri data, int requestCode) {
Intent intent = new Intent();
intent.setData(data);
intent.setClass(getActivity(), PickerActivity.class);
startActivityForResult(intent, requestCode);
}
public void facebookSession(Session session){
//session= Session.getActiveSession();
Session.OpenRequest request = new Session.OpenRequest(this);
request.setPermissions(Arrays.asList("basic_info","email","location"));
request.setCallback( new Session.StatusCallback() {
// callback when session changes state
#Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request.newMeRequest(session, new Request.GraphUserCallback() {
#Override
public void onCompleted(GraphUser user, Response response) {
if (user != null) {
Toast.makeText(SelectionFragment.this.getActivity(), "User email is:"+user.getProperty("email"), Toast.LENGTH_SHORT).show(); }
else {
Toast.makeText(SelectionFragment.this.getActivity(), "Error User Null", Toast.LENGTH_SHORT).show();
}
}
}).executeAsync();
}
}
}); //end of call;
session.openForRead(request); //now do the request above
}
private void sendRequestDialog() {
Bundle params = new Bundle();
params.putString("message", "Learn how to make your Android apps social");
params.putString("data",
"https://play.google.com/store/apps/details?id=de.j4velin.mapsmeasure&hl=en");
WebDialog requestsDialog = (
new WebDialog.RequestsDialogBuilder(getActivity(),
Session.getActiveSession(),
params))
.setOnCompleteListener(new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error != null) {
if (error instanceof FacebookOperationCanceledException) {
Toast.makeText(getActivity().getApplicationContext(),
"Request cancelled",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Network Error",
Toast.LENGTH_SHORT).show();
}
} else {
final String requestId = values.getString("request");
if (requestId != null) {
Toast.makeText(getActivity().getApplicationContext(),
"Request sent",
Toast.LENGTH_SHORT).show();
Toast.makeText(getActivity().getApplicationContext(), requestId, Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Request cancelled",
Toast.LENGTH_SHORT).show();
}
}
}
})
.build();
requestsDialog.show();
}
private void getRequestData(final String inRequestId) {
// Create a new request for an HTTP GET with the
// request ID as the Graph path.
Request request = new Request(Session.getActiveSession(),
inRequestId, null, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Process the returned response
GraphObject graphObject = response.getGraphObject();
FacebookRequestError error = response.getError();
// Default message
String message = "Incoming request";
if (graphObject != null) {
// Check if there is extra data
if (graphObject.getProperty("data") != null) {
try {
// Get the data, parse info to get the key/value info
JSONObject dataObject =
new JSONObject((String)graphObject.getProperty("data"));
// Get the value for the key - badge_of_awesomeness
String badge =
dataObject.getString("badge_of_awesomeness");
// Get the value for the key - social_karma
String karma =
dataObject.getString("social_karma");
// Get the sender's name
JSONObject fromObject =
(JSONObject) graphObject.getProperty("from");
String sender = fromObject.getString("name");
String title = sender+" sent you a gift";
// Create the text for the alert based on the sender
// and the data
message = title + "\n\n" +
"Badge: " + badge +
" Karma: " + karma;
} catch (JSONException e) {
message = "Error getting request info";
}
} else if (error != null) {
message = "Error getting request info";
}
}
Toast.makeText(getActivity().getApplicationContext(),
message,
Toast.LENGTH_LONG).show();
}
});
// Execute the request asynchronously.
Request.executeBatchAsync(request);
}
}
And I have an abstarct baselist element class

how to call Activity asynctask from custom adapter in android

I have made an activity in that i have a listView and ,I have Implemeted a custom adapter for that ListView ,I have implemeted ListItem's textView's Clickevnet,In That I want to call my activity's AsyncTAk inside that customAdapter,CAn anybuddy tell me how can i do that? my code is as below:
main.java
package com.epe.yehki.ui;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.epe.yehki.adapter.BuyingRequestAdapter;
import com.epe.yehki.backend.BackendAPIService;
import com.epe.yehki.uc.Header;
import com.epe.yehki.util.Const;
import com.epe.yehki.util.Pref;
import com.epe.yehki.util.Utils;
import com.example.yehki.R;
public class BuyingreqActivity extends Activity implements OnClickListener {
Button viewReq, postReq;
EditText productName;
TextView productCategory;
TextView expTime;
TextView productDesc;
TextView estOrderQty;
ImageView proImg;
Button send;
ImageView iv_fav_menu;
private int flag = 1;
ScrollView scr_post;
RelativeLayout scr_view;
RelativeLayout quote_view;
private ProgressDialog pDialog;
String viewURL, postURL;
JSONObject jsonObj;
JSONArray requestes = null;
JSONArray quotes = null;
ArrayList<HashMap<String, String>> reqList;
ArrayList<HashMap<String, String>> queList;
private BuyingRequestAdapter buyingRequestContent;
RelativeLayout rl_botm;
ListView lv;
Header header;
Calendar dateandtime;
private static final int PICK_FROM_CAMERA = 100;
private static final int PICK_FROM_GALLERY = 200;
private Uri picUri;
int la, lo;
final int CAMERA_CAPTURE = 1;
private static String fileName;
Intent in = null;
ListView quoteList;
private String imagePath;
private Uri imageUri;
String buyer_request_id, reqID;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_buying_request);
InitializeView();
productCategory.setOnClickListener(this);
send.setOnClickListener(this);
expTime.setOnClickListener(this);
proImg.setOnClickListener(this);
dateandtime = Calendar.getInstance(Locale.US);
header.back.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
reqList = new ArrayList<HashMap<String, String>>();
queList = new ArrayList<HashMap<String, String>>();
viewReq.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag = 2;
reqList.clear();
iv_fav_menu.setBackgroundResource(R.drawable.tab_two_fav);
new GetBuyingReqList().execute();
scr_view.setVisibility(View.VISIBLE);
quote_view.setVisibility(View.GONE);
rl_botm.setVisibility(View.GONE);
scr_post.setVisibility(View.GONE);
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
in = new Intent(getApplicationContext(), BuyingRequestDetailActivity.class);
// getting ProductId from the tag...
reqID = reqList.get(position).get(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::;;THE INTENT FOR THE resuest DETIALS ACTIVITY=================" + reqID);
in.putExtra(Const.TAG_BUYING_REQUEST_ID, reqID);
startActivity(in);
}
});
postReq.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
flag = 1;
iv_fav_menu.setBackgroundResource(R.drawable.tab_one_fav);
quote_view.setVisibility(View.GONE);
scr_post.setVisibility(View.VISIBLE);
rl_botm.setVisibility(View.VISIBLE);
scr_view.setVisibility(View.GONE);
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tv_pro_cat:
break;
case R.id.tv_pro_exp_tym:
DatePickerDailog dp = new DatePickerDailog(BuyingreqActivity.this, dateandtime, new DatePickerDailog.DatePickerListner() {
#Override
public void OnDoneButton(Dialog datedialog, Calendar c) {
datedialog.dismiss();
dateandtime.set(Calendar.YEAR, c.get(Calendar.YEAR));
dateandtime.set(Calendar.MONTH, c.get(Calendar.MONTH));
dateandtime.set(Calendar.DAY_OF_MONTH, c.get(Calendar.DAY_OF_MONTH));
expTime.setText(new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()));
}
#Override
public void OnCancelButton(Dialog datedialog) {
// TODO Auto-generated method stub
datedialog.dismiss();
}
});
dp.show();
break;
case R.id.btn_send:
new postBuyingReqList().execute();
break;
case R.id.iv_img:
showCustomeAlert2(BuyingreqActivity.this, "Yehki", "From Camera", "From Gallery");
break;
}
}
#SuppressWarnings("deprecation")
private void showCustomeAlert2(Context context, String title, String rightButton, String leftButton) {
final Dialog dialog = new Dialog(BuyingreqActivity.this);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
dialog.getWindow().setLayout(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
dialog.setContentView(R.layout.popup_alert);
dialog.setCancelable(false);
final ImageView btn_lft = (ImageView) dialog.findViewById(R.id.iv_left);
final ImageView btn_rgt = (ImageView) dialog.findViewById(R.id.iv_right);
final Button cancel = (Button) dialog.findViewById(R.id.btn_cancle);
final TextView btn_left = (TextView) dialog.findViewById(R.id.btnLeft);
final TextView btn_right = (TextView) dialog.findViewById(R.id.btnRight);
btn_left.setText(leftButton);
btn_right.setText(rightButton);
cancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
btn_rgt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
try {
System.out.println("=========== perform click ==============");
String mediaStorageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getPath();
fileName = "user_" + Pref.getValue(BuyingreqActivity.this, Const.PREF_USER_ID, 0) + "_" + System.currentTimeMillis() + ".png";
imageUri = Uri.fromFile(new File(Const.DIR_USER + "/" + fileName));
System.out.println(" PATH ::: " + imageUri);
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(cameraIntent, CAMERA_CAPTURE);
} catch (ActivityNotFoundException anfe) {
String errorMessage = "Whoops - your device doesn't support capturing images!";
}
dialog.dismiss();
}
});
btn_lft.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
// call android default gallery
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// ******** code for crop image
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 0);
intent.putExtra("aspectY", 0);
intent.putExtra("outputX", 200);
intent.putExtra("outputY", 200);
try {
intent.putExtra("return-data", true);
startActivityForResult(Intent.createChooser(intent, "Complete action using"), PICK_FROM_GALLERY);
} catch (ActivityNotFoundException e) {
e.printStackTrace();
}
dialog.dismiss();
}
});
dialog.show();
}
void InitializeView() {
iv_fav_menu = (ImageView) findViewById(R.id.iv_fav_menu);
viewReq = (Button) findViewById(R.id.btn_view);
postReq = (Button) findViewById(R.id.btn_post);
scr_post = (ScrollView) findViewById(R.id.scr_post);
scr_view = (RelativeLayout) findViewById(R.id.scr_view);
quote_view = (RelativeLayout) findViewById(R.id.quote_view);
lv = (ListView) findViewById(R.id.req_list);
rl_botm = (RelativeLayout) findViewById(R.id.rl_botm);
header = (Header) findViewById(R.id.headerBuying);
header.title.setText("Post Buying Request");
proImg = (ImageView) findViewById(R.id.iv_img);
quoteList = (ListView) findViewById(R.id.quote_list);
productName = (EditText) findViewById(R.id.et_pro_name);
productCategory = (TextView) findViewById(R.id.tv_pro_cat);
expTime = (TextView) findViewById(R.id.tv_pro_exp_tym);
productDesc = (EditText) findViewById(R.id.et_pro_desc);
estOrderQty = (TextView) findViewById(R.id.et_est_qty);
send = (Button) findViewById(R.id.btn_send);
}
/*
* getting buying request list...!!!
*/
private class GetBuyingReqList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "");
query = query.replace(" ", "%20");
viewURL = Const.API_BUYING_REQUEST_LIST + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyer_request_id = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyer_request_id);
String subject = c.getString(Const.TAG_PRODUCT_NAME);
String date_modified = c.getString(Const.TAG_DATE_MODIFIED);
String expired_date = c.getString(Const.TAG_EXPIRY_DATE);
String quote_count = c.getString(Const.TAG_QUOTE_COUNT);
String buying_request_status = c.getString(Const.TAG_BUYING_REQUEST_STATUS);
HashMap<String, String> request = new HashMap<String, String>();
request.put(Const.TAG_BUYING_REQUEST_ID, buyer_request_id);
request.put(Const.TAG_PRODUCT_NAME, subject);
request.put(Const.TAG_DATE_MODIFIED, date_modified);
request.put(Const.TAG_EXPIRY_DATE, expired_date);
request.put(Const.TAG_QUOTE_COUNT, quote_count);
request.put(Const.TAG_BUYING_REQUEST_STATUS, buying_request_status);
reqList.add(request);
System.out.println("::::::::::::::::Is filled:::::::::::" + reqList.size());
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
buyingRequestContent = new BuyingRequestAdapter(BuyingreqActivity.this, reqList);
lv.setAdapter(buyingRequestContent);
}
}
/*
* getting qoute List...!!!
*/
public class GetQuoteList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
String query = "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&buyer_request_id=" + reqID;
query = query.replace(" ", "%20");
viewURL = Const.API_QUOTE_RECIEVED + query;
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::ADDRESS URL:::::::::::::::::" + viewURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(viewURL, BackendAPIService.GET);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.has(Const.TAG_BUYING_REQUEST)) {
System.out.println("::::::::::::::::true::::::::::::::::" + jsonObj.has(Const.TAG_ADDRESS_LIST));
requestes = jsonObj.getJSONArray(Const.TAG_BUYING_REQUEST);
if (requestes != null && requestes.length() != 0) {
// looping through All Contacts
System.out.println(":::::::::::FLAG IN SUB:::::::::::" + flag);
for (int i = 0; i < requestes.length(); i++) {
JSONObject c = requestes.getJSONObject(i);
buyer_request_id = c.getString(Const.TAG_BUYING_REQUEST_ID);
System.out.println(":::::::::::::::MY buying request:::::::::::::" + buyer_request_id);
String product_name = c.getString(Const.TAG_PRODUCT_NAME);
String quote_id = c.getString(Const.TAG_QUOTE_ID);
String supplier_name = c.getString(Const.TAG_SUPPLIER_NAME);
String status = c.getString(Const.TAG_STATUS);
HashMap<String, String> quote = new HashMap<String, String>();
quote.put(Const.TAG_BUYING_REQUEST_ID, buyer_request_id);
quote.put(Const.TAG_PRODUCT_NAME, product_name);
quote.put(Const.TAG_QUOTE_ID, quote_id);
quote.put(Const.TAG_EXPIRY_DATE, supplier_name);
quote.put(Const.TAG_QUOTE_COUNT, status);
reqList.add(quote);
System.out.println("::::::::::::::::Is filled:::::::::::" + reqList.size());
}
}
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
*
* */
buyingRequestContent = new BuyingRequestAdapter(BuyingreqActivity.this, reqList);
lv.setAdapter(buyingRequestContent);
}
}
/*
* post Buying Request api()...!!!
*/
private class postBuyingReqList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(BuyingreqActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postURL = Const.API_BUYING_REQUEST + "?customer_id=" + Pref.getValue(BuyingreqActivity.this, Const.PREF_CUSTOMER_ID, "") + "&product_name=" + productName.getText().toString().trim()
+ "&category_id=1&expire_time=" + expTime.getText().toString() + "&detail_desc=" + productDesc.getText().toString().trim() + "&esti_ordr_qty="
+ estOrderQty.getText().toString().trim() + "&esti_ordr_qty_unit=1&filename=abc.jpg&image=abc.png";
// Creating service handler class instance
postURL = postURL.replace(" ", "%20");
BackendAPIService sh = new BackendAPIService();
System.out.println(":::::::::::::::::::post buying request URL:::::::::::::::::" + postURL);
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(postURL, BackendAPIService.POST);
Log.d("Response: ", "> " + jsonStr);
try {
if (jsonStr != null) {
jsonObj = new JSONObject(jsonStr);
if (jsonObj.get("status").equals("success")) {
flag = 0;
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
} catch (JSONException e) {
e.printStackTrace();
System.out.println("::::::::::::::::::got an error::::::::::::");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Intent i;
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
if (flag == 0) {
Utils.showCustomeAlertValidation(BuyingreqActivity.this, "Request Posted", "Yehki", "OK");
clearViews();
} else {
Toast.makeText(BuyingreqActivity.this, "Buying Request has not been posted", 0).show();
}
/**
* Updating parsed JSON data into ListView
*
* */
}
}
void clearViews() {
productName.setText("");
productDesc.setText("");
estOrderQty.setText("");
expTime.setText("Expiration Time");
proImg.setImageResource(R.drawable.noimage);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_CAPTURE) { // for camera
try {
System.out.println("============= FILENAME :: " + fileName);
if (new File(Const.DIR_USER + "/" + fileName).exists()) {
performCrop();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) { // for crop image
try {
if (data != null) {
Bundle extras = data.getExtras();
Bitmap thePic = extras.getParcelable("data");
Utils.createDirectoryAndSaveFile(thePic, Const.DIR_USER + "/" + fileName);
// pro_pic.setImageBitmap(thePic);
#SuppressWarnings("deprecation")
Drawable dra = (Drawable) new BitmapDrawable(thePic);
proImg.setImageDrawable(dra);
proImg.setScaleType(ScaleType.FIT_XY);
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == PICK_FROM_GALLERY && resultCode == RESULT_OK) {
if (data != null) {
/*
* fileName = Const.DIR_USER + "/" + "user_" +
* Pref.getValue(ProfileActivity.this, Const.PREF_USER_ID, 0) +
* "_" + System.currentTimeMillis() + ".png";
*/
fileName = "user_" + Pref.getValue(BuyingreqActivity.this, Const.PREF_USER_ID, 0) + "_" + System.currentTimeMillis() + ".png";
Bundle extras2 = data.getExtras();
Bitmap photo = extras2.getParcelable("data");
Utils.createDirectoryAndSaveFile(photo, Const.DIR_USER + "/" + fileName);
ImageView picView = (ImageView) findViewById(R.id.iv_img);
picView.setImageBitmap(photo);
}
}
}
private void performCrop() {
try {
System.out.println("============= AFTER FILENAME :: " + fileName);
Intent cropIntent = new Intent("com.android.camera.action.CROP");
imageUri = Uri.fromFile(new File(Const.DIR_USER + "/" + fileName));
cropIntent.setDataAndType(imageUri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 200);// 256
cropIntent.putExtra("outputY", 200);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 2);
}
catch (ActivityNotFoundException anfe) {
String errorMessage = "Whoops - your device doesn't support the crop action!";
Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
toast.show();
}
}
}
adapter.java
package com.epe.yehki.adapter;
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.epe.yehki.ui.BuyingreqActivity;
import com.epe.yehki.ui.BuyingreqActivity.GetQuoteList;
import com.epe.yehki.util.Const;
import com.example.yehki.R;
public class BuyingRequestAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> BuyingRequestArray;
private Context mContext;
public BuyingRequestAdapter(Context paramContext, ArrayList<HashMap<String, String>> productList) {
this.mContext = paramContext;
this.BuyingRequestArray = productList;
}
public int getCount() {
return this.BuyingRequestArray.size();
}
public Object getItem(int paramInt) {
return Integer.valueOf(paramInt);
}
public long getItemId(int paramInt) {
return paramInt;
}
#SuppressWarnings("static-access")
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup) {
LayoutInflater localLayoutInflater = (LayoutInflater) this.mContext.getSystemService("layout_inflater");
Viewholder localViewholder = null;
if (paramView == null) {
paramView = localLayoutInflater.inflate(R.layout.raw_buying_req, paramViewGroup, false);
localViewholder = new Viewholder();
localViewholder.sub = ((TextView) paramView.findViewById(R.id.sub));
localViewholder.expDate = ((TextView) paramView.findViewById(R.id.exp_date));
localViewholder.quote = ((TextView) paramView.findViewById(R.id.quote));
localViewholder.status = ((TextView) paramView.findViewById(R.id.status));
localViewholder.lastUpdate = ((TextView) paramView.findViewById(R.id.last_updated));
paramView.setTag(localViewholder);
} else {
localViewholder = new Viewholder();
localViewholder = (Viewholder) paramView.getTag();
}
System.out.println(":::::::::::::::values:::::::::::::::" + BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.sub.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_PRODUCT_NAME));
localViewholder.expDate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_EXPIRY_DATE));
localViewholder.lastUpdate.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_DATE_MODIFIED));
localViewholder.quote.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_QUOTE_COUNT));
localViewholder.quote.setTextColor(Color.parseColor("#0000ff"));
localViewholder.status.setText(BuyingRequestArray.get(paramInt).get(Const.TAG_BUYING_REQUEST_STATUS));
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*
* HERE I WANT TO CALL "GETqUOTElIST" ASYNCTASK OF MY ACTIVITY/////!!!!!!!
*/
}
});
return paramView;
}
static class Viewholder {
TextView sub;
TextView lastUpdate;
TextView expDate;
TextView quote;
TextView status;
}
}
This might not be the correct approach of coding ,where in you have all the asyncs in one activity.
But to achieve what you want you can use the context that you pass in the adapter like this:
((YourActivityYouArePassing)mContext).someMethod();
the activity's context must be the same as the one you are using for type casting, and someMethod() should be a method declared inside the activity with public keyword.
in someMethod() you could then call your async task like:
public void someMethod() {
new AsyncClass().execute();
}
EDIT:
The onClick will look like this in the adapter
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*
* HERE I WANT TO CALL "GETqUOTElIST" ASYNCTASK OF MY ACTIVITY/////!!!!!!!
*/
((YourActivityYouArePassing)mContext).someMethod();
}
});
Hope that helps!!
You can call async task on text click inside Custom adapter
localViewholder.quote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new GetBuyingReqList.execute();
}
});
and make GetBuyingReqList class private to public
put below code where u want
GetBuyingReqList getBuyingReqList = new GetBuyingReqList ();
getBuyingReqList .execute();
Possible duplicate How to Call AsyncTask from Adapter class?
found these answers
move your adapter class inside your activity class and make adapter class as inner class.so you have access for calling Asynctask in adapter
Remove AsyncTask Inner class from activity class and Make AsyncTask as a separate class (put it in your package). After that you can call like this "new Asynctask().execute();" from any where
what i did... i sent an instance of the activity to the adapter while initializing, then i called a method at the activity by activity.method() and this method calls the AsyncTask

Categories

Resources