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
Related
Here I'm trying to send my value that gets from a spinner (array adapter) to another activity. I populate my spinner using json and my spinner is something like below.
ArrayAdapter<String> adp = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, villageList);
spinner_village.setAdapter(adp);
spinner_village.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
try {
JSONObject villageObject = arrayList.get(position);
String villageId = villageObject.getString("id");
String villageName = villageObject.getString("name");
String villageCode = villageObject.getString("village_code");
Toast.makeText(Region.this, villageCode, Toast.LENGTH_SHORT).show();
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
Now I'm trying to get "villageCode" to my on create a method so that I can pass this value to my another activity. What I've done so far is
spinner_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Region.this, Participant_Details.class)
.putExtra("catment_code", **-----**);
Region.this.startActivity(intent);
Region.this.finish();
}
})
putextra is giving error. How can I resolve it or what is the problem.
You can set the string villageCode as global variable (You can make your variable global by declaring it in the class level It should not be inside any method in your class) and then you extract the value of the string in your onClick method. Like so:
spinner_next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Region.this, Participant_Details.class)
.putExtra("catment_code", villageCode); //the value is being set here
Region.this.startActivity(intent);
Region.this.finish();
}
})
i have tried all the things but i cant get proper result,i also try
adapter.clearAll()
adapter.notifyDataSetChanged()
but i cant get result when i delete row from list view its deleted from its position but when i change value of another row than the delete process working perfectly but changed value not set.getting value from database perfectly.
Here is my code please help me and tell where i m doing wrong.
Thank you in advance
Delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String Identifier_fev = null;
String Default_Option = null;
String Quantity1 = null;
jffDatabase.open();
Cursor identifie = jffDatabase.getALL();
if (identifie.moveToPosition(position)) {
Identifier_fev = identifie.getString(identifie.getColumnIndexOrThrow("identifier"));
Default_Option = identifie.getString(identifie.getColumnIndexOrThrow("default_option"));
}
jffDatabase.delete(Identifier_fev, Default_Option);
identifier.remove(position);
title.remove(position);
defaultPrice.remove(position);
default_option.remove(position);
price.remove(position);
quantity.remove(position);
Cursor c1 = jffDatabase.getALL();
if (c1.moveToFirst()) {
do {
Quantity1 = c1.getString(c1.getColumnIndexOrThrow("quantity"));
update_quantity.add(Quantity1);
} while (c1.moveToNext());
}
for (int i = 0; i < update_quantity.size(); i++) {
Toast.makeText(ctx, "" + update_quantity, Toast.LENGTH_LONG).show();
Quantitylbl.setText(update_quantity.get(i).toString());
Toast.makeText(ctx, "set " + Quantitylbl.getText().toString(), Toast.LENGTH_LONG).show();
}
Quantity();
notifyDataSetChanged()
AddtoCartActivity.Cartcount.setText(String.valueOf(sum));
}
});
Good practice is use Interface
Create new Interface
public interface MyCustomObjectListener {
public void RefreshList();
//add parameter for delete if required ex-
//public void RefreshList(String Item_id);
}
then implement Activity by this Interface
YourActivityName extends Activity implements MyCustomObjectListener
And Implement Method
#Override
public void RefreshList() {
// Do your delete task and clear current List and get updated list task here
}
and from Base adapter onClick you can call method RefreshList like this
((YourActivityName)mContext).RefreshList();
you can delete and refresh list from #Override RefreshList
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
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>();
I am trying to use a spinner control that will enable the user to delete any list element.
I have an 'add' button to add elements to the list, and a 'delete' button that removes the currently-displayed item from the list.
It works as expected except when the user deletes the last item in the list. At that point, all of the list's items are deleted.
My code is as follows:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// grab our UI elements so we can manipulate them (for the Spinner)
// or add listeners to them (in the case of the buttons)
m_myDynamicSpinner = (Spinner)findViewById(R.id.dynamicSpinner);
m_addItemText = (EditText)findViewById(R.id.newSpinnerItemText);
Button addButton = (Button)findViewById(R.id.AddBtn);
Button clearButton = (Button)findViewById(R.id.ClearBtn);
// create an arrayAdapter an assign it to the spinner
m_adapterForSpinner = new ArrayAdapter(this, android.R.layout.simple_spinner_item);
((ArrayAdapter)m_adapterForSpinner).setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
m_myDynamicSpinner.setAdapter(m_adapterForSpinner);
// add listener for addButton
addButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
addNewSpinnerItem();
}
});
clearButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearSpinnerItems();
}
});
}
// add listener for addButton
private void addNewSpinnerItem() {
if (m_addItemText.getText().length() == 0) {
Toast.makeText(getApplicationContext(), "The textView is empty", Toast.LENGTH_LONG).show();
} else {
CharSequence textHolder = "" + m_addItemText.getText();
((ArrayAdapter) m_adapterForSpinner).add(textHolder);
}
m_addItemText.setText("");
}
private void clearSpinnerItems() {
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object t = m_adapterForSpinner.getItem(pos);
((ArrayAdapter) m_adapterForSpinner).remove((CharSequence) t);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO
}
});
}
Does anyone have any ideas or suggestions on how to make this work?
The problem with your code is that the deletion is inside the onItemSelected callback, which gets called every time you are deleting an entry, thus deleting recursively until you effectively do not have any more entries to select. If you add a log inside that method:
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
you will see what I mean. I'm sure you can come up with more elegant code, but a quick and dirty hack is to set up a boolean flag to stop the recursion after the first deletion. See the snippet below and add the commented lines to your own code:
public class SpinnerTest extends Activity {
Spinner m_myDynamicSpinner;
EditText m_addItemText;
ArrayAdapter m_adapterForSpinner;
public static boolean cleared = false; // <--- set up a static boolean here
#Override
public void onCreate(Bundle savedInstanceState) {
// all your code unchanged
clearButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
cleared=false; // <--- nope, we did not clear the value yet
clearSpinnerItems();
}
});
}
// code unchanged
private void clearSpinnerItems() {
m_myDynamicSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
Object t = m_adapterForSpinner.getItem(pos);
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
if (!cleared) // <--- did I do it already?
((ArrayAdapter) m_adapterForSpinner).remove((CharSequence) t);
Log.d("Spinner", "Count: " + m_adapterForSpinner.getCount());
cleared=true; // I did it!
}
// code unchanged
i cann't understand your question.any way you can get the position of the selected item by using getSelectedItemPosition() method.