I wrote the code below, where the search for latitude and longitude is performed based on the address entered by the enduser.
The class CadastroClientes.java. It is responsible for seeking the user's address (HttpRequestTask method) and set this result to char_Logradouro field (textvfield).
After set the value in the mentioned field, BuscaGeolocalizacao class is called and the getAddressFromLocation method passing as parameter, the address you entered. So far everything was running right.
The problem started when in the BuscaGeolocalizacao class I tried to set the value of the result of latitude and longitude on the fields:
cc.char_Lat.setText(sb.append(address.getLatitude()));
cc.char_Long.setText(sb.append(address.getLongitude()));
CadastroClientes.java (first code called)
package com.clubee.doggywalker;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Handler;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import java.util.ArrayList;
import java.util.List;
public class CadastroClientes extends Activity {
//JSON node
private static final String TAG_SUCCESS = "success";
//url para cadastrar novo usuário
private static String url_cadastraCliente = "http://clubee.com.br/dev/dbDoggyWalker/DoggyWalker_CadastroCliente_Inserir.php";
JSONParser jsonParser = new JSONParser();
EditText char_Nome;
EditText char_CEP;
EditText char_Email;
EditText char_Cidade;
EditText char_Estado;
EditText char_Logradouro;
EditText char_Endereco;
EditText char_Bairro;
TextView char_Lat;
TextView char_Long;
//barra de progressão
private ProgressDialog pDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cadastro_dw);
char_Nome = (EditText) findViewById(R.id.inputNome);
char_Email = (EditText) findViewById(R.id.inputEmail);
char_Logradouro = (EditText) findViewById(R.id.inputLogradouro);
char_Cidade = (EditText) findViewById(R.id.inputCidade);
char_Estado = (EditText) findViewById(R.id.inputEstado);
char_Bairro = (EditText) findViewById(R.id.inputBairro);
char_CEP = (EditText) findViewById(R.id.inputCEP);
char_Lat = (TextView) findViewById(R.id.inputLatitude);
char_Long = (TextView) findViewById(R.id.inputLongitude);
//Criar botão
Button btnCadastraCliente = (Button) findViewById(R.id.btnCadastraCliente);
Button btnBuscaCEP = (Button) findViewById(R.id.btnBuscaEndereco);
//Criar evento do botão
btnCadastraCliente.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View view) {
//abre thread em background
new CadastraCliente().execute();
}
});
//Criar evento do botão
btnBuscaCEP.setOnClickListener(new View.OnClickListener() {#Override
public void onClick(View view) {
//abre thread em background
new HttpRequestTask().execute();
}
});
}
private class HttpRequestTask extends AsyncTask < Void, Void, DAOPostmon > {
String charCepTrim = char_CEP.getText().toString().trim();
final String url = "http://api.postmon.com.br/v1/cep/" + charCepTrim;
RestTemplate restTemplate = new RestTemplate();
#Override
protected DAOPostmon doInBackground(Void...params) {
try {
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
DAOPostmon DAOPostmon = restTemplate.getForObject(url, DAOPostmon.class);
return DAOPostmon;
} catch (Exception e) {
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
DAOPostmon DAOPostmon = restTemplate.getForObject(url, DAOPostmon.class);
return DAOPostmon;
}
}
#Override
protected void onPostExecute(DAOPostmon DAOPostmon) {
//quando a tag Logradouro estiver disponiivel no retorno da api rest
if (DAOPostmon.getLogradouro() == null) {
TextView greetingLogradouro = (TextView) findViewById(R.id.inputLogradouro);
TextView greetingBairro = (TextView) findViewById(R.id.inputBairro);
TextView greetingCidade = (TextView) findViewById(R.id.inputCidade);
TextView greetingEstado = (TextView) findViewById(R.id.inputEstado);
TextView greetingCEP = (TextView) findViewById(R.id.inputCEP);
greetingLogradouro.setText(DAOPostmon.getEndereco().toUpperCase());
greetingCidade.setText(DAOPostmon.getCidade().toUpperCase());
greetingBairro.setText(DAOPostmon.getBairro().toUpperCase());
greetingEstado.setText(DAOPostmon.getEstado().toUpperCase());
greetingCEP.setText(DAOPostmon.getCep());
} else {
//senão, quando não tiver a tag logradouro, usar endereco
TextView greetingLogradouro = (TextView) findViewById(R.id.inputLogradouro);
TextView greetingBairro = (TextView) findViewById(R.id.inputBairro);
TextView greetingCidade = (TextView) findViewById(R.id.inputCidade);
TextView greetingEstado = (TextView) findViewById(R.id.inputEstado);
TextView greetingCEP = (TextView) findViewById(R.id.inputCEP);
greetingLogradouro.setText(DAOPostmon.getLogradouro().toUpperCase());
greetingCidade.setText(DAOPostmon.getCidade().toUpperCase());
greetingBairro.setText(DAOPostmon.getBairro().toUpperCase());
greetingEstado.setText(DAOPostmon.getEstado().toUpperCase());
greetingCEP.setText(DAOPostmon.getCep());
}
String address = char_Logradouro.getText().toString();
BuscaGeolocalizacao locationAddress = new BuscaGeolocalizacao();
locationAddress.getAddressFromLocation(address,
getApplicationContext(), new GeocoderHandler());
}
}
private class GeocoderHandler extends Handler {
public void handlerMsg(Message message) {
String locationAddress;
switch (message.what) {
case 1:
Bundle bundle = message.getData();
locationAddress = bundle.getString("char_Logradouro");
char_Lat.setText(locationAddress);
break;
default:
locationAddress = null;
}
}
}
class CadastraCliente extends AsyncTask < String, String, String > {
/**
* Before starting background thread Show Progress Dialog
*/#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(CadastroClientes.this);
pDialog.setMessage("Cadastrando usuário..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
*/
protected String doInBackground(String...args) {
String Nome = char_Nome.getText().toString();
String Email = char_Email.getText().toString();
String Endereco = char_Endereco.getText().toString();
String TipoLicenca = "DogWalker";
// Building Parameters
List < NameValuePair > params = new ArrayList < NameValuePair > ();
params.add(new BasicNameValuePair("char_Nome", Nome));
params.add(new BasicNameValuePair("char_Email", Email));
params.add(new BasicNameValuePair("char_Endereco", Endereco));
params.add(new BasicNameValuePair("char_TipoLicenca", TipoLicenca));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_cadastraCliente,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), CadastroClientes.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
BuscaGeolocalizacao.java (the class responsible to return lat/long)
package com.clubee.doggywalker;
import android.location.Geocoder;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
public class BuscaGeolocalizacao {
private static final String TAG = "GeocodingLocation";
public static void getAddressFromLocation(final String locationAddress,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
try {
List<Address> addressList = geocoder.getFromLocationName(locationAddress, 1);
if (addressList != null && addressList.size() > 0) {
CadastroClientes cc = new CadastroClientes();
Address address = addressList.get(0);
StringBuilder sb = new StringBuilder();
sb.append(address.getLatitude()).append("\n");
sb.append(address.getLongitude()).append("\n");
result = sb.toString();
cc.char_Lat.setText(sb.append(address.getLatitude()));
cc.char_Long.setText(sb.append(address.getLongitude()));
}
} catch (IOException e) {
Log.e(TAG, "Unable to connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (result != null) {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n\nLatitude and Longitude :\n" + result;
bundle.putString("address", result);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n Unable to get Latitude and Longitude for this address location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
After the attempt to implement sending latitude and longitude for activity, the system started to explode with the following message
07-01 00:44:18.412 8978-9170/com.clubee.doggywalker E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-23081
Process: com.clubee.doggywalker, PID: 8978
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.(Handler.java:200)
at android.os.Handler.(Handler.java:114)
at android.app.Activity.(Activity.java:793)
at com.clubee.doggywalker.CadastroClientes.(CadastroClientes.java:27)
at com.clubee.doggywalker.BuscaGeolocalizacao$1.run(BuscaGeolocalizacao.java:33)
You can post on the UI thread also like
cc.char_Lat.post(new Runnable() {
#Override
public void run() {
cc.char_Lat.setText("what ever value");
}
});
But by the way i think you should use your handler instead of using a reference to CadastroClientes
do your UI operations in a UI Thread. Like this..
runOnUiThread(new Runnable() {
#Override
public void run() {
cc.char_Lat.setText(sb.append(address.getLatitude()));
cc.char_Long.setText(sb.append(address.getLongitude()));
}
});
Android basically works on two thread types namely UI thread and background thread. According to android documentation -
Do not access the Android UI toolkit from outside the UI thread to fix this problem, Android offers several ways to access the UI thread from other threads. Here is a list of methods that can help:
Activity.runOnUiThread(Runnable)
View.post(Runnable)
View.postDelayed(Runnable, long)
new Thread()
{
public void run()
{
myactivity.this.runOnUiThread(new runnable()
{
public void run()
{
cc.char_Lat.setText(sb.append(address.getLatitude()));
cc.char_Long.setText(sb.append(address.getLongitude()));
}
});
}
}.start();
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location != null) {
showAddress(location);
}
final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location loc) {
showAddress(loc);
}
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
private void showAddress(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
Geocoder myLoc = new Geocoder(getApplicationContext(), Locale.getDefault());
List<Address> mlist;
try {
mlist = myLoc.getFromLocation(latitude, longitude, 1);
if(mList.size() == 1) { char_Lat.SetText(mlist.get(0).getLatitude().toString()); char_Long.Settext(mlist.get(0).getLongitude().toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
log.e("IO Exception",e.Message);
}
}
use Location Permission in your Manifest :
android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION
http://developer.android.com/reference/android/Manifest.permission.html
Related
i am working on json parsing where in my TypeMenu java file i am getting response from server and when i click on the item in listview i should get related item in the next activity in listview ..that listview item is also coming from server...here i want to get item only from selected item..but i am getting all item from database in my next activity which is SubMenu.java...like if i select Pizza so in next activity i should get item related with pizza only
Here is my TypeMenu.java file
package com.example.zeba.broccoli;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class TypeMenu extends AppCompatActivity {
private String TAG = TypeMenu.class.getSimpleName();
String bid;
private ProgressDialog pDialog;
private ListView lv;
private static final String TAG_BID = "bid";
// URL to get contacts JSON
private static String url = "http://cloud.granddubai.com/brtemp/index.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// getting values from selected ListItem
HashMap<String, String> selected = contactList.get(position);
String keyId = new ArrayList<>(selected.keySet()).get(0);
String type_items = selected.get(keyId);
Intent in = new Intent(getApplicationContext(), SubMenu.class);
// sending pid to next activity
in.putExtra(TAG_BID ,type_items );
startActivityForResult(in, 100);
Toast.makeText(getApplicationContext(),"Toast" +type_items ,Toast.LENGTH_LONG).show();
}
});
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(TypeMenu.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
// Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonArry = new JSONArray(jsonStr);
for (int i = 0; i < jsonArry.length(); i++)
{
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String type = c.getString("type");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("type", type);
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
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
* */
ListAdapter adapter = new SimpleAdapter(
TypeMenu.this, contactList,
R.layout.list_item, new String[]{ "type","id"},
new int[]{
R.id.type,R.id.id});
lv.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
here is my SubMenu.java file
package com.example.zeba.broccoli;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class SubMenu extends AppCompatActivity {
private String TAG = SubMenu.class.getSimpleName();
String type_items ;
private ProgressDialog pDialog;
private ListView lv;
private static final String TAG_BID = "bid";
// URL to get contacts JSON
private static String url = "http://cloud.granddubai.com/broccoli/menu_typeitem.php";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_type_menu);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Intent i = getIntent();
// getting product id (pid) from intent
type_items = i.getStringExtra(TAG_BID);
Toast.makeText(getApplicationContext(),"Toast 12" + type_items ,Toast.LENGTH_LONG).show();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
contactList = new ArrayList<>();
lv = (ListView) findViewById(R.id.list);
new GetContacts().execute();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pDialog = new ProgressDialog(SubMenu.this);
pDialog.setMessage("Loading book details.");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
// getting values from selected ListItem
HashMap<String, String> selected = contactList.get(position);
String keyId = new ArrayList<>(selected.keySet()).get(0);
String type_items = selected.get(keyId);
//Intent in = new Intent(getApplicationContext(), SubMenu.class);
// sending pid to next activity
// in.putExtra(TAG_BID ,text);
//startActivityForResult(in, 100);
Toast.makeText(getApplicationContext(),"Toast" + type_items,Toast.LENGTH_LONG).show();
}
});
}
/**
* Async task class to get json by making HTTP call
*/
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SubMenu.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
// Toast.makeText(getApplicationContext(),"Toast",Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONArray jsonArry = new JSONArray(jsonStr);
for (int i = 0; i < jsonArry.length(); i++)
{
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contactList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG)
.show();
}
});
}
} else {
Log.e(TAG, "Couldn't get json from server.");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG)
.show();
}
});
}
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
* */
ListAdapter adapter = new SimpleAdapter(
SubMenu.this, contactList,
R.layout.list_item, new String[]{ "name","id"},
new int[]{
R.id.type});
lv.setAdapter(adapter);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
here is my php file..i know it will show all the data ..i tried other code also but not working ..in this atleast all data from table is showing..but i want only selected data
<?php
if($_SERVER['REQUEST_METHOD']=='GET')
{
$id = $_GET['type_items'];
require_once('config.php');
$sql = "SELECT * FROM main_menu_items WHERE type_item='".$id."'";
$r = mysqli_query($con,$sql);
$res = mysqli_fetch_array($r);
$result = array();
array_push($result,array("name"=>$res['name'],)
);
echo json_encode(array("result"=>$result));
mysqli_close($con);
}
replace for loop of GetContacts of SubMenu.java class with below :
for (int i = 0; i < jsonArry.length(); i++) {
JSONObject c = jsonArry.getJSONObject(i);
String id = c.getString("id");
String name = c.getString("name");
String type = c.getString("type");
if (type.equalsIgnoreCase(type_items)) {
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contactList.add(contact);
break;
}
}
In submenu class you need to check if the selected ID matches with the id just save that data in list and break the loop.
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.
I'm developing my android app for a conference. In, my login page I printed an error message when no internet connection. but, the app crashes when no internet connection and following error message display in logcat.
I followed many questions from stack overflow and may be I can't understand, I couldn't find my answer.
08-19 10:01:21.840
8931-9124/com.NICT.nict E/AndroidRuntime﹕ FATAL EXCEPTION: Thread-691
java.lang.RuntimeException: Can't create handler inside thread that hasnot called Looper.prepare()
at android.os.Handler.<init>(Handler.java:205)
at android.os.Handler.<init>(Handler.java:119)
atandroid.widget.Toast$TN.<init>(Toast.java:325)
atandroid.widget.Toast.<init>(Toast.java:91)
atandroid.widget.Toast.makeText(Toast.java:239)
at com.NICT.nict.services.MessageHandler.showMessage(MessageHandler.java:9)
at com.NICT.nict.LoginActivity$1$1.run(LoginActivity.java:117)
at java.lang.Thread.run(Thread.java:838)
Here is my login activity
package com.NICT.nict;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import com.NICT.nict.WorkShopActivity.HttpAsyncTask;
import com.NICT.nict.services.EmailValidator;
import com.NICT.nict.services.MessageHandler;
import com.NICT.nict.services.ServiceHandler;
public class LoginActivity extends Activity {
public final static String URL = "http://demo.et.lk/nitcapi/api/login";
public static String Uid;
private Button loginBtn;
private EditText codeEdit;
private EditText nameEdit;
private EditText emailEdit;
private ServiceHandler sh = new ServiceHandler();
private boolean errorStatus;
private ProgressBar spinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
loginBtn = (Button) findViewById(R.id.loginBtn);
codeEdit = (EditText) findViewById(R.id.codeEdit);
nameEdit = (EditText) findViewById(R.id.nameEdit);
emailEdit = (EditText) findViewById(R.id.emailEdit);
spinner = (ProgressBar) findViewById(R.id.progressBar1);
spinner.setVisibility(View.GONE);
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!ServiceHandler.isOnline(getApplicationContext())) {
MessageHandler.showMessage("You are not online.",
getApplicationContext());
}
new Thread(new Runnable() {
public void run() {
String code = codeEdit.getText().toString();
String email = emailEdit.getText().toString();
String name = nameEdit.getText().toString();
if (code.length() == 0) {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Please Enter the app code",
getApplicationContext());
errorStatus = true;
}
});
;
} else if (name.length() == 0) {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Please Enter Your Name",
getApplicationContext());
errorStatus = true;
}
});
;
} else if (email.length() == 0) {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Please Enter Your Email",
getApplicationContext());
errorStatus = true;
}
});
;
}
EmailValidator emailValidator = new EmailValidator();
if(!emailValidator.validate(email)){
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage(
"Invalid Email",
getApplicationContext());
errorStatus = true;
}
});
;
}
String jsonStr = null;
if (!errorStatus) {
if (!ServiceHandler.isOnline(getApplicationContext())) {
MessageHandler.showMessage("You are not online.",
getApplicationContext());
} else {
ConnectivityManager conMgr = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
// notify user you are online
try{
runOnUiThread(new Runnable() {
public void run() {
spinner.setVisibility(View.VISIBLE);
}
});
;
jsonStr = sh.makeServiceCall(URL + "/" + code + "/"
+ name + "/" + email, ServiceHandler.GET);
System.out.println(URL + "/" + code + "/" + name + "/"
+ email);
}
catch (Exception e){
spinner.setVisibility(View.GONE);
runOnUiThread(new Runnable() {
public void run() {
MessageHandler.showMessage("You are not online.",
getApplicationContext());
}
});
;
}
}
if (jsonStr != null) {
String status = "";
String msg = "";
try {
JSONObject jsonObj = new JSONObject(jsonStr);
runOnUiThread(new Runnable() {
public void run() {
spinner.setVisibility(View.GONE);
}
});
;
if (jsonObj != null
&& jsonObj.has("status")) {
status = jsonObj.getString("status");
msg = jsonObj.getString("message");
if(jsonObj.has("uid"))
Uid = jsonObj.getString("uid");
System.out.println(jsonObj);
if (status.equals("OK")) {
Intent myIntent = new Intent(
getBaseContext(),
MainMenuActivity.class);
startActivityForResult(myIntent, 0);
} else if (status.equals("ERROR")) {
final String errorMsg = msg;
runOnUiThread(new Runnable() {
public void run() {
MessageHandler
.showMessage(
errorMsg,
getApplicationContext());
}
});
;
} else {
runOnUiThread(new Runnable() {
public void run() {
MessageHandler
.showMessage(
"Oops..! something wrong with the service. Please try again Later.",
getApplicationContext());
}
});
;
}
}
} catch (Exception e) {
System.out
.println("Creation of json object failed");
}
}
}
}
}).start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
}
Here is my serviceHandler.
package com.NICT.nict.services;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
*
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
*
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
public static boolean isOnline(Context ctx) {
ConnectivityManager cm;
NetworkInfo info = null;
try {
cm = (ConnectivityManager) ctx
.getSystemService(Context.CONNECTIVITY_SERVICE);
info = cm.getActiveNetworkInfo();
} catch (Exception e) {
e.printStackTrace();
}
return (info!=null&&!info.equals(null));
}
}
add this following snippet in your if condition::
if (!ServiceHandler.isOnline(getApplicationContext())) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(
new Runnable()
{
#Override
public void run()
{
MessageHandler.showMessage("You are not online.",
getApplicationContext());
}
}
);
}
Try this.when you see runtimeException due to Looper not prepared before handler.
Handler handler = new Handler(Looper.getMainLooper());
From Android Docs:
LOOPER
Class used to run a message loop for a thread. Threads by default do
not have a message loop associated with them; to create one, call
prepare() in the thread that is to run the loop, and then loop() to
have it process messages until the loop is stopped.
Looper.getMainLooper()
Returns the application's main looper, which
lives in the main thread of the application.
I hope it helps!
Android basically works on two thread types namely UI thread and background thread.
Try this,
activity.runOnUiThread(new Runnable() {
public void run() {
//run your code here.....
}
});
I am making a weather app and my current issue is that the weather is updating based on the default values for the location rather than waiting for the method getLocation() to update the location. As soon as I refresh, everything works, but this is not what I'd prefer to happen in my app. Here is my MainActivity.java: Please excuse the mess. It's compiled from code snippet after code snippet and needs some re-organising.
package com.nrsmac.stormy.ui;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.nrsmac.stormy.R;
import com.nrsmac.stormy.weather.Current;
import com.nrsmac.stormy.weather.Day;
import com.nrsmac.stormy.weather.Forecast;
import com.nrsmac.stormy.weather.Hour;
import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
public class MainActivity extends ActionBarActivity {
public static final String TAG = MainActivity.class.getSimpleName();
public static final String DAILY_FORECAST = "DAILY_FORECAST";
public static final String HOURLY_FORECAST = "HOURLY_FORECAST";
//9.927128 -84.082012 San José, Costa Rica
private double mLatitude = 0;
private double mLongitude = 0;
public static String cityName = null;
public static int backgroundColor;
private Forecast mForecast;
#InjectView(R.id.relativeLayout)
RelativeLayout mRelativeLayout;
#InjectView(R.id.timeLabel)
TextView mTimeLabel;
#InjectView(R.id.temperatureLabel)
TextView mTemperatureLabel;
#InjectView(R.id.humidityValue)
TextView mHumidityValue;
#InjectView(R.id.precipValue)
TextView mPrecipValue;
#InjectView(R.id.summaryLabel)
TextView mSummaryLabel;
//#InjectView(R.id.iconImageView) ImageView mIconImageView;
#InjectView(R.id.refreshImageView)
ImageView mRefreshImageView;
#InjectView(R.id.progressBar)
ProgressBar mProgressBar;
#InjectView(R.id.locationLabel)
TextView mLocationLabel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
mProgressBar.setVisibility(View.INVISIBLE);
getLocation();
mRefreshImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getForecast(mLatitude, mLongitude);
}
});
getForecast(mLatitude, mLongitude);
Log.d(TAG, "Main UI code is running!");
}
public void getLocation() {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener ll = new LocationListener() {
#Override
public void onLocationChanged(Location location) {
if (location != null){
double pLong = location.getLongitude();
double pLat = location.getLatitude();
mLongitude = pLong;
mLatitude = pLat;
}
String longitude = "Longitude: " + location.getLongitude();
Log.v(TAG, longitude);
String latitude = "Latitude: " + location.getLatitude();
Log.v(TAG, latitude);
/*----------to get City-Name from coordinates ------------- */
Geocoder gcd = new Geocoder(getBaseContext(), Locale.getDefault());
List<Address> addresses;
try {
addresses = gcd.getFromLocation(location.getLatitude(),
location.getLongitude(), 1);
if (addresses.size() > 0)
System.out.println(addresses.get(0).getLocality());
cityName = addresses.get(0).getLocality();
} catch (IOException e) {
e.printStackTrace();
}
mLocationLabel.setText(cityName);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
};
//took this to line 123 out to test for gps always on bug, using only line 124 right now
//exceptions will be thrown if provider is not permitted.
// try{gps_enabled=lm.isProviderEnabled(LocationManager.GPS_PROVIDER);}catch(Exception ex){}
//try{network_enabled=lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);}catch(Exception ex){}
// if(gps_enabled) {
// lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 100, ll);
//if(network_enabled)
// lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 100, ll);
// }
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 100, 100, ll);
// if update broke it, try un-commenting this line, comment out above line?
//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10, 10, ll);
}
private void getForecast(double latitude, double longitude) {
String apiKey = "7a73984cc278e10ed332f1e5d6db96e9";
String forecastUrl = "https://api.forecast.io/forecast/" + apiKey + "/" + latitude + "," + longitude;
if (isNetworkAvailable()) {
toggleRefresh();
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(forecastUrl)
.build();
Call call = client.newCall(request);
call.enqueue(new Callback() {
#Override
public void onFailure(Request request, IOException e) {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
alertUserAboutError();
}
#Override
public void onResponse(Response response) throws IOException {
runOnUiThread(new Runnable() {
#Override
public void run() {
toggleRefresh();
}
});
try {
String jsonData = response.body().string();
Log.v(TAG, jsonData);
if (response.isSuccessful()) {
mForecast = parseForecastDetails(jsonData);
runOnUiThread(new Runnable() {
#Override
public void run() {
updateDisplay();
}
});
} else {
alertUserAboutError();
}
} catch (IOException e) {
Log.e(TAG, "Exception caught", e);
} catch (JSONException e) {
Log.e(TAG, "Exception caught", e);
}
}
});
} else {
Toast.makeText(this, getString(R.string.network_unavailible_message),
Toast.LENGTH_LONG).show();
}
}
private void toggleRefresh() {
getLocation();
if (mProgressBar.getVisibility() == View.INVISIBLE) {
mProgressBar.setVisibility(View.VISIBLE);
mRefreshImageView.setVisibility(View.INVISIBLE);
}
else {
mProgressBar.setVisibility(View.INVISIBLE);
mRefreshImageView.setVisibility(View.VISIBLE);
}
}
private void updateDisplay() {
getLocation();
Current current = mForecast.getCurrent();
mTemperatureLabel.setText(current.getTemperature() + " degrees");
mTimeLabel.setText(current.getFormattedTime());
mHumidityValue.setText(current.getHumidity() + "");
mPrecipValue.setText(current.getPrecipChance() + "%");
mSummaryLabel.setText(current.getSummary());
// Drawable drawable = getResources().getDrawable(current.getIconId());
// mIconImageView.setImageDrawable(drawable);
backgroundColor = current.getBackgroundColor();
mRelativeLayout.setBackgroundColor(backgroundColor);
}
private Forecast parseForecastDetails(String jsonData) throws JSONException {
Forecast forecast = new Forecast();
forecast.setCurrent(getCurrentDetails(jsonData));
forecast.setHourlyForecast(getHourlyForecast(jsonData));
forecast.setDailyForecast(getDailyForecast(jsonData));
return forecast;
}
private Day[] getDailyForecast(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject daily = forecast.getJSONObject("daily");
JSONArray data = daily.getJSONArray("data");
Day[] days = new Day[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonDay = data.getJSONObject(i);
Day day = new Day();
day.setSummary(jsonDay.getString("summary"));
day.setIcon(jsonDay.getString("icon"));
day.setTemperatureMax(jsonDay.getDouble("temperatureMax"));
day.setTime(jsonDay.getLong("time"));
day.setTimezone(timezone);
days[i] = day;
}
return days;
}
private Hour[] getHourlyForecast(String jsonData) throws JSONException{
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
JSONObject hourly = forecast.getJSONObject("hourly");
JSONArray data = hourly.getJSONArray("data");
Hour[] hours = new Hour[data.length()];
for (int i = 0; i < data.length(); i++) {
JSONObject jsonHour = data.getJSONObject(i);
Hour hour = new Hour();
hour.setSummary(jsonHour.getString("summary"));
hour.setTemperature(jsonHour.getDouble("temperature"));
hour.setIcon(jsonHour.getString("icon"));
hour.setTime(jsonHour.getLong("time"));
hour.setTimezone(timezone);
hours[i] = hour;
}
return hours;
}
private Current getCurrentDetails(String jsonData) throws JSONException {
JSONObject forecast = new JSONObject(jsonData);
String timezone = forecast.getString("timezone");
Log.i(TAG, "From JSON: " + timezone);
JSONObject currently = forecast.getJSONObject("currently");
Current current = new Current();
current.setHumidity(currently.getDouble("humidity"));
current.setTime(currently.getLong("time"));
current.setIcon(currently.getString("icon"));
current.setPrecipChance(currently.getDouble("precipProbability"));
current.setSummary(currently.getString("summary"));
current.setTemperature(currently.getDouble("temperature"));
current.setTimeZone(timezone);
Log.d(TAG, current.getFormattedTime());
return current;
}
private boolean isNetworkAvailable() {
ConnectivityManager manager = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = manager.getActiveNetworkInfo();
boolean isAvailible = false;
if (networkInfo != null && networkInfo.isConnected()) {
isAvailible = true;
}
return isAvailible;
}
private void alertUserAboutError() {
AlertDialogFragment dialog = new AlertDialogFragment();
dialog.show(getFragmentManager(), "error_dialog");
}
#OnClick (R.id.dailyButton)
public void startDailyActivity(View view) {
Intent intent = new Intent(this, DailyForecastActivity.class);
intent.putExtra(DAILY_FORECAST, mForecast.getDailyForecast());
startActivity(intent);
}
#OnClick (R.id.hourlyButton)
public void startHourlyActivity(View view) {
Intent intent = new Intent(this, HourlyForecastActivity.class);
intent.putExtra(HOURLY_FORECAST, mForecast.getHourlyForecast());
startActivity(intent);
}
}
I did kind of the same of yours, we are on the same boat:)
Remove getForecast() in onCreate. You need to update your current location by using google new FusedLocationApi,
because this avoiding getLastKnowLocation crash. How to use this please refer to here, and get the code here.
Then, you need to handleNewLocation(update the weather) in onLocationChanged method.
and the sample code:
#Override
public void onLocationChanged(Location location) {
handleNewLocation(location);
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
mLatitude = location.getLatitude();
mLongitude = location.getLongitude();
getForecast(mLatitude, mLongitude);
getCityName();
}
Remember, always check mLongitude != 0 && mLatitude != 0 before updating the weather info.
If you still cannot figure out, please refer to my Github here.
Remove the call to getForecast in onCreate. That will make it not try to immediately get the forecast based on the wrong location. Only call getForecast after onLocationUpdates is called, so you have the right location.
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...