AutoCompleteText View using webservice api Giving me error in Android - 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

Related

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 */
}

Getting results from several AsyncTasks

Hi and thanks for your help.
I have a method that calls an AsyncTask to retrieve some data from the net.
The method is called several times in sequence and therefore launches several AsyncTasks.
From each launch of the method I need to get back the correct result from the relative AsyncTask (and not from some other AsyncTask which was called before or after).
Any help very much appreciated.
EDIT EDIT EDIT EDIT
Added rest of code.
Please Note: the whole process runs inside a Service.
public static class UpdateService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int[] appWidgetIds = intent.getIntArrayExtra("widgetsids");
final int N = appWidgetIds.length;
AppWidgetManager manager = AppWidgetManager.getInstance(this);
for (int i = 0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
Log.e("","i="+Integer.toString(i)+ " di "+Integer.toString(N));
RemoteViews view = buildUpdate(getApplicationContext(),
appWidgetIds);
manager.updateAppWidget(appWidgetId, view);
}
return (START_NOT_STICKY);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
private static RemoteViews buildUpdate(Context ctxt, int[] appWidgetIds) {
RemoteViews updateViews = new RemoteViews(ctxt.getPackageName(),
R.layout.widget);
updateViews.setTextViewText(R.id.price1, getPrice(list.get(0)
.getSymbol()));
}
//THIS METHOD IS CALLED SEVERAL TIMES IN SEQUENCE <----
private static String getPrice(String symbol) {
String result="";
UpdateTaskPrice up = new UpdateTaskPrice();
up.execute(symbol, null, null);
//HERE I WANT THE RESULT FROM onPostExecute() <----
return result;
}
//THIS IS THE ASYNCTASK WHICH IS LAUNCHED SEVERAL TIMES
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(String result) {
//HERE I RECEIVE THE RESULT FROM doInBackground <----
//I NEED TO PASS IT BACK TO getPrice() <----
}
#Override
protected String doInBackground(String... symbol) {
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
String srt = "";
String url = context.getString(R.string.urlaternativo).concat(
symbol[0]);
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
srt = client.execute(getMethod, responseHandler);
int inizio = srt.indexOf("<last data=\"");
int fine = srt.indexOf("\"/>", inizio + 12);
result = srt.substring(inizio + 12, fine);
} catch (Throwable t) {
// Log.e("ERROR", "ERROR", t);
}
//HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute() <----
return result;
}
}
AsyncTask is asynchronous and run in a separate thread. So it is not possible to get the result of AsyncTask in very next statement after you execute it.
To get the relative results from AsyncTask, add a member variable "mRequestId" in your UpdateTaskPrice class and before calling UpdateTaskPrice.execute, set unique request ID.
in "onPostExecute" method of your UpdateTaskPrice class, you can return and process result using this Request Id.
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {
protected int mRequestId;
public void setRequestId (int requestId)
{
this.mRequestId = requestId;
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(String result) {
// do whatever with result using mRequestId
}
#Override
protected String doInBackground(String... symbol) {
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
String srt = "";
String url = context.getString(R.string.urlaternativo).concat(
symbol[0]);
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
srt = client.execute(getMethod, responseHandler);
int inizio = srt.indexOf("<last data=\"");
int fine = srt.indexOf("\"/>", inizio + 12);
result = srt.substring(inizio + 12, fine);
} catch (Throwable t) {
// Log.e("ERROR", "ERROR", t);
}
//HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute() <----
return result;
}
}
You can get the data from multiple asynctask, but the place you want the result is not possible
with the asyctask, you need to use more encapsulation to structure this problem.
the problem with your structure is...
private static String getPrice(String symbol) {
String result="";
UpdateTaskPrice up = new UpdateTaskPrice();
up.execute(symbol, null, null);
//HERE I WANT THE RESULT FROM onPostExecute() <----
return result;
}
when you are starting the new thread it will first execute the statement which is return after task.execute(symbol); in your case it is return statement and then it will exucute pre.. doin.. and post...
Hear is the pattern which you can use to retrieve the data from multiple AsycTask
//Calling to the method callAsyncTask;
callAsyncTask(new AsyncResultCallback(){
public void onResult(String result, String symbol){
//TODO dosomthing with the result
}
});
public void callAsyncTask(AsyncResultCallback callback){
new UpdateTaskPrice(callback).execurte(symbol);
}
public interface AsyncResultCallback{
public void onResult(String result, String symbol);
}
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {
AsyncResultCallback callback;
String symbol;
UpdateTaskPrice(AsyncResultCallback callback){
this.callback = callback;
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(String result) {
callback.onResult(result, symbol);
}
#Override
protected String doInBackground(String... symbol) {
this.symbol = symbol;
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
String srt = "";
String url = context.getString(R.string.urlaternativo).concat(symbol[0]);
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
srt = client.execute(getMethod, responseHandler);
int inizio = srt.indexOf("<last data=\"");
int fine = srt.indexOf("\"/>", inizio + 12);
result = srt.substring(inizio + 12, fine);
} catch (Throwable t) {
// Log.e("ERROR", "ERROR", t);
}
//HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute() <----
return result;
}
}
hope that help.
Well, I think you can pass the unique request id in the constructor of the AsyncTask. Then in the postExecute() method, update the UI with the result and the unique request id -
public class UpdateTaskPrice extends AsyncTask<String, Void, String> {
private int mIdentifier;
private Service mService;
public UpdateTaskPrice(Service service, int identifier) {
this.mIdentifier = identifier;
}
#Override
protected void onProgressUpdate(Void... progress) {
}
#Override
protected void onPostExecute(String result) {
((UpdateService) mService).informPrice(mIdentifier, result);
}
#Override
protected String doInBackground(String... symbol) {
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
String srt = "";
String url = context.getString(R.string.urlaternativo).concat(
symbol[0]);
HttpGet getMethod = new HttpGet(url);
try {
ResponseHandler<String> responseHandler = new BasicResponseHandler();
srt = client.execute(getMethod, responseHandler);
int inizio = srt.indexOf("<last data=\"");
int fine = srt.indexOf("\"/>", inizio + 12);
result = srt.substring(inizio + 12, fine);
} catch (Throwable t) {
// Log.e("ERROR", "ERROR", t);
}
//HERE I GET THE RESULT I WANT, AND PASS IT TO onPostExecute() <----
return result;
}
}

