ProgressDialog Not Dismissing in AsyncTask - android

I have an app that propogates a spinner from a website inside an AsyncTask. Without a ProgressDialog, I am stuck with an empty spinner until it loads. With a ProgressDialog, the network operation never finishes and the ProgressDialog stays up forever. Here is my code:
class TheaterGetter extends AsyncTask<Void, Void, Document> {
private Context context;
private ProgressDialog dialog;
public TheaterGetter(Context context) {
this.context = context;
dialog = new ProgressDialog(context);
}
#Override
protected void onPreExecute() {
dialog.setMessage(((Activity) context).getString(R.string.loading_theaters));
dialog.setCancelable(false);
dialog.show();
}
protected Document doInBackground(Void...voids) {
Document doc = null;
try {
doc = Jsoup.connect("http://landmarkcinemas.com").timeout(10000).get();
} catch (IOException e) {
Log.e("landmark cinemas connection error", e.getMessage());
}
return doc;
}
protected void onPostExecute(Document doc) {
Element allOptions = doc.select("select[id=campaign").first();
Elements options = allOptions.getElementsByTag("option");
options.remove(0);
TreeMap<String, String> theaters = new TreeMap<String, String>();
for (Element option:options) {
theaters.put(option.html(), option.attr("value"));
}
final TreeMapSpinAdapter adapter = new TreeMapSpinAdapter(context, android.R.layout.simple_spinner_item, theaters);
final Spinner spinner = (Spinner) ((Activity) context).findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
MainActivity.setTheater((String) adapter.getItem(pos));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
dialog.dismiss();
}
}

Just rearrange the dismiss dialog line as follows :
protected void onPostExecute(Document doc) {
dialog.dismiss(); // rearranged
Element allOptions = doc.select("select[id=campaign").first();
Elements options = allOptions.getElementsByTag("option");
options.remove(0);
TreeMap<String, String> theaters = new TreeMap<String, String>();
for (Element option:options) {
theaters.put(option.html(), option.attr("value"));
}
final TreeMapSpinAdapter adapter = new TreeMapSpinAdapter(context, android.R.layout.simple_spinner_item, theaters);
final Spinner spinner = (Spinner) ((Activity) context).findViewById(R.id.spinner1);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
MainActivity.setTheater((String) adapter.getItem(pos));
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}

Related

Listview doesn't get refreshed

I have an issue with the ListView that it doesn't refreshed on changing the Spinner value.
What i did,
Step 1:
Created Custom Adapter and passes the the List to initialize my Adpater.
list = handler.getdata(loc);
if (list.size() > 0) {
ordList = new MicListAdapter(InventoryCount.this, list);
lstView.setAdapter(ordList);
}
Step 2:
Created one Spinner with seletion Listener
mspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
spinlocation = mspinner.getItemAtPosition(arg2).toString();
loc = spinlocation;
String item = (String) arg0.getItemAtPosition(arg2);
((TextView) arg0.getChildAt(0)).setTextColor(Color
.parseColor("#000000"));
((TextView) arg0.getChildAt(0)).setTextSize(20);
if (!changeSpinner) {
new InflateList(spinlocation).execute();
} else {
changeSpinner = false;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
new InflateList(spinlocation).execute();
}
});
Step 3:
Once spinner's value changed it will call Asynctask where i'm loading the new list in the Listview but its not reflecting anything in ListView
class InflateList extends AsyncTask<String, String, List<MIC_OrderDetails>> {
ProgressDialog dialog;
Context context;
String spinLoc;
public InflateList(String spinloc) {
dialog = new ProgressDialog(InventoryCount.this);
dialog.setCancelable(false);
this.spinLoc = spinloc;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Please wait while Data is Loading...");
dialog.show();
}
#Override
protected List<MIC_OrderDetails> doInBackground(String... params) {
// TODO Auto-generated method stub
String result = "";
List<MIC_OrderDetails> lst = new ArrayList<MIC_OrderDetails>();
try {
lst = handler.getdata(spinLoc);
result = "success";
MIC_OrderDetails mic_OrderDetails = new MIC_OrderDetails();
mic_OrderDetails.setResult(result);
lst.add(mic_OrderDetails);
}
catch (Exception e) {
result = "error";
MIC_OrderDetails mic_OrderDetails = new MIC_OrderDetails();
mic_OrderDetails.setResult(result);
lst.add(mic_OrderDetails);
dialog.dismiss();
Log.e("Failed", e.getLocalizedMessage());
}
return lst;
}
protected void onPostExecute(List<MIC_OrderDetails> lst) {
dialog.setMessage("Inflating Data...");
if (lst.get(lst.size() - 1).getResult().contains(("success"))) {
list.clear();
ordList.clear();
list.addAll(lst);
// ordList.notifyDataSetInvalidated();
ordList.notifyDataSetChanged();
dialog.dismiss();
/*
* ordList = new MicListAdapter(InventoryCount.this, lst);
* lstView.setAdapter(ordList);
*
* dialog.dismiss();
*/
} else {
dialog.dismiss();
toastText.setText("Problem in loading Items");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 410);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(toastLayout);
toast.show();
}
}
}
Listview doesn't get refreshed
Create a method in MicListAdapter for updating new data in current data-source of Adapter like:
In MicListAdapter class create a method addAll:
public void addAll(List<MIC_OrderDetails> lst){
this.list.clear();
this.list.addAll(lst);
this.notifyDataSetChanged();
}
Where this.list is List object which is used to return count from getCount method.
and call addAll method using ordList from onPostExecute for updating ListView with latest data:
ordList.addAll(lst);

