Trouble clearing spinner data android - android

I have a problem with my spinners in my android app. I have two spinners implemented. Both loads contents from json. The first one look as,
// Code for First spinner
loc = json.getJSONArray("location");
for(int i = 0; i < loc.length(); i++){
JSONObject c = loc.getJSONObject(i);
//put json obkject on variable
String l = c.getString("stock_location");
locationList.add(l);
// Set Spinner Adapter
location.setAdapter(new ArrayAdapter<String>OfferedDiesel.this,android.R.layout.simple_spinner_dropdown_item,locationList));
// Spinner on item click listener
location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,View arg1, int position, long arg3) {
place = locationList.get(position);
selected = place;
new LoadProduct().execute();
product_title.setVisibility(View.VISIBLE);
product.setVisibility(View.VISIBLE);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
place = null;
}
});
}
//Following is the LoadProduct
private class LoadProduct extends AsyncTask<String, String, JSONObject> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(OfferedDiesel.this);
pDialog.setMessage("Loading Product ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.getProductFromLocation(selected);
return json;
}
protected void onPostExecute(JSONObject json) {
if(pDialog.isShowing()){
pDialog.dismiss();
}
// Locate the spinner in activity_main.xml
/*LOcate site node*/
try{
if(json.has("error_msg")){
String err = json.getString("error_msg");
alert.showAlertDialog(OfferedDiesel.this, "ALert !!", err, null);
}else{
prod = json.getJSONArray("product");
for(int i = 0; i < prod.length(); i++){
JSONObject d = prod.getJSONObject(i);
//put json obkject on variable
String k = d.getString("stock_name");
productList.add(k);
arrayAdapter = new ArrayAdapter<String>(OfferedDiesel.this,android.R.layout.simple_spinner_dropdown_item,productList);
// Set Spinner Adapter
product.setAdapter(arrayAdapter);
// Spinner on item click listener
product.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0,View arg1, int position, long arg3) {
good = locationList.get(position);
//selected = place;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
place = null;
}
});
}
}
}catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}/*End of Spinner Populate*/
Here, whenever I am selecting a new item in above spinner it will execute new LoadProduct().execute(); and on my second spinner I am getting the data but the date are appended. I mean for example if by defalt '1' on my first spiner then at second spinner I will get "First" and when I select '2' (change on first spinner) then I will get "Second" it is appended on 'First' and Hence I get 2 items "First" and "Second" instead of just one i.e'Second'. I now need to clear all the spinner list before loading the new. For both spinners I am using json to load data.
Thanks in advance.

I'm going to take a few guesses here about what you are trying to do, because I'm not 100% sure I understood... Here's what I think you are trying to do:
There are two ListViews.
When you click on the first one, it sets up text in the second one to load.
It does so via an AsyncTask called LoadProduct.
selected is used in the LoadProduct to determine what to load.
You aren't getting quite the results you expect.
Okay, so if I'm right here, I would suggest a few changes.
Pass in the selected value to the AsyncTask.
Clear the previous adapter from it's values.
Add the new values.
The AsyncTask should be able to take the input, no problem.

You just need to clear array list using clear method before adding new data to array,this would defiantly help you

Related

AsyncTask filling a ListView in a Dialog launched from a button click doesn't work right

