AutoCompleteTextView on click of item not set in AutoCompleteBox - android

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 ^^

Related

Get return from AsyncTask

I'm trying to get a return value from the InBackground method in a way that it fetches the first time, returns right but after returns NULL, my logic was as follows: inside the onPostExecute method I call another function to set the value of a variable , however for some reason this variable becomes NULL, after receiving the data correctly. Here is my code:
public class HomeActivity extends Activity {
Button btnEntrada, btnCarregamento, btnDescarregamento;
EditText numberOF;
TextView txt;
private AlertDialog alert;
private Boolean isOnline;
private JSONArray jsonArray;
private String url = "http://192.168.1.5/ws/entradaSetor.php?numberOF=";
private MyTask task = new MyTask();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
btnEntrada = (Button) this.findViewById(R.id.btnEntrada);
btnCarregamento = (Button) this.findViewById(R.id.btnCarregamento);
btnDescarregamento = (Button) this.findViewById(R.id.btnDescarregamento);
numberOF = (EditText) this.findViewById(R.id.numberOFText);
btnEntrada.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (numberOF.getText().toString().compareTo("") == 0) {
alertDialog("la");
} else {
conecta(numberOF.getText().toString());
}
}
});
}
private void alertDialog(String numero){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Atenção");
builder.setMessage(numero);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alert = builder.create();
alert.show();
}
private void func_EntryQuantity(){
AlertDialog.Builder alert = new AlertDialog.Builder(this);
final EditText edittext = new EditText(HomeActivity.this);
alert.setMessage("\nQuantidade Recebida na OF");
alert.setTitle("Digite a quantidade recebida");
alert.setView(edittext);
alert.setPositiveButton("CONFIRMAR ENTRADA", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable YouEditTextValue = edittext.getText();
}
});
alert.setNegativeButton("VOLTAR", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
alert.show();
}
private Boolean verifica(){
if(this.jsonArray.length() == 0){
return false;
}
else{
return true;
}
}
private void conecta(String numberOF){
task.execute(url + numberOF);
}
private void entradaSetor(JSONArray jsonArray){
this.jsonArray = jsonArray;
}
private class MyTask extends AsyncTask<String, Void, JSONArray>
{
#Override
protected JSONArray doInBackground(String... urls)
{
try{
URL url = new URL(urls[0]);
HttpURLConnection myConnection =
(HttpURLConnection) url.openConnection();
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
BufferedReader streamReader = new BufferedReader(new InputStreamReader(responseBody, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONArray jsonArray = new JSONArray(responseStrBuilder.toString());
//myConnection.disconnect();
return jsonArray;
} else {
return null;
}
}catch (Exception e){
return null;
}
}
#Override
protected void onPostExecute(JSONArray jsonArray)
{
// Call activity method with results
entradaSetor(jsonArray);
}
}
}
I believe that a better way to provide result back to the calling code is to use an interface, like for instance:
interface RequestListener {
public onResultSuccess(JSONArray array);
public onResultFail(String error);
}
private class MyTask extends AsyncTask<String, Void, JSONArray>
{
RequestListener listener = null;
MyTask(RequestListener listener) {
this.listener = listener
}
#Override
protected JSONArray doInBackground(String... urls)
{
try{
URL url = new URL(urls[0]);
HttpURLConnection myConnection =
(HttpURLConnection) url.openConnection();
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
BufferedReader streamReader = new BufferedReader(new InputStreamReader(responseBody, "UTF-8"));
StringBuilder responseStrBuilder = new StringBuilder();
String inputStr;
while ((inputStr = streamReader.readLine()) != null)
responseStrBuilder.append(inputStr);
JSONArray jsonArray = new JSONArray(responseStrBuilder.toString());
//myConnection.disconnect();
return jsonArray;
} else {
return null;
}
}catch (Exception e){
return null;
}
}
#Override
protected void onPostExecute(JSONArray jsonArray)
{
if (listener != null) {
if (jsonArray != null) {
listener.onResultSuccess(jsonArray);
} else {
listener.onResultFail(your-message);
}
}
}
}
then of course you have to provide an instance of the RequestListener interface when you instantiate the MyTask object (might be inside the onCreate)

How do i get the right content in Single Item View