how to search data into json list view?

I am developing an apps. Where i Want to add a search functionality but i failed to do it. I try to search the whole list but my search is work only in one item in the list view.
Here is my MainActivity Code
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
private ProgressBar spinner;
ArrayList<HashMap<String, String>> arraylist;
private long lastPressedTime;
public static String imgURL = "url";
public static String VIDEO_ID = "videoId";
public static String TITLE = "title";
EditText editsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
final boolean b=wifiManager.isWifiEnabled();
ConnectivityManager cManager=(ConnectivityManager)getSystemService(this.CONNECTIVITY_SERVICE);
final NetworkInfo nInfo=cManager.getActiveNetworkInfo();
if(nInfo!=null&& nInfo.isConnected()) {
Toast.makeText(this, "You are Connected to the Internet", Toast.LENGTH_LONG).show();
setContentView(R.layout.listview_main);
spinner = (ProgressBar)findViewById(R.id.progressBar1);
new DownloadJSON().execute();
}
else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Your DATA Connection is Currently Unreachable")
.setMessage("Connect your WiFi or 2G/3G DATA Connection")
.setPositiveButton("WiFi ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
}, 5000);
wifiManager.setWifiEnabled(true);
Toast.makeText(MainActivity.this, "WiFi Enabling in 5sec Please Wait", Toast.LENGTH_LONG).show();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
})
.setNegativeButton("3G/2G ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//use here tablayout to work when 3G/2G connecion is available
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
}, 5000);
Intent myints = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
Toast.makeText(MainActivity.this, "Your DATA Connection is NOW Connected", Toast.LENGTH_LONG).show();
startActivity(myints);
}
})
.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "To use this Application you have to Connected to the Internet", Toast.LENGTH_LONG).show();
finish();
}
})
.setCancelable(false)
.show();
}
}
public class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
spinner.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=bangla+video+song&maxResults=50&key=api_key");
try {
// Locate the array name in JSON
JSONArray jsonarray = jsonobject.getJSONArray("items");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
JSONObject jsonObjId = jsonobject.getJSONObject("id");
map.put("videoId", jsonObjId.getString("videoId"));
JSONObject jsonObjSnippet = jsonobject.getJSONObject("snippet");
map.put("title", jsonObjSnippet.getString("title"));
//map.put("description", jsonObjSnippet.getString("description"));
// map.put("flag", jsonobject.getString("flag"));
JSONObject jsonObjThumbnail = jsonObjSnippet.getJSONObject("thumbnails");
String imgURL = jsonObjThumbnail.getJSONObject("high").getString("url");
map.put("url",imgURL);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
spinner.setVisibility(View.GONE);
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
}
// Dialouge Box
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new android.support.v7.app.AlertDialog.Builder (this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
MainActivity.this.finish();
}
})
.setNeutralButton(R.string.neutral, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Rate This App", Toast.LENGTH_SHORT).show();
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://play.google.com/store/apps/details?id=")));
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
and here is my list view adapter code.
// Declare Variables
MainActivity main;
private PublisherInterstitialAd mPublisherInterstitialAd;
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View view, ViewGroup parent) {
// Declare Variables
TextView country;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
//rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
// population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
// rank.setText(resultp.get(MainActivity.VIDEO_ID));
country.setText(resultp.get(MainActivity.TITLE));
// population.setText(resultp.get(MainActivity.DESCRIPTION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.imgURL), flag);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, PlayerViewDemoActivity.class);
intent.putExtra("videoId", resultp.get(MainActivity.VIDEO_ID));
context.startActivity(intent);
mPublisherInterstitialAd.isLoaded();
mPublisherInterstitialAd.show();
requestNewInterstitial();
}
});
return itemView;
}
private void requestNewInterstitial() {
PublisherAdRequest adRequest = new PublisherAdRequest.Builder()
.addTestDevice("020AC93F90A14C29209AF3CA716FFBD4")
.build();
mPublisherInterstitialAd.loadAd(adRequest);
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
data.add(resultp); // resultp is hashmap
} else {
if (resultp.get(MainActivity.TITLE).toLowerCase(Locale.getDefault())
.contains(charText)) {
data.add(resultp);
}
}
notifyDataSetChanged();
}
}
You should declare one more ArrayList name allData, it always store all objects.
ArrayList<HashMap<String, String>> allOriginalData; // always store all object
ArrayList<HashMap<String, String>> data; // use for store object that display in the ListView
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
allOriginalData = new ArrayList<HashMap<String, String>>(arraylist);
imageLoader = new ImageLoader(context);
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
// search empty -> new data = all original data
data = new ArrayList<HashMap<String, String>>(allData);
} else {
// loop all original data
// check the condition and make the new data for display in ListView
for(int i = 0; i < allOriginalData.size(); i++){
HashMap<String, String> resultA = allOriginalData.get(i);
if (resultA.get(MainActivity.TITLE).toLowerCase(Locale.getDefault())
.contains(charText)) {
data.add(resultA);
}
}
}
notifyDataSetChanged();
}