I've spent all day trying to figure this out, and it's drinving me nuts, hoping the experts around here can help me figure this out so I stop pulling my hair out. I'm trying to fill a ListView in a Dialog window that pops up when a button is clicked. If I put the asynctask code to start when the activity starts, everything works fine, but if I try to move the code into either where the button OnClickListener, it starts double filling the listview.
Here's the code:
In my OnCreate:
new LoadAllProducts().execute();
Which runs the following code:
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting All products from url
* */
#Override
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_get_classes, "GET",
params);
// Check your log cat for JSON response
Log.d("All Classes: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// classes found
// Getting Array of Classes
classes = json.getJSONArray(TAG_CLASSES);
// looping through All Classes
for (int i = 0; i < classes.length(); i++) {
JSONObject c = classes.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_CLASSID);
String name = c.getString(TAG_CLASSNAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_CLASSID, id);
map.put(TAG_CLASSNAME, name);
// adding HashList to ArrayList
classesList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
}
In my button's OnClickListener, I have the following:
onCreateDialog().show();
which launches the following dialog:
protected Dialog onCreateDialog() {
//Set up dialog
dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.checkindialog);
Button canceldialog = (Button) dialog.findViewById(R.id.btncancel);
//Define ListView and set it's empty view in case no results come back
this.lv = (ListView) dialog.findViewById(R.id.lvCheckin);
this.lv.setEmptyView(dialog.findViewById(R.id.empty));
TextView header = (TextView) dialog.findViewById(R.id.lblCheckin);
Typeface tf = Typeface.createFromAsset(getAssets(),
"fonts/roboto-light.ttf");
header.setTypeface(tf);
//ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(this,
// R.layout.checkin_item, R.id.list_content, checkinOptions);
ListAdapter adapter = new SimpleAdapter(Checkin.this, classesList,
R.layout.checkin_item, new String[] { TAG_CLASSID,
TAG_CLASSNAME }, new int[] { R.id.pid, R.id.name });
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listAdapter, View arg1,
int position, long arg3) {
CheckIn checkin = new CheckIn();
TextView txt = (TextView) listAdapter.getChildAt(
position - lv.getFirstVisiblePosition()).findViewById(
R.id.name);
String CheckinMessage = Utilities.getFacebookCheckinMessage(txt
.getText().toString(), context);
checkin.CheckInToFacebook(CheckinMessage, activity);
}
});
canceldialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
return dialog;
}
So like I said, this works fine, except the listview only gets it's data when the activity is launched, and I'm trying to have it happen when the button gets clicked. I've tried two things. Moving the "onCreateDialog().show();" to the "onPostExecute" of the AsncTask, but this doesn't work right, and I've tried moving the "new LoadAllProducts().execute();" into both the ondialog create event, as well as inline with the button click listener. Both of these only end up continually adding to the listview, instead of clearing/refreshing the listview each time.
Really hope someone can help, as I'm sure it's probably something stupid but this has been kicking my butt all day today.
Thanks in advance!
Evan try overriding the protected Dialog onCreateDialog(int id) function for show dialog and also override public void onPrepareDialog(int id, Dialog dialog). In onPrepareDialog function call removeDialog(int id) function this will help in creating a fresh dialog every time and remove previously cached data.

How to access values defined in AsyncTask from an activity

I have code like this
#Override
public void onCreate(Bundle savedInstanceState) {
addItemsOnSpinnerOrgaLevel();
btn_getReport.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//How can i access map and list defined in orgaLevelTask(AsyncTask)???
Like
String option = parent.getItemAtPosition(pos).toString();
int orgaCode = orgaLevelMap.get(option);
// Both are defined in AsyncTask ??
}); //end of anonymous class
} //end of onCreate()
public void addItemsOnSpinnerOrgaLevel() {
orgaLevelTask = new OrgaLevelTask(AccountReportActivity.this, spinner_orgaLevel, spinner_branch, txt_extra, txt_extra1);
orgaLevelTask.execute();
} //end of addItemsOnSpinnerOrgaLevel()
In AsyncTask onPostExecute() Method i have
#Override
protected void onPostExecute(ArrayList<OrgaLevel> result) {
super.onPostExecute(result);
if (result != null) {
addItemsOnSpinnerOrgaLevel(result);
}
dialog.dismiss();
} //end of onPostExecute()
public void addItemsOnSpinnerOrgaLevel(ArrayList<OrgaLevel> result) {
orgaLevelElementslist = new ArrayList<String>();
orgaLevelElementslist.add("All");
orgaLevelMap = new HashMap<String, Integer>();
orgaLevelMap.put("All", 0);
for (int i=0; i<result.size(); i++) {
OrgaLevel orgaLevelRecord = (OrgaLevel) result.get(i);
String key = orgaLevelRecord.getOrgaName();
String value = orgaLevelRecord.getOrgaCode();
orgaLevelMap.put(key, Integer.parseInt(value));
orgaLevelElementslist.add(key);
} //end of for()
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(accountReportActivity, android.R.layout.simple_spinner_item, orgaLevelElementslist);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner_orgaLevel.setAdapter(dataAdapter);
setSpinnerOrgaLevelListener();
} //end of addItemsOnSpinnerOrgaLevel()
private void setSpinnerOrgaLevelListener() {
spinner_orgaLevel.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
String option = parent.getItemAtPosition(pos).toString();
int orgaCode = orgaLevelMap.get(option);
subOrgaLevelTask = new SubOrgaLevelTask(accountReportActivity, spinner_branch, orgaCode);
subOrgaLevelTask.execute();
} //end of onItemSelected()
}); //end of anonymous class
} //end of setSpinnerOrgaLevelListener()
In the subOrgaLevelTask i also have the same hash map as in this class. You can see that what i am trying to do is, put a key value in spinner. So when my btn_getReport button get click then i get the value of the selected item. Like if All is slected then i get 0 and so on. This key value thing is working. The problem is when btn_getReport get click then how can i get the value of the selected item. Because i am filling items in a background thread(In OrgaLevelTask and SubOrgaLevelTask) and my button is in Activity. So how can i do that when button get click, then i get the values from the map defined in OrgaLevelTask and SubOrgaLevelTask ?
Thanks
well, make them public in orgaLevelTask, and simply access them. orgaLevelTask should be a variable in you activity class. Have you tried it? any errors?
You must make sure orgaLevelTask members will be accessed in thread safe manner