After Clicking an Item in my List view, my Single Item View should appear. Unfortunately every time i click on one of the two items just the same content appears. How can i fix the problem and the right content will be shown?
First i get parse data in my Main Activity:
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener {
ArrayList<productforloc> arrayList;
ListView lv;
private String TAG = MainActivity.class.getSimpleName();
private TextView addressField; //Add a new TextView to your activity_main to display the address
private LocationManager locationManager;
private String provider;
int i = 1;
private ProgressDialog pDialog;
String name;
String image;
String street;
String postalcode;
String musicstyle;
String musicsecond;
String entry;
String opening;
String agegroup;
String urlbtn;
String Fsk;
String city;
// URL to get contacts JSON
private static String url = "http://partypeople.bplaced.net/maptest.json";
ArrayList<HashMap<String, String>> contactList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
arrayList = new ArrayList<>();
lv = (ListView) findViewById(R.id.lv);
lv.setOnItemClickListener((AdapterView.OnItemClickListener) this);
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
final Button popbutton = (Button) findViewById(R.id.popbutton);
popbutton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onClick(View v) {
if (i == 1) {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.secondbg));
arrayList.clear();
url = "http://partypeople.bplaced.net/justpop.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i + 1;
}
} else {
if (popbutton.isPressed()) {
popbutton.setBackground(getResources().getDrawable(R.drawable.bg_popbutton));
arrayList.clear();
url = "http://partypeople.bplaced.net/maptest.json";
runOnUiThread(new Runnable() {
#Override
public void run() {
new ReadJSON().execute(url);
}
});
i = i - 1;
}
}
}
});
}
class ReadJSON extends AsyncTask<String,Integer,String>{
#Override
protected String doInBackground(String... params) {
return readURL(params[0]);
}
#Override
protected void onPostExecute(String content) {
if (pDialog.isShowing())
pDialog.dismiss();
try{
JSONObject jo = new JSONObject(content);
JSONArray ja = jo.getJSONArray("contacts");
for(int i=0;i<ja.length();i++){
JSONObject po = ja.getJSONObject(i);
arrayList.add(new productforloc(
image= po.getString("imageurl"),
name = po.getString("name"),
street = po.getString("street"),
postalcode = po.getString("postalcode"),
musicstyle = po.getString("musicstyle"),
musicsecond = po.getString("musicsecond"),
entry = po.getString("entry"),
opening = po.getString("opening"),
agegroup = po.getString("agegroup"),
urlbtn = po.getString("urlbtn"),
Fsk = po.getString("Fsk"),
city = po.getString("city")
));
}
} catch (JSONException e) {
e.printStackTrace();
}
CustomListAdapterforloc adapter = new CustomListAdapterforloc(getApplicationContext(),R.layout.model,arrayList);
lv.setAdapter(adapter);
}
}
private String readURL(String url){
StringBuilder content = new StringBuilder();
try{
URL uri = new URL(url);
URLConnection urlConnection = uri.openConnection();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
String line;
while((line = bufferedReader.readLine()) !=null){
content.append(line+"\n");
}
bufferedReader.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return content.toString();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",name);
intent.putExtra("imageurl",image);
intent.putExtra("street",street);
intent.putExtra("postalcode",postalcode);
intent.putExtra("musicstyle",musicstyle);
intent.putExtra("musicsecond",musicsecond);
intent.putExtra("entry",entry);
intent.putExtra("opening",opening);
intent.putExtra("agegroup",agegroup);
intent.putExtra("urlbtn",urlbtn);
intent.putExtra("Fsk",Fsk);
intent.putExtra("city",city);
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}
/**
* Async task class to get json by making HTTP call
}
*/
}
Then as you can see in the bottom the content will be sent to the detailactivity, but i always get the content from the second item in my json even if i click on the first item.
Change your onItemClick method to get the right object from your list.
Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
productforloc pForloc = arrayList.get(positon);
Intent intent = new Intent();
intent.setClass(this,DetailActivity.class);
intent.putExtra("name",pForloc.getName());
intent.putExtra("imageurl",pForloc.getImage());
intent.putExtra("street",pForloc.getStreet());
intent.putExtra("postalcode",pForloc.getPostalcode());
intent.putExtra("urlbtn",pForloc.getUrlbtn());
intent.putExtra("Fsk",pForloc.getFsk());
intent.putExtra("city",pForloc.getCity());
startActivity(intent);
Toast.makeText(getApplicationContext(),street,Toast.LENGTH_LONG).show();
}

ArrayAdapter is null even after getting a string array as a parameter

