Need help following tutorial on Google Map API for autocompletion - android

I am trying to use auto completion in my app.
After searching for a while i found the following tutorial:
http://www.claytical.com/blog/android-dynamic-autocompletion-using-google-places-api
There is a unresolved variable called s. where the URL is beeing created:
URLEncoder.encode(s.toString(), "UTF-8") +
I can not understand where this variable comes from.
Here is pretty much the whole code from the tutorial adapted a little bit.
public class PlacesListSearchActivity extends Activity {
private static final String TAG = "PlacesListActivity";
public ArrayAdapter<String> adapter;
public AutoCompleteTextView textView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.places_search);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.item_list);
final AutoCompleteTextView textView = (AutoCompleteTextView)
findViewById(R.id.autoCompleteTextView1);
adapter.setNotifyOnChange(true);
textView.setAdapter(adapter);
textView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (count%3 == 1) {
adapter.clear();
GetPlaces task = new GetPlaces();
//now pass the argument in the textview to the task
task.execute(textView.getText().toString());
}
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
}
});
}
class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {
#Override
// three dots is java for an array of strings
protected ArrayList<String> doInBackground(String... args)
{
Log.d("gottaGo", "doInBackground");
ArrayList<String> predictionsArr = new ArrayList<String>();
try
{
//https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Vict&types=geocode&language=fr&sensor=true&key=AddYourOwnKeyHere
URL googlePlaces = new URL(
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" +
URLEncoder.encode(s.toString(), "UTF-8") +
"&types=geocode&language=en&sensor=true&key=" +
getResources().getString(R.string.googleAPIKey));
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
//take Google's legible JSON and turn it into one big string.
while ((line = in.readLine()) != null) {
sb.append(line);
}
//turn that string into a JSON object
JSONObject predictions = new JSONObject(sb.toString());
//now get the JSON array that's inside that object
JSONArray ja = new JSONArray(predictions.getString("predictions"));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
//add each entry to our array
predictionsArr.add(jo.getString("description"));
}
} catch (IOException e)
{
Log.e("YourApp", "GetPlaces : doInBackground", e);
} catch (JSONException e)
{
Log.e("YourApp", "GetPlaces : doInBackground", e);
}
return predictionsArr;
}
//then our post
#Override
protected void onPostExecute(ArrayList<String> result){
Log.d("YourApp", "onPostExecute : " + result.size());
//update the adapter
adapter = new ArrayAdapter<String>(getBaseContext(), R.layout.item_list);
adapter.setNotifyOnChange(true);
//attach the adapter to textview
textView.setAdapter(adapter);
for (String string : result) {
Log.d("YourApp", "onPostExecute : result = " + string);
adapter.add(string);
adapter.notifyDataSetChanged();
}
Log.d("YourApp", "onPostExecute : autoCompleteAdapter" + adapter.getCount());
}
}
}
Ok, I answered my own question. See answer below!

ok, I got it.
The URL above should be calculated this way:
URL googlePlaces = new URL(
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" +
URLEncoder.encode(args[0], "UTF-8") +
"&types=geocode&language=en&sensor=true&key=" +
getResources().getString(R.string.googleAPIKey));

Related

AutoCompleteTextView on click of item not set in AutoCompleteBox

