I am creating an app. my app is crash when i enter any word after provide space in autocompletetextview and then again when i enter any word then its crash. please help me. using following code.........
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,
LocationListener, AdapterView.OnItemClickListener {
private GoogleMap mMap;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker,FindMarker;
LocationRequest mLocationRequest;
AutoCompleteTextView atvPlaces;
DownloadTask placesDownloadTask;
DownloadTask placeDetailsDownloadTask;
ParserTask placesParserTask;
ParserTask placeDetailsParserTask;
LatLng latLng;
final int PLACES = 0;
final int PLACES_DETAILS = 1;
ListView lv;
ImageButton remove;
private boolean exit = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onLocationChanged(mLastLocation);
}
});
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
remove = (ImageButton)findViewById(R.id.place_autocomplete_clear_button);
// Getting a reference to the AutoCompleteTextView
atvPlaces = (AutoCompleteTextView) findViewById(R.id.id_search_EditText);
atvPlaces.setThreshold(1);
// Adding textchange listener
atvPlaces.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Creating a DownloadTask to download Google Places matching "s"
placesDownloadTask = new DownloadTask(PLACES);
// Getting url to the Google Places Autocomplete api
String url = getAutoCompleteUrl(s.toString().trim());
// Start downloading Google Places
// This causes to execute doInBackground() of DownloadTask class
placesDownloadTask.execute(url);
if (!atvPlaces.getText().toString().equals("")){
lv.setVisibility(View.VISIBLE);
remove.setVisibility(View.VISIBLE);
}else {
lv.setVisibility(View.GONE);
remove.setVisibility(View.GONE);
}
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
// Setting an item click listener for the AutoCompleteTextView dropdown list
/* atvPlaces.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int index,
long id) {
ListView lv = (ListView) arg0;
SimpleAdapter adapter = (SimpleAdapter) arg0.getAdapter();
HashMap<String, String> hm = (HashMap<String, String>) adapter.getItem(index);
// Creating a DownloadTask to download Places details of the selected place
placeDetailsDownloadTask = new DownloadTask(PLACES_DETAILS);
// Getting url to the Google Places details api
String url = getPlaceDetailsUrl(hm.get("reference"));
// Start downloading Google Place Details
// This causes to execute doInBackground() of DownloadTask class
placeDetailsDownloadTask.execute(url);
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
}
});*/
lv=(ListView)findViewById(R.id.list);
lv.setOnItemClickListener(this);
setListenerOnWidget();
}
private void setListenerOnWidget() {
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
atvPlaces.setText("");
}
};
remove.setOnClickListener(listener);
}
#Override
public void onBackPressed() {
if(exit){
finish();
}else {
Toast.makeText(this, "Tap Back again to Exit.",
Toast.LENGTH_SHORT).show();
exit = true;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
exit = false;
}
}, 3 * 1000);
}
}
#Override
public void onItemClick (AdapterView < ? > adapterView, View view,int i, long l){
//ListView lv = (ListView) adapterView;
SimpleAdapter adapter = (SimpleAdapter) adapterView.getAdapter();
HashMap<String, String> hm = (HashMap<String, String>) adapter.getItem(i);
// Creating a DownloadTask to download Places details of the selected place
placeDetailsDownloadTask = new DownloadTask(PLACES_DETAILS);
// Getting url to the Google Places details api
String url = getPlaceDetailsUrl(hm.get("reference"));
// Start downloading Google Place Details
// This causes to execute doInBackground() of DownloadTask class
placeDetailsDownloadTask.execute(url);
InputMethodManager inputManager = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
String str = ((TextView) view.findViewById(R.id.place_name)).getText().toString();
Toast.makeText(this,str, Toast.LENGTH_SHORT).show();
atvPlaces.setText(str.replace(' ',','));
lv.setVisibility(view.GONE);
}
private String getPlaceDetailsUrl(String ref) {
// Obtain browser key from https://code.google.com/apis/console
String key = "key=**************************************";
// reference of place
String reference = "reference=" + ref;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = reference + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/details/" + output + "?" + parameters;
return url;
}
private String getAutoCompleteUrl(String place) {
// Obtain browser key from https://code.google.com/apis/console
String key = "key=*********************************";
// place to be be searched
String input = "input=" + place;
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input + "&" + types + "&" + sensor + "&" + key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/" + output + "?" + parameters;
return url;
}
/**
* 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;
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#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_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
mLocationRequest = new LocationRequest();
//mLocationRequest.setInterval(1000);
//mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if(mCurrLocationMarker != null){
mCurrLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOption = new MarkerOptions();
markerOption.position(latLng);
markerOption.title("Current Position");
markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOption);
Toast.makeText(this,"Location changed",Toast.LENGTH_SHORT).show();
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(13).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
if(mGoogleApiClient != null){
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
loadNearByPlaces(location.getLatitude(), location.getLongitude());
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
} else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResult) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
if (grantResult.length > 0
&& grantResult[0] == PackageManager.PERMISSION_GRANTED) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if (mGoogleApiClient == null) {
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
} else {
Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
private void loadNearByPlaces(double latitude, double longitude) {
//YOU Can change this type at your own will, e.g hospital, cafe, restaurant.... and see how it all works
String type = "atm";
StringBuilder googlePlacesUrl =
new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
googlePlacesUrl.append("location=").append(latitude).append(",").append(longitude);
googlePlacesUrl.append("&radius=").append(PROXIMITY_RADIUS);
googlePlacesUrl.append("&types=").append(type);
googlePlacesUrl.append("&sensor=true");
googlePlacesUrl.append("&key=" + GOOGLE_BROWSER_API_KEY);
JsonObjectRequest request = new JsonObjectRequest(googlePlacesUrl.toString(),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject result) {
Log.i(TAG, "onResponse: Result= " + result.toString());
parseLocationResult(result);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "onErrorResponse: Error= " + error);
Log.e(TAG, "onErrorResponse: Error= " + error.getMessage());
}
});
AppController.getInstance().addToRequestQueue(request);
}
private void parseLocationResult(JSONObject result) {
String id, place_id, placeName = null, reference, icon, vicinity = null;
double latitude, longitude;
try {
JSONArray jsonArray = result.getJSONArray("results");
if (result.getString(STATUS).equalsIgnoreCase(OK)) {
//mMap.clear();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject place = jsonArray.getJSONObject(i);
id = place.getString(ATM_ID);
place_id = place.getString(PLACE_ID);
if (!place.isNull(NAME)) {
placeName = place.getString(NAME);
}
if (!place.isNull(VICINITY)) {
vicinity = place.getString(VICINITY);
}
latitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LATITUDE);
longitude = place.getJSONObject(GEOMETRY).getJSONObject(LOCATION)
.getDouble(LONGITUDE);
reference = place.getString(REFERENCE);
icon = place.getString(ICON);
MarkerOptions markerOptions = new MarkerOptions();
LatLng latLng = new LatLng(latitude, longitude);
markerOptions.position(latLng);
markerOptions.title(placeName);
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory .HUE_BLUE));
markerOptions.snippet(vicinity);
mMap.addMarker(markerOptions);
mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {
#Override
public View getInfoWindow(Marker arg0) {
return null;
}
#Override
public View getInfoContents(Marker marker) {
View myContentsView = getLayoutInflater().inflate(R.layout.marker, null);
TextView tvTitle = ((TextView)myContentsView.findViewById(R.id.title));
tvTitle.setText(marker.getTitle());
TextView tvSnippet = ((TextView)myContentsView.findViewById(R.id.snippet));
tvSnippet.setText(marker.getSnippet());
return myContentsView;
}
});
}
Toast.makeText(getBaseContext(), jsonArray.length() + " ATM_FOUND!",
Toast.LENGTH_SHORT).show();
} else if (result.getString(STATUS).equalsIgnoreCase(ZERO_RESULTS)) {
Toast.makeText(getBaseContext(), "No ATM found in 5KM radius!!!",
Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "parseLocationResult: Error=" + e.getMessage());
}
}
private class DownloadTask extends AsyncTask<String, Void, String> {
private int downloadType = 0;
// Constructor
public DownloadTask(int type) {
this.downloadType = type;
}
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
switch (downloadType) {
case PLACES:
// Creating ParserTask for parsing Google Places
placesParserTask = new ParserTask(PLACES);
// Start parsing google places json data
// This causes to execute doInBackground() of ParserTask class
placesParserTask.execute(result);
break;
case PLACES_DETAILS:
// Creating ParserTask for parsing Google Places
placeDetailsParserTask = new ParserTask(PLACES_DETAILS);
// Starting Parsing the JSON string
// This causes to execute doInBackground() of ParserTask class
placeDetailsParserTask.execute(result);
}
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
int parserType = 0;
public ParserTask(int type) {
this.parserType = type;
}
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
JSONObject jObject;
List<HashMap<String, String>> list = null;
try {
jObject = new JSONObject(jsonData[0]);
switch (parserType) {
case PLACES:
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
// Getting the parsed data as a List construct
list = placeJsonParser.parse(jObject);
break;
case PLACES_DETAILS:
PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
// Getting the parsed data as a List construct
list = placeDetailsJsonParser.parse(jObject);
}
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return list;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
switch (parserType) {
case PLACES:
String[] from = new String[]{"description"};
int[] to = new int[]{R.id.place_name};
// Creating a SimpleAdapter for the AutoCompleteTextView
//SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);
// Setting the adapter
//atvPlaces.setAdapter(adapter);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, result,R.layout.row,from,to);
// Adding data into listview
lv.setAdapter(adapter);
break;
case PLACES_DETAILS:
String location = atvPlaces.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
break;
}
}
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
for(int i=0;i<addresses.size();i++){
Address address = (Address)addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker = mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(13).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
loadNearByPlaces(address.getLatitude(), address.getLongitude());
}
}
}
}
my app is crash when i enter any word after provide space in autocompletetextview and then again when i enter any word then its crash....
Your list is initialized to null at
List<HashMap<String, String>> list = null;
And if the parsing fire any exception, the list will be still null since it won't get initialized & setting a null List to an adapter will produce the NullPointerException at getCount(). So just ensure to initialize it.
List<HashMap<String, String>> list = new ArrayList<>();
IMPORTANT
When you use a space & try to call that URL, it will fire a FileNotFoundException if not encoded properly. In your case, URL url = new URL(strUrl); is firing that exception while using space character.
Easiest way is to replace space with %20. In getAutoCompleteUrl() before return, put the following code to replace space with %20.
private String getAutoCompleteUrl(String place) {
-------existing code----
url = url.replaceAll(" ", "%20");
return url;
}
Actually i had faced the same situation. You are adding data to autocomplete textview dynamically , basically just like google for each word you are typing u are getting that data from server , if i am wrong please correct me.
Use this code for populating data into autocomplete textview dynamically from server depending upon your search
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.SyncStateContract.Columns;
import android.support.v4.widget.SimpleCursorAdapter;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.Filter;
import android.widget.FilterQueryProvider;
import android.widget.ListView;
public class TestActivity extends Activity {
public Context mContext;
// views declaration
public AutoCompleteTextView txtAutoComplete;
public ListView lvItems;
// arrayList for Adaptor
ArrayList<String> listItems;
// getting input from AutocompleteTxt
String strItemName;
// making Adaptor for autocompleteTextView
ArrayAdapter<String> adaptorAutoComplete;
private static final int ADDRESS_TRESHOLD = 2;
private Filter filter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// for showing full screen
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_listitem);
mContext = this;
listItems = new ArrayList<String>();
// Declaring and getting all views objects
Button btnShare = (Button) findViewById(R.id.ListItem_btnShare);
Button btnSort = (Button) findViewById(R.id.ListItem_btnSort);
lvItems = (ListView) findViewById(R.id.ListItem_lvItem);
txtAutoComplete = (AutoCompleteTextView) findViewById(R.id.ListItem_autoComplete);
// adding listeners to button
btnShare.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
btnSort.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
String[] from = { "name" };
int[] to = { android.R.id.text1 };
SimpleCursorAdapter a = new SimpleCursorAdapter(this,
android.R.layout.simple_dropdown_item_1line, null, from, to, 0);
a.setStringConversionColumn(1);
FilterQueryProvider provider = new FilterQueryProvider() {
#Override
public Cursor runQuery(CharSequence constraint) {
// run in the background thread
if (constraint == null) {
return null;
}
String[] columnNames = { Columns._ID, "name" };
MatrixCursor c = new MatrixCursor(columnNames);
try {
// total code for implementing my way of auto complte
String SOAP_ACTION = "your action";
String NAMESPACE = "your name space";
String METHOD_NAME = "your method name";
String URL = "your Url";
SoapObject objSoap = null;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
// Use this to add parameters
request.addProperty("KEY", yourkey);
request.addProperty("Key", constraint);
request.addProperty("Key", Id);
// Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.setOutputSoapObject(request);
envelope.dotNet = true;
HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
// this is the actual part that will call the webservice
androidHttpTransport.call(SOAP_ACTION, envelope);
// Get the SoapResult from the envelope body.
objSoap = (SoapObject) envelope.getResponse();
if (objSoap != null) {
String strData = objSoap.toString();
}
if (objSoap != null) {
System.out.println("getPropertyCountinevents//////////"
+ objSoap.getPropertyCount());
for (int i = 0; i < objSoap.getPropertyCount(); i++) {
Object obj = objSoap.getProperty(i);
if (obj instanceof SoapObject) {
SoapObject objNew = (SoapObject) obj;
c.newRow()
.add(i)
.add(objNew.getProperty("Itemname")
.toString());
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return c;
}
};
a.setFilterQueryProvider(provider);
txtAutoComplete.setAdapter(a);
} // on create ends
} // final class ends
replace mine code of getting data from server to yours i.e calling webservices through http calls and it will work like a charm.
Related
I want to show item of list view in autocomplete text view when click on that item in the list view using the following code.
public class MainActivity extends AppCompatActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener, AdapterView.OnItemClickListener {
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
GoogleMap mMap;
SupportMapFragment mFragment;
Marker CurrentMarker,FindMarker;
Location mLastLocation;
CustomAutoCompleteTextView atvPlaces = null;
DownloadTask placesDownloadTask;
DownloadTask placeDetailsDownloadTask;
ParserTask placesParserTask;
ParserTask placeDetailsParserTask;
final int PLACES=0;
final int PLACES_DETAILS=1;
LatLng latLng;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkLocationPermission();
}
mFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mFragment.getMapAsync(this);
// Getting a reference to the AutoCompleteTextView
atvPlaces = (CustomAutoCompleteTextView) findViewById(R.id.atv_places);
atvPlaces.setThreshold(1);
// Adding textchange listener
atvPlaces.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Creating a DownloadTask to download Google Places matching "s"
placesDownloadTask = new DownloadTask(PLACES);
// Getting url to the Google Places Autocomplete api
String url = getAutoCompleteUrl(s.toString());
// Start downloading Google Places
// This causes to execute doInBackground() of DownloadTask class
placesDownloadTask.execute(url);
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
lv = (ListView) findViewById(R.id.list);
lv.setOnItemClickListener(this);
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
public boolean checkLocationPermission() {
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
if(ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)){
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
}else{
return true;
}
}
private String getAutoCompleteUrl(String place){
// Obtain browser key from https://code.google.com/apis/console
String key = "key=AIzaSyC_7RaIknbxXauB6n2xHNTZgRjg0eo5xog";
// place to be be searched
String input = "input="+place;
// place type to be searched
String types = "types=geocode";
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = input+"&"+types+"&"+sensor+"&"+key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/autocomplete/"+output+"?"+parameters;
return url;
}
private String getPlaceDetailsUrl(String ref){
// Obtain browser key from https://code.google.com/apis/console
String key = "key=AIzaSyC_7RaIknbxXauB6n2xHNTZgRjg0eo5xog";
// reference of place
String reference = "reference="+ref;
// Sensor enabled
String sensor = "sensor=false";
// Building the parameters to the web service
String parameters = reference+"&"+sensor+"&"+key;
// Output format
String output = "json";
// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/place/details/"+output+"?"+parameters;
return url;
}
/** 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;
}
#Override
public void onConnected(Bundle bundle) {
mLocationRequest = new LocationRequest();
// mLocationRequest.setInterval(1000);
// mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)==PackageManager.PERMISSION_GRANTED){
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest,this);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onLocationChanged(Location location) {
mLastLocation = location;
if(CurrentMarker != null){
CurrentMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOption = new MarkerOptions();
markerOption.position(latLng);
markerOption.title("Current Position");
markerOption.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
CurrentMarker = mMap.addMarker(markerOption);
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mMap.animateCamera(CameraUpdateFactory.zoomTo(13));
if(mGoogleApiClient != null){
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
==PackageManager.PERMISSION_GRANTED){
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResult){
switch (requestCode){
case MY_PERMISSIONS_REQUEST_LOCATION: {
if(grantResult.length > 0
&& grantResult[0] == PackageManager.PERMISSION_GRANTED){
if(ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
if(mGoogleApiClient == null){
buildGoogleApiClient();
}
mMap.setMyLocationEnabled(true);
}
}else {
Toast.makeText(this, "permisison denied", Toast.LENGTH_LONG).show();
}
return;
}
}
}
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = ((TextView) view.findViewById(R.id.place_name)).getText().toString();
Toast.makeText(this,str, Toast.LENGTH_SHORT).show();
}
private class DownloadTask extends AsyncTask<String, Void, String> {
private int downloadType = 0;
// Constructor
public DownloadTask(int type) {
this.downloadType = type;
}
#Override
protected String doInBackground(String... url) {
// For storing data from web service
String data = "";
try {
// Fetching the data from web service
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
switch (downloadType) {
case PLACES:
// Creating ParserTask for parsing Google Places
placesParserTask = new ParserTask(PLACES);
// Start parsing google places json data
// This causes to execute doInBackground() of ParserTask class
placesParserTask.execute(result);
break;
case PLACES_DETAILS:
// Creating ParserTask for parsing Google Places
placeDetailsParserTask = new ParserTask(PLACES_DETAILS);
// Starting Parsing the JSON string
// This causes to execute doInBackground() of ParserTask class
placeDetailsParserTask.execute(result);
}
}
}
/**
* A class to parse the Google Places in JSON format
*/
private class ParserTask extends AsyncTask<String, Integer, List<HashMap<String, String>>> {
int parserType = 0;
public ParserTask(int type) {
this.parserType = type;
}
#Override
protected List<HashMap<String, String>> doInBackground(String... jsonData) {
JSONObject jObject;
List<HashMap<String, String>> list = null;
try {
jObject = new JSONObject(jsonData[0]);
switch (parserType) {
case PLACES:
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
// Getting the parsed data as a List construct
list = placeJsonParser.parse(jObject);
break;
case PLACES_DETAILS:
PlaceDetailsJSONParser placeDetailsJsonParser = new PlaceDetailsJSONParser();
// Getting the parsed data as a List construct
list = placeDetailsJsonParser.parse(jObject);
}
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return list;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
switch (parserType) {
case PLACES:
String[] from = new String[]{"description"};
int[] to = new int[]{R.id.place_name};
// Creating a SimpleAdapter for the AutoCompleteTextView
//SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, from, to);
// Setting the adapter
// atvPlaces.setAdapter(lv);
// list adapter
ListAdapter adapter = new SimpleAdapter(MainActivity.this, result,R.layout.list_item,from,to);
// Adding data into listview
lv.setAdapter(adapter);
break;
case PLACES_DETAILS:
String location = atvPlaces.getText().toString();
if (location != null && !location.equals("")) {
new GeocoderTask().execute(location);
}
break;
}
}
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>> {
#Override
protected List<Address> doInBackground(String... locationName) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address> addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
}
for(int i=0;i<addresses.size();i++){
Address address = (Address)addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker = mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(13).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
}
}
}
I want to show selected item in autocompleteTextview from listView when click on that item. Please tell me using my source code.
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long id) {
String str = ((TextView) view.findViewById(R.id.place_name)).getText().toString();
Toast.makeText(this,str, Toast.LENGTH_SHORT).show();
atvPlaces.setText(str);
atvPlaces.dismissDropDown();
}
Pls check this code, I modified.
String mSelectedItem;
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int ClikedPosition, long id) {
//Getting clicked item from list view
mSelectedItem=adapter.getItem(ClikedPosition);
//Setting to auto complete text view
mAutoCompleteTextView.setText(mSelectedItem);
}
});
I am trying to create an app. I want to add search by address on google map in fragment Using the following code-
public class Search extends Fragment implements OnItemClickListener{
private final String TAG = this.getClass().getSimpleName();
MainActivity main=null;
PlacesTask placesTask = null ;
DownloadTask downloadTask=null;
LatLng latLng;
GoogleMap mMap;
Marker CurrentMarker,FindMarker;
AutoCompleteTextView autoCompView=null;
Button findbtn = null;
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
//------------ make your specific key ------------
private static final String API_KEY = "**************************************";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.search, container,false);
autoCompView = (AutoCompleteTextView) view.findViewById(R.id.editplace);
autoCompView.setAdapter(new GooglePlacesAutocompleteAdapter(getActivity(), R.layout.list_item));
autoCompView.setOnItemClickListener(this);
findbtn =(Button) view.findViewById(R.id.findbtn);
findbtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String location = autoCompView.getText().toString();
if(location!=null && !location.equals("")){
new GeocoderTask().execute(location);
Log.e(TAG, "login button is clicked");
}
}
});
return view;
}
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{
#Override
protected List<Address> doInBackground(String... locationName) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getActivity());
List<Address> addresses = null;
try {
// Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0],3);
} catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address>addresses) {
if(addresses==null || addresses.size()==0){
Toast.makeText(getActivity(), "No Location found", Toast.LENGTH_SHORT).show();
}
for(int i=0;i<addresses.size();i++){
Address address = (Address)addresses.get(i);
latLng = new LatLng(address.getLatitude(), address.getLongitude());
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Find Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
FindMarker=mMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder().target(latLng).zoom(14).build();
mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
double mLatitude=address.getLatitude();
double mLongitude=address.getLongitude();
StringBuilder sb = new StringBuilder("https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location="+mLatitude+","+mLongitude);
sb.append("&radius=5000");
sb.append("&types=" + "liquor_store");
sb.append("&sensor=true");
sb.append("&key=********************************");
Log.d("Map", "<><>api: " + sb.toString());
//query places with find location
placesTask.execute(sb.toString());
//for direction Route
LatLng origin = CurrentMarker.getPosition();
LatLng dest = FindMarker.getPosition();
String url = getDirectionsUrl(origin, dest);
// Start downloading json data from Google Directions API
downloadTask.execute(url);
Toast.makeText(getActivity(), " Location found", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onResume() {
super.onResume();
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
return true;
}
return false;
}
});
}
#Override
public void onDestroyView() {
super.onDestroyView();
getActivity().getActionBar().setTitle("IQWINER");
}
#Override
public void onItemClick(AdapterView adapterView, View view, int position,
long id) {
// TODO Auto-generated method stub
String str = (String) adapterView.getItemAtPosition(position);
Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
}
public static ArrayList<String> autocomplete(String input) {
ArrayList<String> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?key=" + API_KEY);
sb.append("&input=" + URLEncoder.encode(input, "utf8"));
URL url = new URL(sb.toString());
System.out.println("URL: "+url);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
} catch (MalformedURLException e) {
//Log.e(LOG_TAG, "Error processing Places API URL", e);
return resultList;
} catch (IOException e) {
//Log.e(LOG_TAG, "Error connecting to Places API", e);
return resultList;
} finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList<String>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
} catch (JSONException e) {
//Log.e(LOG_TAG, "Cannot process JSON results", e);
}
return resultList;
}
class GooglePlacesAutocompleteAdapter extends ArrayAdapter<String> implements Filterable {
private ArrayList<String> resultList;
public GooglePlacesAutocompleteAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
}
#Override
public int getCount() {
return resultList.size();
}
#Override
public String getItem(int index) {
return resultList.get(index);
}
#Override
public Filter getFilter() {
Filter filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if (constraint != null) {
// Retrieve the autocomplete results.
resultList = autocomplete(constraint.toString());
// Assign the data to the FilterResults
filterResults.values = resultList;
filterResults.count = resultList.size();
}
return filterResults;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results != null && results.count > 0) {
notifyDataSetChanged();
} else {
notifyDataSetInvalidated();
}
}
};
return filter;
}
}
}
[enter error description here][2]
how to implement search by address location on Google Map in fragment.Please tell me..
enter error description here
You can do it in another way.
You can generate an api key along with Google maps & Google places api in your developers console (Click on the circled link and Enable the api)
You can call the api like below with your AutoCompleteView onclick listener or any other listener of your wish
private int PLACE_AUTOCOMPLETE_REQUEST_CODE = 1;// declare this globally
//Call this on your listener method
Intent intent = new PlaceAutocomplete.IntentBuilder(PlaceAutocomplete.MODE_OVERLAY)
.build(getActivity());
startActivityForResult(intent, PLACE_AUTOCOMPLETE_REQUEST_CODE);
This will open the Google place search screen and you can get the result like below
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == PLACE_AUTOCOMPLETE_REQUEST_CODE) {
if (resultCode == getActivity().RESULT_OK) {
Place place = PlaceAutocomplete.getPlace(getActivity(), data);
mSearchPlace = place;
mSearchText.setText(String.valueOf(place.getName()));
// You will get Lat,Long values here where you can use it to move your map or reverse geo code it.
LatLng latLng = new LatLng(place.getLatLng().latitude, place.getLatLng().longitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 12));
} else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {
Status status = PlaceAutocomplete.getStatus(getActivity(), data);
} else if (resultCode == getActivity().RESULT_CANCELED) {
// The user canceled the operation.
}
}
}
Hope this helps.
EDIT: Found the solution to my problem.
The json string output returned the wrong url for my local images.
i am barely new to android and struggle with asyncTask.
What i want is to get the corresponding image to a marker on a map.
every entry on this map has its own image which has to be loaded from server via json.
the image load works fine but i dont get the right workflow to get the image i need for one entry.
by now i have one solution to load an async task in a for-loop, but this cant be the right way because the app refuses to go on after 43 tasks and stops with
"ECONNECTION TIMEOUT"
so how can get the asynctask out of the loop?
hope anyone can help? thank you!
here is my code:
public class MapsActivity extends AppCompatActivity implements OnMapReadyCallback {
private GoogleMap mMap;
JSONArray contentJson;
String contentId;
String imageJsonUrl;
String userId;
Bitmap bmp;
LatLng latLng;
Marker m;
HashMap<Marker, String> hashMap;
int k = 0;
// check value for Request check
final int MY_LOCATION_REQUEST_CODE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if(this.getIntent().getExtras() != null) {
try {
contentJson = new JSONArray(this.getIntent().getStringExtra("contentJson"));
// Log.v("TESTITEST", contentJson.toString());
} catch (JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_maps, menu);
return true;
}
public LatLng getLatLngPosition() {
return new LatLng(0, 0);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Ask for Permission. If granted show my Location
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_LOCATION_REQUEST_CODE);
} else {
// permission has been granted, continue as usual
mMap.setMyLocationEnabled(true);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
LatLng selectedLocation = place.getLatLng();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(selectedLocation, 10f));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("PlaceSelectorError", "An error occurred: " + status);
}
});
LatLng bonn = new LatLng(50.7323, 7.1847);
LatLng cologne = new LatLng(50.9333333, 6.95);
//mMap.addMarker(new MarkerOptions().position(bonn).title("Marker in Bonn"));
// hash map for saving content id with marker
hashMap = new HashMap<Marker, String>();
if(contentJson != null) {
if (this.getIntent().getStringExtra("contentId") == null) {
// show all contents of my friends
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
// Log.v("contentslength", String.valueOf(contents.length()));
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
//Log.v("eachcontent", eachcontent.toString());
JSONObject location = eachcontent.getJSONObject("Location");
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
Log.v("contentTitle", contentTitle);
//Log.v("m", m.toString());
//m = mMap.addMarker(new MarkerOptions().title(contentTitle).position(new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")))).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
}
}
} catch (JSONException e) {
Log.e("Exception", "unexpected JSON exception", e);
e.printStackTrace();
}
}
else {
// if we only want to see a specific content
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
JSONObject location = eachcontent.getJSONObject("Location");
if(eachcontent.getString("id").equals(this.getIntent().getStringExtra("contentId"))) {
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
// Log.v("LATLNG", contentId);
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
continue;
}
}
}
} catch (JSONException e) {
Log.e("LOGEDILOG", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 10f));
mMap.setOnMyLocationChangeListener(null);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = hashMap.get(marker);
Log.v("BITMAP", bmp.toString());
try {
Context context = getApplicationContext();
Intent mapIntent = new Intent(getApplicationContext(), contentDetailActivity.class);
mapIntent.putExtra("contentId", id);
mapIntent.putExtra("contentJson", contentJson.toString());
mapIntent.putExtra("userId", userId);
String filename = "profileImage.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
mapIntent.putExtra("image", filename);
startActivity(mapIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Marker[] addMarkers() {
return null;
}
/**
* lets you load Image from external source via url
*/
public class MapImageLoadTask extends AsyncTask<Void, Void, Bitmap> {
private final String LOG_TAG = MapImageLoadTask.class.getSimpleName();
String url, userId, contentId, title;
LatLng location;
BufferedReader reader = null;
public MapImageLoadTask(String url, String userId, String contentId, String title, LatLng location) {
this.url = url;
this.userId = userId;
this.contentId = contentId;
this.title = title;
this.location = location;
}
private String getImageUrlFromJson(String imageJson) throws JSONException {
JSONObject imageJsonOutput = new JSONObject(imageJson);
imageJsonUrl = imageJsonOutput.getString("imageUrl");
//Log.v(LOG_TAG, imageJsonUrl);
return imageJsonUrl;
}
#Override
protected Bitmap doInBackground(Void... params) {
String imageJson = null;
try {
URL urlConnection = new URL(url + userId);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (input == null) {
// Nothing to do.
//forecastJsonStr = null;
return null;
}
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
imageJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
String jsonUrl = getImageUrlFromJson(imageJson);
URL url = new URL(jsonUrl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
return bmp;
}
catch(Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
k +=1;
Log.v("COUNTER", String.valueOf(k));
m = mMap.addMarker(new MarkerOptions().title(title).position(location).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
hashMap.put(m, contentId);
}
}
}
Your problem maybe AsyncTask limitations. In android.os.AsyncTask.java you will see core size and blockingqueue size(128), should use counter for asynctask and debug it(Problem is, lots of async tasks or other).
AsyncTask.java
public abstract class AsyncTask<Params, Progress, Result> {
private static final String LOG_TAG = "AsyncTask";
private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();
private static final int CORE_POOL_SIZE = CPU_COUNT + 1;
private static final int MAXIMUM_POOL_SIZE = CPU_COUNT * 2 + 1;
private static final int KEEP_ALIVE = 1;
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "AsyncTask #" + mCount.getAndIncrement());
}
};
private static final BlockingQueue<Runnable> sPoolWorkQueue =
new LinkedBlockingQueue<Runnable>(128);
...}
Change Your Code Use Buffer(RequestData) And Use Only One Async Task. Update Market instance every publishProgress in onProgressUpdate
private GoogleMap mMap;
JSONArray contentJson;
String contentId;
String imageJsonUrl;
String userId;
Bitmap bmp;
LatLng latLng;
Marker m;
HashMap<Marker, String> hashMap;
int k = 0;
// check value for Request check
final int MY_LOCATION_REQUEST_CODE = 3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
if(this.getIntent().getExtras() != null) {
try {
contentJson = new JSONArray(this.getIntent().getStringExtra("contentJson"));
// Log.v("TESTITEST", contentJson.toString());
} catch (JSONException e) {
Log.e("EXCEPTION", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_maps, menu);
return true;
}
public LatLng getLatLngPosition() {
return new LatLng(0, 0);
}
/**
* Manipulates the map once available.
* This callback is triggered when the map is ready to be used.
* This is where we can add markers or lines, add listeners or move the camera. In this case,
* we just add a marker near Sydney, Australia.
* If Google Play services is not installed on the device, the user will be prompted to install
* it inside the SupportMapFragment. This method will only be triggered once the user has
* installed Google Play services and returned to the app.
*/
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
//Ask for Permission. If granted show my Location
if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Check Permissions Now
ActivityCompat.requestPermissions(MapsActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_LOCATION_REQUEST_CODE);
} else {
// permission has been granted, continue as usual
mMap.setMyLocationEnabled(true);
}
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
LatLng selectedLocation = place.getLatLng();
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(selectedLocation, 10f));
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.i("PlaceSelectorError", "An error occurred: " + status);
}
});
LatLng bonn = new LatLng(50.7323, 7.1847);
LatLng cologne = new LatLng(50.9333333, 6.95);
//mMap.addMarker(new MarkerOptions().position(bonn).title("Marker in Bonn"));
// hash map for saving content id with marker
hashMap = new HashMap<Marker, String>();
if(contentJson != null) {
if (this.getIntent().getStringExtra("contentId") == null) {
// show all contents of my friends
try {
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
// Log.v("contentslength", String.valueOf(contents.length()));
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
//Log.v("eachcontent", eachcontent.toString());
JSONObject location = eachcontent.getJSONObject("Location");
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
Log.v("contentTitle", contentTitle);
//Log.v("m", m.toString());
//m = mMap.addMarker(new MarkerOptions().title(contentTitle).position(new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")))).icon(BitmapDescriptorFactory.fromBitmap(bmp)));
}
}
} catch (JSONException e) {
Log.e("Exception", "unexpected JSON exception", e);
e.printStackTrace();
}
}
else {
// if we only want to see a specific content
try {
List<RequestData> datas = new ArrayList<RequestData>();
for (int i = 0; i < contentJson.length(); i++) {
JSONObject jsonInfo = contentJson.getJSONObject(i);
JSONArray contents = jsonInfo.getJSONArray("content");
//get all contents of one user
for (int j = 0; j < contents.length(); j++) {
JSONObject eachcontent = contents.getJSONObject(j);
JSONObject location = eachcontent.getJSONObject("Location");
if(eachcontent.getString("id").equals(this.getIntent().getStringExtra("contentId"))) {
String contentId = eachcontent.getString("id");
String contentTitle = eachcontent.getString("title");
userId = eachcontent.getString("user_id");
latLng = new LatLng(Double.valueOf(location.getString("latitude")), Double.valueOf(location.getString("longitude")));
// Log.v("LATLNG", contentId);
RequestData data = new RequestData();
data.url = "http://192.168.63.35:1234/rest_app_users/getImage/";
data.userId = userId;
data.contentId = contentId;
data.contentTitle = contentTitle;
data.latlng = latlng;
datas.add(data);
//new MapImageLoadTask("http://192.168.63.35:1234/rest_app_users/getImage/", userId, contentId, contentTitle, latLng).execute();
continue;
}
}
}
new MapImageLoadTask(datas).execute();
} catch (JSONException e) {
Log.e("LOGEDILOG", "unexpected JSON exception", e);
e.printStackTrace();
}
}
}
mMap.setOnMyLocationChangeListener(new GoogleMap.OnMyLocationChangeListener() {
#Override
public void onMyLocationChange(Location location) {
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 10f));
mMap.setOnMyLocationChangeListener(null);
}
});
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
#Override
public void onInfoWindowClick(Marker marker) {
String id = hashMap.get(marker);
Log.v("BITMAP", bmp.toString());
try {
Context context = getApplicationContext();
Intent mapIntent = new Intent(getApplicationContext(), contentDetailActivity.class);
mapIntent.putExtra("contentId", id);
mapIntent.putExtra("contentJson", contentJson.toString());
mapIntent.putExtra("userId", userId);
String filename = "profileImage.png";
FileOutputStream stream = context.openFileOutput(filename, Context.MODE_PRIVATE);
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
//Cleanup
stream.close();
mapIntent.putExtra("image", filename);
startActivity(mapIntent);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Marker[] addMarkers() {
return null;
}
/**
* lets you load Image from external source via url
*/
static class RequestData{
public String url;
public String userId;
public String contentId;
public String contentTitle;
public LatLng latLng;
public Bitmap bmp;
}
public class MapImageLoadTask extends AsyncTask<Void, RequestData, Void> {
private final String LOG_TAG = MapImageLoadTask.class.getSimpleName();
BufferedReader reader = null;
List<RequestData> dataSet;
public MapImageLoadTask(List<RequestData> dataSet) {
this.dataSet = dataSet;
}
private String getImageUrlFromJson(String imageJson) throws JSONException {
JSONObject imageJsonOutput = new JSONObject(imageJson);
imageJsonUrl = imageJsonOutput.getString("imageUrl");
//Log.v(LOG_TAG, imageJsonUrl);
return imageJsonUrl;
}
#Override
protected Bitmap doInBackground(Void... params) {
for(RequestData item : dataSet){
String imageJson = null;
try {
URL urlConnection = new URL(url + userId);
HttpURLConnection connection = (HttpURLConnection) urlConnection
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (input == null) {
// Nothing to do.
//forecastJsonStr = null;
return null;
}
reader = new BufferedReader(new InputStreamReader(input));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
imageJson = buffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
try {
String jsonUrl = getImageUrlFromJson(imageJson);
URL url = new URL(jsonUrl);
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
//
item.bmp = bmp;
publishProgress(item);
}
catch(Exception e) {
e.printStackTrace();
}
}
return null;
}
protected void onPublishProgress(RequestData item){
k +=1;
Log.v("COUNTER", String.valueOf(k));
m = mMap.addMarker(new MarkerOptions().title(item.title).position(item.location).icon(BitmapDescriptorFactory.fromBitmap(item.bmp)));
hashMap.put(m, contentId);
}
#Override
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
}
}
}
I am currently developing an app in android studio.The goal of my app is to have one page(MainActivity.java & activityMain.xml) display a spinner. The items in this spinner are items from a remote database. When the user selects an item in this spinner I want that selected item to be displayed in a separate page(Map.java map.xml).
I used a putExtra method in MainActivity to store the selected item into a string variable:
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, Map.class);
String text = spinnerFood.getSelectedItem().toString();
intent.putExtra("SPINNER_KEY", text);
startActivity(intent);
}
Then in my Map class I am calling that string using getExtras:
String spinnerString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
spinnerString= null;
} else {
spinnerString= extras.getString("STRING_I_NEED");
}
} else {
spinnerString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
I can pass this string from MainActivity to Map successfully. My problem is when I try to display this string is does not appear on the XML page or on my phone when I run the app. I used the following code to try and display the string:
TextView e = (TextView)findViewById(R.id.textView);
e.setText(spinnerString);
Could someone please tell me where I am going wrong?
Here is my MainActivity class:
package com.example.cillin.infoandroidhivespinnermysql;
import java.util.ArrayList;
...
public class MainActivity extends Activity implements OnItemSelectedListener {
private Button btnAddNewCategory;
private TextView txtCategory;
public Spinner spinnerFood;
//public String spinnerValue;
// array list for spinner adapter
private ArrayList<Category> categoriesList;
ProgressDialog pDialog;
// API urls
// Url to create new category
private String URL_NEW_CATEGORY = "http://food_api/new_category.php";
// Url to get all categories
private String URL_CATEGORIES = "http://food_api/get_categories.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAddNewCategory = (Button) findViewById(R.id.btnAddNewCategory);
spinnerFood = (Spinner) findViewById(R.id.spinFood);
txtCategory = (TextView) findViewById(R.id.txtCategory);
categoriesList = new ArrayList<Category>();
// spinner item select listener
spinnerFood.setOnItemSelectedListener(this);
// Add new category click event
btnAddNewCategory.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (txtCategory.getText().toString().trim().length() > 0) {
// new category name
String newCategory = txtCategory.getText().toString();
// Call Async task to create new category
new AddNewCategory().execute(newCategory);
} else {
Toast.makeText(getApplicationContext(),
"Please enter category name", Toast.LENGTH_SHORT)
.show();
}
}
});
new GetCategories().execute();
}
/**
* Adding spinner data
* */
public void populateSpinner() {
List<String> lables = new ArrayList<String>();
txtCategory.setText("");
for (int i = 0; i < categoriesList.size(); i++) {
lables.add(categoriesList.get(i).getName());
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, lables);
// Drop down layout style - list view with radio button
spinnerAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
spinnerFood.setAdapter(spinnerAdapter);
//String text = spinnerFood.getSelectedItem().toString();
}
/**
* Async task to get all food categories
* */
private class GetCategories extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Fetching food categories..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(URL_CATEGORIES, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray categories = jsonObj
.getJSONArray("categories");
for (int i = 0; i < categories.length(); i++) {
JSONObject catObj = (JSONObject) categories.get(i);
Category cat = new Category(catObj.getInt("id"),
catObj.getString("name"));
categoriesList.add(cat);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
populateSpinner();
}
}
/**
* Async task to create a new food category
* */
private class AddNewCategory extends AsyncTask<String, Void, Void> {
boolean isNewCategoryCreated = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating new category..");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(String... arg) {
String newCategory = arg[0];
// Preparing post params
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", newCategory));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(URL_NEW_CATEGORY,
ServiceHandler.POST, params);
Log.d("Create Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
boolean error = jsonObj.getBoolean("error");
// checking for error node in json
if (!error) {
// new category created successfully
isNewCategoryCreated = true;
} else {
Log.e("Create Category Error: ", "> " + jsonObj.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if (isNewCategoryCreated) {
runOnUiThread(new Runnable() {
#Override
public void run() {
// fetching all categories
new GetCategories().execute();
}
});
}
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(
getApplicationContext(),
parent.getItemAtPosition(position).toString() + " Selected" ,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(MainActivity.this, Map.class);
String text = spinnerFood.getSelectedItem().toString();
intent.putExtra("SPINNER_KEY", text);
startActivity(intent);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
Here is Map.java:
package com.example.cillin.infoandroidhivespinnermysql;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
/**
* Created by cillin on 06/07/2015.
*/
public class Map extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//This page layout is located in the menu XML file
//SetContentView links a Java file, to its XML file for the layout
setContentView(R.layout.map);
/*Spinner mySpinner = (Spinner)findViewById(R.id.spinFood);
String text = mySpinner.getSelectedItem().toString();
EditText e = (EditText) findViewById (R.id.editText1);
e.setText(text);*/
String spinnerString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
spinnerString= null;
} else {
spinnerString= extras.getString("STRING_I_NEED");
}
} else {
spinnerString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
/*if (getIntent() != null && getIntent().getExtras() != null) {
Bundle bundle = getIntent().getExtras();
if (bundle.getString("SPINNER_KEY") != null) {
spinnerString = bundle.getString("SPINNER_KEY");
}
}*/
//String a = "ddd";
TextView e = (TextView)findViewById(R.id.textView);
e.setText(spinnerString);
Button mainm = (Button)findViewById(R.id.mainmenu);
mainm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//This button is linked to the map page
Intent i = new Intent(Map.this, MainMenu.class);
//Activating the intent
startActivity(i);
}
});
}
}
Here is my map.xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="300dp"
android:layout_height="300dp"
android:id="#+id/imageView"
android:adjustViewBounds="true"
android:scaleType="fitCenter"
android:src="#drawable/map_image"
android:contentDescription="#string/map"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="46dp" />
<Button
android:id="#+id/mainmenu"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="140dp"
android:layout_marginTop = "450dp"
android:text="Main Menu" />
<TextView
android:layout_width="200dp"
android:layout_height="20dp"
android:id="#+id/textView"
android:layout_below="#+id/imageView"
android:layout_alignRight="#+id/imageView"
android:layout_alignEnd="#+id/imageView" />
</RelativeLayout>
you have to use getIntent().getStringExtra("STRING_I_NEED");
getIntent.getExtras() will work only if you pass Bundle in calling activity
I fixed it:
String spinnerString;
if (savedInstanceState == null) {
Bundle extras = getIntent().getExtras();
if(extras == null) {
spinnerString= null;
} else {
spinnerString= extras.getString("STRING_I_NEED");
}
} else {
spinnerString= (String) savedInstanceState.getSerializable("STRING_I_NEED");
}
I changed "STRING_I_NEED" to "SPINNER_KEY"
google map is loading on emulator givin error that application is stopped unfortunately following is my code package com.ayesha.MIT;
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.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class Spot_Location_Screen extends FragmentActivity implements
LocationListener {
Database_Table_Operations database;
ArrayList<String> locations = new ArrayList<String>();
ArrayList<String> latitude = new ArrayList<String>();
ArrayList<String> longitude = new ArrayList<String>();
GoogleMap mGoogleMap;
Spinner mSprPlaceType;
Intent intent;
String[] mPlaceType = null;
String[] mPlaceTypeName = null;
double mLatitude = 0;
double mLongitude = 0;
Button btnFind;
Button doneButton;
boolean isFound = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.spot_location_screen);
mPlaceType = getResources().getStringArray(R.array.place_type);
mPlaceTypeName = getResources().getStringArray(R.array.place_type_name);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, mPlaceTypeName);
mSprPlaceType = (Spinner) findViewById(R.id.spr_place_type);
mSprPlaceType.setAdapter(adapter);
btnFind = (Button) findViewById(R.id.btn_find);
doneButton = (Button) findViewById(R.id.doneButton);
SupportMapFragment fragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mGoogleMap = fragment.getMap();
mGoogleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String provider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(provider);
locationManager.requestLocationUpdates(provider, 20000, 0, this);
database = new Database_Table_Operations(getApplicationContext());
if (getIntent().getStringExtra("Update") != null) {
if (getIntent().getStringExtra("Update").equals("true")) {
addMarker(getIntent().getStringExtra("Date"));
}
}
int status = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(getBaseContext());
if (status != ConnectionResult.SUCCESS) {
int requestCode = 10;
Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
requestCode);
dialog.show();
} else {
if (location != null) {
onLocationChanged(location);
}
btnFind.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (checkInternetConnection(getApplicationContext())) { // browser
// key
mGoogleMap.clear();
locations.clear();
latitude.clear();
longitude.clear();
int selectedPosition = mSprPlaceType
.getSelectedItemPosition();
String type = mPlaceType[selectedPosition];
StringBuilder sb = new StringBuilder(
"https://maps.googleapis.com/maps/api/place/nearbysearch/json?");
sb.append("location=" + 33.6000 + "," + 73.0333);
sb.append("&radius=20000");
sb.append("&types=" + type);
sb.append("&sensor=true");
sb.append("&key=AIzaSyAVhTyd9GXAkJ9VJ1S7OD9ldrBsQgOH69c");
PlacesTask placesTask = new PlacesTask();
placesTask.execute(sb.toString());
}
}
});
doneButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (checkInternetConnection(getApplicationContext())) {
if (getIntent().getStringExtra("Update").equals("true")) {
database.open();
String myDate = getIntent().getStringExtra("Date");
locations.add(database.getLocation(myDate));
latitude.add(database.getLatitude(myDate));
longitude.add(database.getLongitude(myDate));
intent = new Intent(Spot_Location_Screen.this,
Locations_List_View_Screen.class);
intent.putStringArrayListExtra("Locations",
locations);
intent.putStringArrayListExtra("Latitude", latitude);
intent.putStringArrayListExtra("Longitude",
longitude);
intent.putExtra("Date",
getIntent().getStringExtra("Date"));
intent.putExtra("Update", getIntent()
.getStringExtra("Update"));
database.close();
startActivity(intent);
finish();
} else {
if (locations.size() != 0) {
intent = new Intent(Spot_Location_Screen.this,
Locations_List_View_Screen.class);
intent.putStringArrayListExtra("Locations",
locations);
intent.putStringArrayListExtra("Latitude",
latitude);
intent.putStringArrayListExtra("Longitude",
longitude);
intent.putExtra("Date", getIntent()
.getStringExtra("Date"));
intent.putExtra("Update", getIntent()
.getStringExtra("Update"));
startActivity(intent);
finish();
}
}
}
}
});
}
}
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try {
URL url = new URL(strUrl);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.connect();
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;
}
/** A class, to download Google Places */
private class PlacesTask 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;
}
#Override
protected void onPostExecute(String result) {
ParserTask parserTask = new ParserTask();
parserTask.execute(result);
}
}
/** A class to parse the Google Places in JSON format */
private class ParserTask extends
AsyncTask<String, Integer, List<HashMap<String, String>>> {
JSONObject jObject;
#Override
protected List<HashMap<String, String>> doInBackground(
String... jsonData) {
List<HashMap<String, String>> places = null;
PlaceJSONParser placeJsonParser = new PlaceJSONParser();
try {
jObject = new JSONObject(jsonData[0]);
places = placeJsonParser.parse(jObject);
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return places;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> list) {
mGoogleMap.clear();
for (int i = 0; i < list.size(); i++) {
MarkerOptions markerOptions = new MarkerOptions();
HashMap<String, String> hmPlace = list.get(i);
double lat = Double.parseDouble(hmPlace.get("lat"));
latitude.add(String.valueOf(lat));
double lng = Double.parseDouble(hmPlace.get("lng"));
longitude.add(String.valueOf(lng));
String name = hmPlace.get("place_name");
String vicinity = hmPlace.get("vicinity");
locations.add(name + ", " + vicinity);
LatLng latLng = new LatLng(lat, lng);
markerOptions.position(latLng);
markerOptions.title(name + " : " + vicinity);
mGoogleMap.addMarker(markerOptions);
}
if (locations.size() > 1) {
int median = locations.size();
median = median / 2;
LatLng myLatLng = new LatLng(Double.parseDouble(latitude
.get(median)),
Double.parseDouble(longitude.get(median)));
mGoogleMap.animateCamera(CameraUpdateFactory
.newLatLng(myLatLng));
} else if (locations.size() == 1) {
LatLng myLatLng = new LatLng(
Double.parseDouble(latitude.get(0)),
Double.parseDouble(longitude.get(0)));
mGoogleMap.animateCamera(CameraUpdateFactory
.newLatLng(myLatLng));
}
}
}
#Override
public void onLocationChanged(Location location) {
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
LatLng latLng = new LatLng(mLatitude, mLongitude);
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomTo(12));
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
intent = new Intent(Spot_Location_Screen.this,
SetMeetup_Screen.class);
startActivity(intent);
finish();
}
return super.onKeyDown(keyCode, event);
}
public void addMarker(String date) {
database.open();
MarkerOptions markerOptions = new MarkerOptions();
final LatLng latLng = new LatLng(Double.parseDouble(database
.getLatitude(date)), Double.parseDouble(database
.getLongitude(date)));
markerOptions.position(latLng);
markerOptions.title("Your saved location:\n"
+ database.getLocation(date));
mGoogleMap.addMarker(markerOptions);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
database.close();
}
}, 2500);
}
public boolean checkInternetConnection(Context context) {
ConnectivityManager conMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
if (conMgr.getActiveNetworkInfo() != null
&& conMgr.getActiveNetworkInfo().isAvailable()
&& conMgr.getActiveNetworkInfo().isConnected()) {
isFound = true;
} else {
isFound = false;
}
return isFound;
}
}
Google Android Map API is not able to run Google Maps on the Android emulator. You must use an Real Android device for testing your app.
Refer this link to run Google Map on emulator.
hey ma problem is solved but the emulator is not working with Google maps I think its about the device problem but before it was also not working with the blue stacks for that I've changed the package name
right click the package from
src folder->refactor->rename
and
change the package name then change the package name in the manifest then click the on the project
ctrl+shiftz+o
it will change the package name throughout your project..
then again create the browser key and android key with new package name and it will load the map.....
and don forget to turn on the API's in Google console... and also check the minimum SDK version if its 9 then go to SSDK manager and install API 9 by clicking the obsolete option there...