Get value in HashMap Android

I have two activitys...
Activity 1: have a edittext and two button:button1 & button2
Activity 2: have a autocompletetextview and a listview
I want to that when i enter string to edittext and click button1 ,i create a HashMap(static) to save value(set defaul="hello word") and key as string in edittext...
Event when click button1:
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
hashMap.put(edittext.getText().toString(),"hello word");//I declared hashMap
}
});
In activity2 :
public class Notification_App extends Activity {
AutoCompleteTextView actv_notification;
ListView lv_notification;
Dictionary1 dictionary1;
ArrayList<String> str_value;
ArrayList<String> array_key;
#Override
public void onCreate(Bundle circle)
{
super.onCreate(circle);
setContentView(R.layout.notification);
actv_notification=(AutoCompleteTextView)findViewById(R.id.actv_notification);
lv_notification=(ListView)findViewById(R.id.listview_notification);
array_key=new ArrayList<String>(dictionary1.hashMap.keySet());
Iterator myVeryOwnIterator = dictionary1.hashMap.keySet().iterator();
while(myVeryOwnIterator.hasNext())
{
String key=(String)myVeryOwnIterator.next();
String value=(String)dictionary1.hashMap.get(key);
str_value.add(value);
}
ArrayAdapter<String> adapter=new ArrayAdapter<String>(Notification_App.this, android.R.layout.simple_dropdown_item_1line,array_key);
ArrayAdapter<String> adapter1=new ArrayAdapter<String>(Notification_App.this, android.R.layout.simple_list_item_1,array_key);
actv_notification.setAdapter(adapter);
lv_notification.setAdapter(adapter1);
lv_notification.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), str_value.get(position), Toast.LENGTH_LONG).show();
}
});
}
but error display: null poiter at line: str_value.add(value);...Can you help me..
I think you just forgot to initialise str_value variable. Put before your while loop:
str_value = new ArrayList<String>();
and it should do the trick.
P.S. I'm not checking the logic of your code, simply pointing out why you get NullPointerException.
Try to add
str_value = new ArrayList<String>();
Before the first
str_value.add(value);
You're getting an exception because str_value is null.
You need to create the actual object:
str_value = new ArrayList<String>();

Refreshing a listview in android