I want to show item in AutoCompleteTextView. Its working fine and all drop down item showing. but according to my need i dont want to set item in AutoComplete box on click of item. How can i achieve this?
public class AutoCompleteViewActvitiy extends Activity {
AutoCompleteTextView autoCompleteTextView;
String[] language;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.support_simple_spinner_dropdown_item);
//after calling this service then you will get resposne ...in post method
new CallServiceForFetchResponseOfCategory().execute();
}
public class CallServiceForFetchResponseOfCategory extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
protected String doInBackground(String... params) {
String stringUrl = params[0];
String result;
String inputLine;
try {
URL myUrl = new URL(stringUrl);
HttpURLConnection connection = (HttpURLConnection)
myUrl.openConnection();
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.connect();
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
result = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
result = null;
}
return result;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
//in response you will get category array ....
//like
then you will set array into this :
language = .......;
then
setResponse();
}
}
private void setResponse() {
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this, android.R.layout.select_dialog_item, language);
//Getting the instance of AutoCompleteTextView
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
autoCompleteTextView.setThreshold(1);//will start working from first character
autoCompleteTextView.setAdapter(adapter);//setting the adapter data into the AutoCompleteTextView
autoCompleteTextView.setTextColor(Color.RED);
autoCompleteTextView.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
// first srevice again and again call for fetching the result and show in autocomplete
if (autoCompleteTextView.getText().toString().trim().length() > 0) {
new CallServiceForFetchResponseOfCategory().execute();
}
}
});
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//according to id i will call this service but issue is that when i click on item it will set default in autocomplete text box and
//again afterTextChanged will call then again CallServiceForFetchResponseOfCategory hit, that is the issue
// i dont want call this time CallServiceForFetchResponseOfCategory service when i click on item...
new FetchingCityDataAsynkTask().execute();
}
});
}
//
public class FetchingCityDataAsynkTask extends AsyncTask<String, Void, String> {
public static final String REQUEST_METHOD = "GET";
public static final int READ_TIMEOUT = 15000;
public static final int CONNECTION_TIMEOUT = 15000;
#Override
protected String doInBackground(String... params) {
String stringUrl = params[0];
String result;
String inputLine;
try {
URL myUrl = new URL(stringUrl);
HttpURLConnection connection = (HttpURLConnection)
myUrl.openConnection();
connection.setRequestMethod(REQUEST_METHOD);
connection.setReadTimeout(READ_TIMEOUT);
connection.setConnectTimeout(CONNECTION_TIMEOUT);
connection.connect();
InputStreamReader streamReader = new
InputStreamReader(connection.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder stringBuilder = new StringBuilder();
while ((inputLine = reader.readLine()) != null) {
stringBuilder.append(inputLine);
}
reader.close();
streamReader.close();
result = stringBuilder.toString();
} catch (IOException e) {
e.printStackTrace();
result = null;
}
return result;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
//setresponse here
}
}
}
Here is what I did in a project of mine. I simply put the text value of the AutoCompleteTextView to ""
articlesAutocomplete.setOnItemClickListener(
(detailedArticleAdapterView, childView, position, id) ->{
DetailedArticle selectedArticle = (DetailedArticle)detailedArticleAdapterView.getItemAtPosition(position);
/*logic with selected article*/
articlesAutocomplete.setText("");
}
);
I hope this is what you wanted to achieve :)
EDIT : I saw in your comments that you use a TextWatcher, why do you use it for? It may change the usefulness of my solution ^^

how to Get selected spinner item's Id from JSON response?