I'm working on the Sunshine app in the Developing Android App course by Udacity. Currently stuck in lesson 2. I've listed down the MainActivity.java that contains a listview that is populated by a network call in the AsyncTask as an inner class in the MainActivity.java. But the application crashes, due to a null pointer exception, as the array adapter is null. I've tried debugging, and the weekForecast (i.e., the ArrayList that stores the parsed data, and is a parameter to the creation of the ArrayAdapter) does have valid parsed data. Thanks for the help in advance.
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.listview_forecast);
GettingWeatherFromNetwork gettingWeatherFromNetwork = new GettingWeatherFromNetwork();
gettingWeatherFromNetwork.execute("94043");
listView.setAdapter(arrayAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main,menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
switch(id) {
case R.id.action_settings : return true;
case R.id.action_refresh : GettingWeatherFromNetwork gettingWeatherFromNetwork = new GettingWeatherFromNetwork();
gettingWeatherFromNetwork.execute("94043");
return true;
}
return super.onOptionsItemSelected(item);
}
public class GettingWeatherFromNetwork extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = GettingWeatherFromNetwork.class.getSimpleName();
//Removed API KEY. But it is a part of the main code I'm running.
private final String API_KEY = " ";
#Override
protected String[] doInBackground(String... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int noOfDays = 7;
try {
final String BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String MODE_PARAM = "mode";
final String UNITS_PARAM = "units";
final String COUNT_PARAM = "cnt";
final String KEY_PARAM = "appid";
Uri builtURI = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM,params[0])
.appendQueryParameter(MODE_PARAM,format)
.appendQueryParameter(UNITS_PARAM,units)
.appendQueryParameter(COUNT_PARAM, String.valueOf(noOfDays))
.appendQueryParameter(KEY_PARAM,API_KEY)
.build();
String Url = builtURI.toString();
URL url = new URL(Url);
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
forecastJsonStr = buffer.toString();
} catch (IOException e) {
Log.e(LOG_TAG, String.valueOf(e));
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, String.valueOf(e));
}
}
}
String [] weatherForecast = new String[0];
WeatherParser weatherParser = new WeatherParser();
try {
weatherForecast = weatherParser.getWeatherDataFromJson(forecastJsonStr,7);
} catch (JSONException e) {
e.printStackTrace();
}
return weatherForecast;
}
#Override
protected void onPostExecute(String[] s) {
List<String> weekForecast = new ArrayList<String>(Arrays.asList(s));
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,weekForecast);
}
}
}
Try removing the line
listView.setAdapter(arrayAdapter);
from onCreate method and add it in onPostExecute() method of AsyncTask, after initialising the arrayAdapter.
#Override
protected void onPostExecute(String[] s) {
List<String> weekForecast = new ArrayList<String>(Arrays.asList(s));
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.list_item_forecast,R.id.list_item_forecast_textview,weekForecast);
//set adapter set to listview after initialzing it.
listView.setAdapter(arrayAdapter);
}

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

Listview appends new data instead of showing new data

I am new to android and sorry if somebody like this as stupid question
I have an activity that extends Listactivty. Listview is showing data fine when it is first time loaded. It shows all files and folders from server. But when i click on the listview then onListItemClick event is called and it again gets data from server but it is appending data with previous data. What i want is that ListView shows only the most recent data with no appending of data.
My ListView Activity code:
public class MainActivity extends ListActivity {
private String urlString="http://xxxxxxxxserver PathXXXXX";
private List<String> item = null;
private List<String> path = null;
private String root="http://xxxxxxxxserver PathXXXXX";
private String result;
private TextView myPath;
static private String pos;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View v= findViewById(R.id.rowtext);
myPath = (TextView)findViewById(R.id.path);
Http_connection f=new Http_connection();
f.execute("");
}
class Http_connection extends AsyncTask<String, Void, Void> {
private Exception exception;
protected Void doInBackground(String... urls)
{
try
{
URL url= new URL(urlString);
HttpURLConnection con=(HttpURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.connect();
int statusCode=con.getResponseCode();
if (statusCode==HttpURLConnection.HTTP_OK){
BufferedReader in= new BufferedReader(new InputStreamReader(con.getInputStream()));
String line;
while ((line=in.readLine())!=null)
{
result=result+"\n"+line;
}
in.close();
con.disconnect();
root="AndroidMapper";
runOnUiThread(new Runnable() {
#Override
public void run() {
getDir(urlString);
}
});
}
}
private void getDir(String dirPath)
{
String\[\] r=result.split("/");
myPath.setText("Location: " + urlString);
item = new ArrayList<String>();
path = new ArrayList<String>();
for (int k=0;k<r.length;k++)
{
if (r\[k\].contains("."))
{
item.add(r\[k\]);
}
else
{
item.add(r\[k\]+"/");
}
}
ArrayAdapter<String> fileList =
new ArrayAdapter<String>(MainActivity.this, R.layout.row, item);
setListAdapter(fileList);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
String pos=new String(item.get(position));
if (pos.contains("."))
{
Context context = getApplicationContext();
CharSequence text = "Hello toast!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else
{
urlString=urlString+pos;
Http_connection f=new Http_connection();
f.execute("");
}
You need to re-init your result variable
Because of this line :
result=result+"\n"+line;
This way maybe :
String line;
result = "";
while ((line=in.readLine())!=null)
{
result=result+"\n"+line;
}

Categories

Resources