Android: Refresh Listview Item upon clicking spinner Item

Hello guys I have this problem, I want my app to refresh or update the listview items upon clicking a specific spinner item. here is the screenshot
and I have no idea on what I'm gonna do, and this is my code so far :(
public class ViewGrade extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
private ListView mylistView;
private String subj_code = "";
private String subj_code_lab = "";
private Spinner spinTerm;
private List<GradeList> gradeList = new ArrayList<GradeList>();
private GradeAdapter arrayAdapter;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_grade);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
spinTerm = (Spinner) findViewById(R.id.spinTerm);
String[] Term = new String[]{"Prelim", "Midterm", "Tentative Final"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, Term);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinTerm.setAdapter(adapter);
SharedPreferences preferences = getSharedPreferences("MyApp", MODE_PRIVATE);
subj_code = preferences.getString("code", "UNKNOWN");
subj_code_lab = preferences.getString("code_lab", "UNKNOWN");
mylistView = (ListView) findViewById(R.id.list);
arrayAdapter = new GradeAdapter(this, gradeList);
mylistView.setAdapter(arrayAdapter);
new loadGrades().execute();
}
public class loadGrades extends AsyncTask<Void, Void, Void>{
String term = spinTerm.getSelectedItem().toString();
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ViewGrade.this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
String url = null;
try {
url = "http://192.168.22.3/MobileClassRecord/getGrade.php?subj_code="+ URLEncoder.encode(subj_code, "UTF-8")+"&term="+URLEncoder.encode(term, "UTF-8");
}catch (UnsupportedEncodingException e){
e.printStackTrace();
}
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(url, ServiceHandler.GET);
Log.e("Response; ", "> " + json);
if (json != null){
try {
JSONObject object = new JSONObject(json);
if (object != null){
JSONArray grade_array = object.getJSONArray("grade");
for (int i = 0; i < grade_array.length(); i++){
JSONObject grade = (JSONObject) grade_array.get(i);
GradeList grade_list = new GradeList();
grade_list.setName(grade.getString("stud_name"));
grade_list.setGrade(grade.getString("grade"));
grade_list.setRemark(grade.getString("remark"));
gradeList.add(grade_list);
}
}
arrayAdapter.notifyDataSetChanged();
}catch (JSONException e){
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_view_grade, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Intent intent = new Intent(ViewGrade.this, SpecificClassRecord.class);
startActivity(intent);
return true;
case R.id.action_add_grade:
Intent intent1 = new Intent(ViewGrade.this, Grade.class);
startActivity(intent1);
}
return super.onOptionsItemSelected(item);
}
}
adapter.notifydatasetChanged() or if you know the specific item inserted/removed, just use adapter.notifyitemInserted/Removed etc.
Add this code in your onClickListener for spinner
Override onItemClick() listener method of the spinner,then inside the method you call adapter.notifydatasetChanged() of the listview
spinTerm.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
// change the adapter values if your list is being changedin anyway
arrayAdapter.notifydatasetChanged();
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});