Outline:
I have to get some operators list from server.
Below is my JSON data
{"PrepaidServiceList":[{"operator_id":"2","operator_name":"Reliance GSM"},{"operator_id":"9","operator_name":"TATA CDMA\/Walky"},{"operator_id":"10","operator_name":"Virgin GSM - TATA"},{"operator_id":"17","operator_name":"Docomo Mobile"},{"operator_id":"18","operator_name":"Idea Mobile"},{"operator_id":"35","operator_name":"T24 (DOCOMO)"},{"operator_id":"22","operator_name":"VodaFone Mobile"},{"operator_id":"28","operator_name":"MTS DataCard"},{"operator_id":"29","operator_name":"Reliance CDMA\/NetConnect\/Land Line"},{"operator_id":"30","operator_name":"TATA Photon"},{"operator_id":"32","operator_name":"Idea Netsetter"},{"operator_id":"33","operator_name":"MTS Prepaid"},{"operator_id":"38","operator_name":"Bsnl - Data\/Validity"},{"operator_id":"39","operator_name":"Bsnl Topup"},{"operator_id":"41","operator_name":"Bsnl Data Card"},{"operator_id":"45","operator_name":"Aircel"},{"operator_id":"46","operator_name":"Aircel Pocket Internet"},{"operator_id":"52","operator_name":"Virgin CDMA - TATA"},{"operator_id":"53","operator_name":"Docomo Special"},{"operator_id":"55","operator_name":"Videocon"},{"operator_id":"56","operator_name":"MTNL Mumbai"},{"operator_id":"57","operator_name":"MTNL Mumbai Special"},{"operator_id":"58","operator_name":"Uninor"},{"operator_id":"59","operator_name":"MTNL Delhi"},{"operator_id":"60","operator_name":"MTNL Delhi Special"},{"operator_id":"61","operator_name":"Uninor Special"},{"operator_id":"62","operator_name":"Videocon Special"},{"operator_id":"63","operator_name":"MTNL Delhi"},{"operator_id":"64","operator_name":"MTNL Mumbai"}]}
JSON data has "operator_id" and "operator_name".
I have to get both from url and display only "operator_name" in a spinner.
I Have already implemented the above. Please find the main_activity for reference
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.spinner);
plans = (TextView)findViewById(R.id.browseplans);
plans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent in = new Intent(getApplicationContext(), BrowsePlans.class);
in.putExtra("operator_id", id_click);
startActivity(in);
}
});
SimpleDateFormat sdf = new SimpleDateFormat("ddMMyyyyHHmmss");
sdf.setTimeZone(TimeZone.getTimeZone("GMT+5:30"));
currentDateandTime = sdf.format(new Date());
apikey = API_KEY.toString();
currentDateandTime.toString();
codetohash = currentDateandTime + apikey;
SHA1Hash = computeSha1OfString(codetohash);
uri = new Uri.Builder()
.scheme("http")
.authority("xxx.in")
.path("atm")
.appendQueryParameter("op", "GetPrepaidServiceList")
.appendQueryParameter("responseType", "json")
.appendQueryParameter("time", currentDateandTime)
.appendQueryParameter("clientId", ClientId)
.appendQueryParameter("hash", SHA1Hash)
.build();
stringUri = uri.toString();
new DataFromServer().execute();
} //end onCreate()
private class DataFromServer extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
}
#Override
protected Void doInBackground(String... params) {
try {
url = new URL(stringUri);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
conn.setRequestProperty("Host", "xxx.in");
/* Uri.Builder builder = new Uri.Builder()
.appendQueryParameter("val1", from)
.appendQueryParameter("val2", to);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();*/
conn.connect();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
text = sb.toString();
} catch (Exception ex) {
ex.toString();
} finally {
try {
reader.close();
} catch (Exception ex) {
ex.toString();
}
}
/*//only for json object not array
JSONObject parentObject = new JSONObject(text);
name = parentObject.getString("Hello");*/
try {
JSONObject jsonObj = new JSONObject(text);
// Getting JSON Array node
JSONArray jsonArray = jsonObj.getJSONArray("PrepaidServiceList");
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++) {
c = jsonArray.getJSONObject(i);
id = c.getString("operator_id");
name = c.getString("operator_name");
list.add(name);
}
} catch (Exception e) {
e.toString();
}
return null;
}
#Override
protected void onPostExecute(Void unused) {
ArrayAdapter adapter =
new ArrayAdapter(getApplication(), R.layout.list_item, R.id.text1, list);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
int item = spinner.getSelectedItemPosition();
id_click = spinner.getSelectedItem().toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
Problem:
I am able to get user selected "operator_name" from spinner using "onItemSelectedListener".
But i need the "operator_id" of user selected "operator_name"
I have to pass the exact user selected "operator_id" to another class.
If i directly pass the operator_id, it has only the last id which is not the user selected one.
I am confused and don't know how to implement this.
Any Help would be greatly appreciated.
Thanks.
Try this way it worked for me
class LoadAlbums extends AsyncTask<String, String, ArrayList<HashMap<String,String>>> {
ArrayAdapter<String> adaptercountry ;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected ArrayList<HashMap<String,String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
data = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(COUNTRY_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node your array
country_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < country_list.length(); i++) {
JSONObject c = country_list.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(OP_ID, c.getString(OP_ID));
map.put(OP_NAME,c.getString(OP_NAME));
data.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return data;
}
protected void onPostExecute(ArrayList<HashMap<String,String>> result) {
super.onPostExecute(result);
String[] arrConuntry=new String[data.size()];
for(int index=0;index<data.size();index++){
HashMap<String, String> map=data.get(index);
arrConuntry[index]=map.get(OP_NAME);
}
// pass arrConuntry array to ArrayAdapter<String> constroctor :
adaptercountry = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_spinner_dropdown_item,
arrConuntry);
spcountry.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View w) {
new AlertDialog.Builder(getActivity())
.setTitle("Select")
.setAdapter(adaptercountry, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
spcountry.setText(adaptercountry.getItem(which).toString());
try {
cname=country_list.getJSONObject(which).getString("operator_id");
Log.d("Response: ", "> " + cname);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}).create().show();
}
});
}
In this case you can modify the AsyncTask to return in the doInBackground() method a List<HashMap<Integer, String>>. So you can store both operator_id and operator_name in the list and display each wanted item in the spinner.
Hope it helps!!!
Create a new ArrayList like
operator_List = new ArrayList<String>();
Add value in ArrayList like
opt_code.setName(jsonobject.optString("operator_name"));
opt_code.setId(jsonobject.optString("operator_id"));
list.add(opt_code);
datalist.add(jsonobject.optString("operator_name"));
operator_List .add(jsonobject.getString("operator_id")
and get operator_id
protected void onPostExecute(Void unused) {
ArrayAdapter adapter =
new ArrayAdapter(getApplication(), R.layout.list_item, R.id.text1, list);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view, int position, long id) {
id_click = spinner.getSelectedItemPosition();
String opt_code = operator_List.get(position);
String selectedItem = arg0.getItemAtPosition(position).toString();
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
May be help you
Your can get Whole object of selected Spinner item use below code:
Object item = arg0.getItemAtPosition(position);

Google places autocomplete api is not working

I have tried most probably every tutorial regarding this. But still am not able to get a proper working autocomplete textview. What i want is ,when a user starts typing the textview should suggest proper places with every character being typed.
Here's my code :
public class Directions extends FragmentActivity {
AutoCompleteTextView from,to;
Button direction;
private static final int GPS_ERRORDIALOG_REQUEST = 9001;
GoogleMap mMap;
public ParserTask parserTask;
protected PlacesTask placesTask;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(servicesOk())
{
setContentView(R.layout.activity_directions);
if(initMap())
{
from = (AutoCompleteTextView) findViewById(R.id.atv_from);
//from.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.list_item));
from.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
placesTask = new PlacesTask();
placesTask.execute(s.toString());
}
#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
}
});
from.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
from.showDropDown();
return false;
}
});
to = (AutoCompleteTextView) findViewById(R.id.atv_to);
//to.setAdapter(new PlacesAutoCompleteAdapter(this, R.layout.list_item));
to.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
placesTask = new PlacesTask();
placesTask.execute(s.toString());
}
#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
}
});
to.setOnTouchListener(new OnTouchListener(){
#Override
public boolean onTouch(View arg0, MotionEvent arg1) {
from.showDropDown();
return false;
}
});
direction = (Button) findViewById(R.id.direction);
}
else
{
Toast.makeText(getApplicationContext(), "map not available", Toast.LENGTH_LONG).show();
}
}
else
{
setContentView(R.layout.activity_main);
}
}
/** 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;
}
// Fetches all places from GooglePlaces AutoComplete Web Service
private class PlacesTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... place) {
// For storing data from web service
String data = "";
// Obtain browser key from https://code.google.com/apis/console
String key = "key=Api_key";
String input="";
try {
input = "input=" + URLEncoder.encode(place[0], "utf-8");
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
// 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;
try{
// Fetching the data from we service
data = downloadUrl(url);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Creating ParserTask
parserTask = new ParserTask();
// Starting Parsing the JSON string returned by Web Service
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]);
// Getting the parsed data as a List construct
places = placeJsonParser.parse(jObject);
}catch(Exception e){
Log.d("Exception",e.toString());
}
return places;
}
#Override
protected void onPostExecute(List<HashMap<String, String>> result) {
String[] frm = new String[] { "description"};
int[] t = new int[] { android.R.id.text1 };
// Creating a SimpleAdapter for the AutoCompleteTextView
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), result, android.R.layout.simple_list_item_1, frm, t);
// Setting the adapter
from.setAdapter(adapter);
to.setAdapter(adapter);
}
}
}
You can use a AutoCompletetextView for showing the place names. I did the same below.
class GetPlaces extends AsyncTask<String, Void, ArrayList<String>> {
#Override
// three dots is java for an array of strings
protected ArrayList<String> doInBackground(String... args) {
ArrayList<String> predictionsArr = new ArrayList<String>();
try {
URL googlePlaces = new URL(
// URLEncoder.encode(url,"UTF-8");
"https://maps.googleapis.com/maps/api/place/autocomplete/json?input="
+ URLEncoder.encode(args[0].toString(), "UTF-8")
+ "&types=geocode&language=en&sensor=true&key="+Constant.GOOGLE_API_KEY);
URLConnection tc = googlePlaces.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(
tc.getInputStream()));
String line;
StringBuffer sb = new StringBuffer();
// take Google's legible JSON and turn it into one big string.
while ((line = in.readLine()) != null) {
sb.append(line);
}
// turn that string into a JSON object
JSONObject predictions = new JSONObject(sb.toString());
// now get the JSON array that's inside that object
JSONArray ja = new JSONArray(
predictions.getString("predictions"));
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
// add each entry to our array
predictionsArr.add(jo.getString("description"));
}
} catch (IOException e) {
Log.e("YourApp", "GetPlaces : doInBackground", e);
} catch (JSONException e) {
Log.e("YourApp", "GetPlaces : doInBackground", e);
}
return predictionsArr;
}
#Override
protected void onPostExecute(ArrayList<String> result) {
// update the adapter
adapter = new ArrayAdapter<String>(getActivity(),
android.R.layout.simple_list_item_1);
adapter.setNotifyOnChange(true);
// attach the adapter to auto complete textview
et_destination.setAdapter(adapter);
}
}
I have created a GooglePlaceAutoComplete (source) (Javadoc) widget in the Sprockets library. You can see how I implemented it and/or set up the library in your project and use the widget.
<net.sf.sprockets.widget.GooglePlaceAutoComplete
android:id="#+id/place"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
To get the Place that a user selects, add an OnPlaceClickListener to it.
public void onPlaceClick(AdapterView<?> parent, Prediction place, int position) {
/* do something with the Place */
}