I have a listview that contains values from webservice.Each page contains only 10 listitems and the next 10 in page 2 etc.Each listitem is clickable and it contains a button which is mainly for voting.So when i click the button in list item 1 ,a value is added to webservice.
The button click codes are placed in a custom base adapter class.So that i can easily add the vote.But the problem is,When i submit the vote,i want to refresh my listview also.Suppose if iam in page no 5,refresh that listview page.
How can i refresh this listview instantly after submitting the value to webservice?
sample code for main.java
private class ProgressThreadNextPageLoading extends
AsyncTask<String, Void, String> {
// private String Content;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(KidsCrackMeUp.this);
progressDialog.setMessage("Loading..Please Wait..");
progressDialog.setIcon(R.drawable.icon);
progressDialog.show();
}
#Override
protected String doInBackground(String... urls) {
String response = "";
// call ur webservice here
try {
// pagenum = 1;
posts= web
.getAllposts(pagenum);
response = "Yes";
} catch (Exception e) {
e.printStackTrace();
response = "Failure";
}
return response;
}
#Override
protected void onPostExecute(String result) {
// below line code is to dismiss the progress bar
progressDialog.dismiss();
if (posts != null) {
adapter = new DynamicListAdapter(
main.this, posts
lstPosts.setAdapter(adapter);
adapter.notifyDataSetChanged();
//btnState.setPressed(true);
}
----------------------------------custom adapter class
viewHolder.btnVoting.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final Dialog d = new Dialog(activity);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.voteselectornew);
Button btnCategoryCancel = (Button) d
.findViewById(R.id.btnCategoryCancel);
Button twcVote = (Button) d
.findViewById(R.id.btnTwcVote);
twcVote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String confirm = web
.addTwcVote(UserSessionKey, Userlist.get(position).contentid);
if (confirm.contains("Successfully")) {
d.dismiss();
}
You have to notify your ListView adapter that the data has changed.
listViewAdapater.notifyDataSetChanged();
you can just reasing your adapter via the constructor with the updated array.
call your listview adapter's method to update the change as:
adapter.notifyDataSetChanged();

Android adding a custom extended listactivity to layout in code

I have a simple linearlayout with a textbox a button and a listview, I'm doing some URL data getting when something is entered in the textbox and the button is pressed I want to parse the results and display in the listview.
What I can't work out is how to instatiate the listview from within my extende activity class and add it to the layout? I think I'm barking up the wrong tree !
public class HelloAndroid extends Activity{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyList L;
L = new MyList();
//setContentView(L.getListView());
EditText edittext = (EditText)findViewById(R.id.editText1);
edittext.setText("");
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
EditText edittext = (EditText)findViewById(R.id.editText1);
executeHttpGet(edittext.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void executeHttpGet(String vrm) throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://xxx/vrmtest.asp?vrm="+vrm));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
Context context = getApplicationContext();
CharSequence text = page;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class MyList extends ListActivity {
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Create an array of Strings, that will be put to our ListActivity
String[] names = new String[] { "Linux", "Windows7", "Eclipse", "Suse",
"Ubuntu", "Solaris", "Android", "iPhone"};
// Create an ArrayAdapter, that will actually make the Strings above
// appear in the ListView
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG)
.show();
}
}
}
An explanation would suffice rather than code but an example would be nice.
As long as your main.xml layout file has a ListView in it, you're on the right path. Set its #+id to something arbitrary and reference it in your code with:
ListView lv = (ListView) findViewById(R.id.arbitrary_id);
You don't necessarily need a ListActivity to use a ListView. Simply parse the data that you receive back from the server, put it in an array, and use lv.setAdapter(your_array_adapter) to fill the ListView with your data.
You can go further and specify your ItemClickListener by:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
}
};
Alternatively, you can create the ListView programmatically using
ListView lv = new ListView(this);
and adding it to a view in your layout with
some_container_view_in_main.addView(lv);
Then you would set the ArrayAdapter and OnItemClickListener the same as above.
You shouldn't create an Activity object yourself. Android will do it for you. Read this article, it will help you: http://developer.android.com/guide/topics/intents/intents-filters.html
If you want to add a ListView to your layout, just add it in the layout xml file. You can't add one activity to another until parent activity extends ActivityGroup. But that's not your case.
If what you want is to add the list to your layout, then use ListView instead of ListActivity.
you can then add the list as this.addView (myList);
Please follow the example here: http://developer.android.com/resources/tutorials/views/hello-listview.html

Categories

Resources