android get rssitem description from listview

In my android app I'm using a ListView populated by RSSItems taken from a webpage url; the listview shows me only title and pubdate of rssitem.
I would realize that when I click on rssitem of the listview, app shows me an alert dialog showing me in message box the descritpion of the rssitem title.
How can I realize it?
Here the code:
public class MainActivity extends ActionBarActivity{
private ListView listview;
URL url = null;
RssFeed feed = null;
AlertDialog.Builder alert;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView);
alert = new AlertDialog.Builder(MainActivity.this);
try {
url = new URL("http://www.unikore.it/index.php/ingegneria-informatica-home?format=feed");
} catch (MalformedURLException e) {
e.printStackTrace();
}
new ReadRssTask().execute(url);
}
private class ReadRssTask extends AsyncTask<URL, Void, RssFeed> {
#Override
protected RssFeed doInBackground(URL... params) {
RssFeed result = null;
URL url = params[0];
if (!TextUtils.isEmpty(url.toString())) {
try {
result = RssReader.read(url);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
#Override
protected void onPostExecute(RssFeed result) {
if (result != null) {
ArrayList<RssItem> rssItems = (ArrayList<RssItem>) result.getRssItems();
ArrayList<String> arrayList = new ArrayList<String>();
for (final RssItem rssItem : rssItems) {
arrayList.add(rssItem.getTitle()+"\n"+rssItem.getPubDate()+"\n");
ArrayAdapter<String> lista = new ArrayAdapter<String>(getBaseContext(),android.R.layout.simple_list_item_1,arrayList);
listview.setAdapter(lista);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
alert.setTitle(listview.getItemAtPosition(position).toString());
alert.setMessage(); //HERE I SHOULD SET THE rssItem.getDescription()
alert.show();
}
});
Log.i("RSS Reader", rssItem.getTitle());
}
}
}
}
}
You need to change here
alert.show();
to
AlertDialog dialog = alert.create(); // You missed this
dialog.show():
Edit:
Remove this from loop and move to onCreate() after your asynctask executed.
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
alert.setTitle(listview.getItemAtPosition(position).toString());
alert.setMessage(rssItems.get(position).getDescription()); //HERE YOU SHOULD SET THE rssItem.getDescription()
alert.show();
}
});
Make this ArrayList<RssItem> rssItems public static and use as
rssItems = (ArrayList<RssItem>) result.getRssItems();