Android populate spinner with string array

Below I have attached my code for trying to add my string array, names, to the spinner as the options. As of now, I am not getting anything populating the array, and I am really not sure what I'm doing wrong. I have looked over other similar questions on this site, as well as using Google, and have come up empty. Can anyone give me some guidance? Thanks
public class RunesActivity extends Activity {
public static String page;
TextView textName;
Spinner spinner;
ArrayAdapter<String> adapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rune_activity);
GetRunes getRunes = new GetRunes();
getRunes.execute();
spinner = (Spinner) findViewById(R.id.rune_selector);
}
public void addListenerOnSpinnerSelection() {
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
((TextView) adapterView.getChildAt(0)).setTextColor(Color.parseColor("#C49246"));
Toast.makeText(adapterView.getContext(),
"Page Selected: " + adapterView.getItemAtPosition(i).toString(),
Toast.LENGTH_SHORT).show();
page = adapterView.getItemAtPosition(i).toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
class GetRunes extends AsyncTask<String, String, JSONObject> {
private String api_key="d96236d2-6ee3-4cfd-afa7-f41bdbc11128";
String region = MainActivity.region.toLowerCase();
String id = StatsActivity.sumID;
String encodedKey = null;
String encodedRegion = null;
String encodedId = null;
String url = null;
// JSON Node Names
String TAG_NAME = "name";
String TAG_CURRENT = "current";
String TAG_SLOTS = "slots";
String TAG_RUNEID = "runeId";
String TAG_RUNESLOTID = "runeSlotId";
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
// Assign views
textName = (TextView) findViewById(R.id.name);
// Encode URL variables
encodedId = URLEncoder.encode(id, "UTF-8");
encodedKey = URLEncoder.encode(api_key, "UTF-8");
encodedRegion = URLEncoder.encode(region, "UTF-8");
url = "http://prod.api.pvp.net/api/lol/" + region + "/v1.4/summoner/" + id + "/runes?api_key=" + api_key;
Log.i("..........", url);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
#Override
protected JSONObject doInBackground(String... arg0) {
JSONParser jParser = new JSONParser();
// Get JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
Log.i("............", "" + json);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
try {
// Get JSON Object
JSONObject runes = json.getJSONObject(encodedId);
// Get JSON Array node
JSONArray rune = runes.getJSONArray("pages");
// Loop through pages, page names stored in string array
String[] name = new String[rune.length()];
String curr;
ArrayList<String> runePageNames = new ArrayList<String>();
for(int i = 0; i < rune.length(); i++) {
JSONObject c = rune.getJSONObject(i);
name[i] = c.getString(TAG_NAME);
curr = c.getString(TAG_CURRENT);
if(curr.equals("true"))
name[i] = name[i] + " [Active]";
runePageNames.add(name[i]);
Log.i(".........", name[i]);
}
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
addListenerOnSpinnerSelection();
// Set TextView
textName.setText(name[0]);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Try this..
before calling addListenerOnSpinnerSelection(); method set adapter for that spinner.
adapter = new ArrayAdapter(RunesActivity.this,
android.R.layout.simple_spinner_dropdown_item,
runePageNames);
spinner.setAdapter(adapter );
addListenerOnSpinnerSelection();

AutoCompleteText View using webservice api Giving me error in Android

I am trying to do the autocompleteTextView. I am trying the Wiki Example. For Wiki it works. But for my own api its not working. I am trying to call by lastname. I tried using the jSonObject. But looks like i am making some mistake. Here is my Code.
public class WikiSuggestActivity extends Activity {
public String data;
public List<String> suggest;
public AutoCompleteTextView autoComplete;
public ArrayAdapter<String> aAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
suggest = new ArrayList<String>();
autoComplete = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
autoComplete.addTextChangedListener(new TextWatcher(){
public void afterTextChanged(Editable editable) {
// TODO Auto-generated method stub
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// TODO Auto-generated method stub
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
String newText = s.toString();
new getJson().execute(newText);
}
});
}
class getJson extends AsyncTask<String,String,String>{
#Override
protected String doInBackground(String... key) {
String newText = key[0];
newText = newText.trim();
newText = newText.replace(" ", "+");
try{
HttpClient hClient = new DefaultHttpClient();
// HttpGet hGet = new HttpGet("http://en.wikipedia.org/w/api.php?action=opensearch&search="+newText+"&limit=8&namespace=0&format=json");
HttpGet hGet = new HttpGet("http://api.xyz.com?response_format=json&version=2.0&name="+newText);
ResponseHandler<String> rHandler = new BasicResponseHandler();
data = hClient.execute(hGet,rHandler);
suggest = new ArrayList<String>();
JSONArray jArray = new JSONArray(data);
JSONObject mJsonObject = new JSONObject();
for(int i=0;i<jArray.getJSONArray(1).length();i++){
String SuggestKey = jArray.getJSONArray(1).getString(i);
// mJsonObject = jArray.getJSONObject(i);
// mJsonObject.getString("lastname");
suggest.add(SuggestKey);
}
}catch(Exception e){
Log.w("Error", e.getMessage());
}
return null;
}
public void onPostExecute(Void result) {
aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
}
}
Here is my JSON and its a valid JSON
{
"body": {
"players": [
{
"firstname": "abc",
"lastname": "def"
},
{
"firstname": "xyz",
"lastname": "abc"
},
]
},
"statusCode": 200
}
Edit:
Parse your json like this
JSONObject obj=new JSONObject(data);
JSONObject obj2=obj.getJSONObject("body");
JSONArray array=obj2.getJSONArray("players");
for(int i=0;i<array.length();i++)
{
JSONObject playerinfo=array.getJSONObject(i);
String lastname=playerinfo.getString("lastname");
suggest.add(lashname);
}
You can Capture the results from the doInBackGround by returning the result and use it in the onPostExecute .
You are trying to update UI from non UI thread, because doInBackground not running in the UI thread.
put thsi code in onPostExecute
aAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.item,suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
You can get the suggest by returning the value in doInBackground
Take your doInBackground of type ArrayList
and return the suggest
you'll the suggest in the onPostExecute as a method parameter, pass it to the adapter

Categories

Resources