Android: Don't show autosuggest list when item is selected

I was doing some stuff using autocomplete textview in my application. I'm getting suggestion when user types anything. But, I have one query, when user types and taps on the suggested list on the autocomplete textview, then more suggestions comes up. I want to limit the search results when user taps on the list and don't want to show more options there. How can I overcome this situation.
This is my full class, which I'm working on:
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");
ResponseHandler<String> rHandler = new BasicResponseHandler();
data = hClient.execute(hGet, rHandler);
suggest = new ArrayList<String>();
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.getJSONArray(1).length(); i++) {
String SuggestKey = jArray.getJSONArray(1).getString(i);
suggest.add(SuggestKey);
}
} catch (Exception e) {
Log.w("Error", e.getMessage());
}
runOnUiThread(new Runnable() {
public void run() {
aAdapter = new ArrayAdapter<String>(
getApplicationContext(), R.layout.item, suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
});
return null;
}
}
}
Any guidance will be appreciated.
public class WikiSuggestActivity extends Activity {
public String data;
public List<String> suggest;
public AutoCompleteTextView autoComplete;
public ArrayAdapter<String> aAdapter;
public TextWatcher mTextWatcher = 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);
}
};
public boolean watch = true;
/** 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( mTextWatcher );
autoComplete.setOnItemClickListener( new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
autoComplete.removeTextChangedListener( mTextWatcher );
aAdapter.clear();
watch = false;
}
});
}
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");
ResponseHandler<String> rHandler = new BasicResponseHandler();
data = hClient.execute(hGet, rHandler);
suggest = new ArrayList<String>();
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.getJSONArray(1).length(); i++) {
String SuggestKey = jArray.getJSONArray(1).getString(i);
suggest.add(SuggestKey);
}
} catch (Exception e) {
Log.w("Error", e.getMessage());
}
if( watch )
runOnUiThread(new Runnable() {
public void run() {
aAdapter = new ArrayAdapter<String>(
getApplicationContext(), R.layout.item, suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
});
return null;
}
}
}

Android: How to add event listener to auto suggest drop down list

I'm trying to trap event listener on the auto-suggest for my application. i'm populating the list using wiki-suggest : http://en.wikipedia.org/w/api.php?action=opensearch&search=%22bike%22&limit=8&namespace=0&format=json.
I'm getting all the things right but now I want to just click on the item of the list and bring the string to the next activity. I have gone through : http://developer.android.com/reference/android/widget/AutoCompleteTextView.html#setOnItemClickListener(android.widget.AdapterView.OnItemClickListener)
But that is not giving me idea that how can I implement that.
I'm pasting my code here for the auto-suggest populating. Please suggest how to overcome this problem.
#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");
ResponseHandler<String> rHandler = new BasicResponseHandler();
data = hClient.execute(hGet, rHandler);
suggest = new ArrayList<String>();
JSONArray jArray = new JSONArray(data);
for (int i = 0; i < jArray.getJSONArray(1).length(); i++) {
String SuggestKey = jArray.getJSONArray(1).getString(i);
suggest.add(SuggestKey);
}
} catch (Exception e) {
Log.w("Error", e.getMessage());
}
runOnUiThread(new Runnable() {
public void run() {
aAdapter = new ArrayAdapter<String>(
getApplicationContext(), R.layout.item, suggest);
autoComplete.setAdapter(aAdapter);
aAdapter.notifyDataSetChanged();
}
});
return null;
}
This is how I get new suggestions from wiki-suggest:
autoComplete = (AutoCompleteTextView) findViewById(R.id.text);
autoComplete.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable editable) {}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
String newText = s.toString();
new getJson().execute(newText);
}
});
Update from comments
Where you initialize autoComplete, probably in onCreate(), add your OnItemClickListener like this:
autoComplete = (AutoCompleteTextView) findViewById(R.id.autoComplete);
autoComplete.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String text = ((TextView) view).getText().toString();
new getJson().execute(text);
}
});
Solved that. Just has to pass the whole string to the URL on ItemClickListener.

Need help following tutorial on Google Map API for autocompletion

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));

Categories

Resources