Get the arraylist stored id from the clickable item on the autocompletextview

So my problem is this I need to get the respective "id" field stored in my arrylist that correspond to the selected autocompletextview item and I can't do this. I parse data to a json format and store it in arraylist, and what I want is to click on the dropdown list of the autocompletetextview (already working) item, and get the respective id.
Json Data:
{"estab":[{"id":"00","design":"NULL"},
{"id":"01","design":"Continente de Viana do Castelo"},
{"id":"02","design":"Pingo Doce Viana do Castelo"},
{"id":"03","design":"Pingo Doce - Portuzelo (Viana Castelo)"},
Arraylist get and set:
public class Estbs {
private String id;
private String design;
public String getID() {
return id;
}
public void setID(String id) {
this.id = id;
}
public String getDesign() {
return design;
}
public void setDesign(String design) {
this.design = design;
}
}
main/json function
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> establist;
ArrayList<Estbs> estab;
String x;
private AutoCompleteTextView actv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_linha);
//Download JSON file AsyncTask
new DownloadJSON().execute();
}
//Download JSON file AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// Locate the WorldPopulation Class
estab = new ArrayList<Estbs>();
// Create an array to populate the spinner
establist = new ArrayList<String>();
// JSON file URL address
jsonobject = JSONfunctions
.getJSONfromURL(url_donload_estbs);
try {
// Locate the NodeList name
jsonarray = jsonobject.getJSONArray("estab");
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Estbs estabs = new Estbs();
estabs.setID(jsonobject.optString("id"));
estabs.setDesign(jsonobject.optString("design"));
estab.add(estabs);
// Populate spinner with country names
establist.add(jsonobject.optString("design"));
}
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the spinner in activity_main.xml
actv = (AutoCompleteTextView) findViewById(R.id.autoCompleteTextView1);
// Spinner adapter
actv
.setAdapter(new ArrayAdapter<String>(Newlin_ProductActivity.this,
android.R.layout.simple_list_item_1,
establist));
// Spinner on item click listener
actv
.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,
View arg1, int position, long arg3) {
// TODO Auto-generated method stub
// Locate the textviews in activity_main.xml
TextView txtrank = (TextView) findViewById(R.id.design);
// Set the text followed by the position
txtrank.setText("Rank : "
+ estab.get(position).getID());
x = estab.get(position).getID();
Toast.makeText(getApplicationContext(), x,
Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
Please check bellow code :-
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
String selection = (String) parent.getItemAtPosition(position);
int id;
for (int i = 0; i < establist.size(); i++) {
if(estab.get(i).getDesign().equals(selection))
{
id=estab.get(i).getId();
break;
}
}
}
In short onItemClicklistener() did the job but i would suggest you to have a look at the code below and try following such practise in daily coding.
public class MainActivity extends Activity implements OnItemClickListener {
private ArrayList<String> establist;
private ArrayList<Estbs> estab;
private AutoCompleteTextView autoCompleteTextView;
private TextView txtRank;
private int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.autoComplete);
autoCompleteTextView.setOnItemClickListener(this);
txtRank = (TextView) findViewById(R.id.textView1);
estab = new ArrayList<Estbs>();
establist = new ArrayList<String>();
new DownloadJSON().execute();
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
for (int i = 0; i < 10; i++) {
fillDataInEstabs();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
autoCompleteTextView.setAdapter(new ArrayAdapter<String>(
MainActivity.this, android.R.layout.simple_list_item_1,
establist));
}
}
private void fillDataInEstabs() {
Estbs e = new Estbs();
e.setId(String.valueOf(count));
e.setDesign("Hello " + String.valueOf(count));
estab.add(e);
establist.add(e.getDesign());
count++;
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
String selection = (String) parent.getItemAtPosition(position);
int actualPosition = estab.indexOf(selection);
txtRank.setText("Rank : " + estab.get(actualPosition).getId());
Toast.makeText(getApplicationContext(), estab.get(actualPosition).getId(),
Toast.LENGTH_LONG).show();
}
}

Categories

Resources