Can anybody tell me the code to reload a Spinner?
I have created a small app where I can add some items and delete unwanted items. The items added will be showed in a spinner. Once I select an item from the spinner and delete it clicking the Delete Button, The item is getting deleted from the database & I get a Toast displayed "Item Deleted". But its still showing in the spinner until I logout and logs in once again. Here, I think I need to reload the spinner once again on the Delete button click. Can anybody help me out to do that?
public class DeleteChildActivity extends Activity {
TextView name;
Button delete;
Spinner spinner2;
private String URL = "/ParentProfileServlet";
private String URL1 = "/ChildProfileServlet";
private String URL2 = "/DeleteChildServlet";
ArrayList<NameValuePair> postparameter;
public static int selectChildId;
public static String imei;
ParentDetailsMod parentModel;
private ArrayList<ChildDetails> childArray = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.delete_child);
delete = (Button) findViewById(R.id.B_delchild);
spinner2 = (Spinner) findViewById(R.id.childspinner);
childArray = new SelectParser().parseSelectXml(response);
ArrayList<String> stringArray = new ArrayList<String>();
for (ChildDetails childModel : childArray) {
String str;
str = childModel.getName();
stringArray.add(str);
}
// spinner = (Spinner) findViewById(R.id.spinner11);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_list_item_1,
stringArray);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter);
spinner2.setPrompt(getString(R.string.selectLabel));
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int position, long arg3) {
imei = childArray.get(position).getImei_num();
selectChildId = childArray.get(position).getChild_id();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// spinner.performClick();
// String id = spinner2.getSelectedItem().toString();
// selectChildId = id.substring(0, id.indexOf("--"));
postparameter = new ArrayList<NameValuePair>();
String parent_id = LoginPageActivity.id;
postparameter
.add(new BasicNameValuePair("parent_id", parent_id));
postparameter.add(new BasicNameValuePair("child_id",
selectChildId + ""));
String response = null;
try {
response = CustomHttpClient.executeHttpPost(URL2,
postparameter);
System.out.println("response:" + response);
if (response.trim().compareTo("success") == 0) {
Toast.makeText(getApplicationContext(),
"Child deleted", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Failed to delete", Toast.LENGTH_LONG).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
You can use notifyDataSetChanged(); method to reload the adapter or display the changed data.
You should delete the item from you adapter list and then call spinner.notifyDataSetChanged() method to refresh you spinner
Related
I make application can input data from spinner into database when user open activity spinner retrieve data from DB and then if the user change value of spinner, its refresh the spinner (In My case if user click the edit button, data not match with database) how can I fix this?
This is my code :
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editfpp);
getAlamatBill(id);
}
#Override
protected void onResume() {
super.onResume();
spinnerprovinsibill.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String kodeprovinsi = helper.getRefprovinsi(spinnerprovinsibill.getSelectedItem().toString());
ambilKabupaten(kodeprovinsi, spinnerkabupatenbill);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinnerkabupatenbill.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String kodekabupaten = helper.getRefkabupaten(spinnerkabupatenbill.getSelectedItem().toString());
ambilKecamatan(kodekabupaten, spinnerkecamatanbill);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void ambilKecamatan(String kodekabupaten, Spinner spinnerkecamatanbill) {
List<String> data = helper.getKecamatan(kodekabupaten);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_background, data);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerkecamatanbill.setAdapter(adapter);
}
private void ambilKabupaten(String kodeprovinsibill, Spinner spinnerkabupatenbill) {
List<String> data = helper.getKabupaten(kodeprovinsibill);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.spinner_background, data);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerkabupatenbill.setAdapter(adapter);
}
private void ambilProvinsiPilihan(Spinner spinner, String namaprovinsi, String kabupaten, String kecamatan, String kelurahan){
List<String> data = helper.getProvinsi();
ArrayAdapter<String> dataadapter = new ArrayAdapter<String>(this, R.layout.spinner_background, data);
dataadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataadapter);
int posisi = dataadapter.getPosition(namaprovinsi);
spinner.setSelection(posisi);
System.out.println("hasil = " + helper.getRefkabupaten(kabupaten) + " " + helper.getRefkecamatan(kecamatan));
}
private void getAlamatBill(String id) {
try {
System.out.println("persiapan data: " + id);
JSONArray array = new JSONArray(helper.getAlamatShip(id));
JSONObject object = array.getJSONObject(0);
String alamat = object.getString("alamat");
String kdpos = object.getString("kdpos");
String kelurahan = object.getString("kelurahan");
String kecamatan = object.getString("kecamatan");
String kabupaten = object.getString("kabupaten");
String provinsi = object.getString("provinsi");
String kota = object.getString("kota");
ambilProvinsiPilihanShip(spinnerprovinsiship, provinsi, kabupaten, kecamatan, kelurahan);
ambilKotaPilihan(spinnerkotaship, kota);
edalamatship.setText(alamat);
edkodeposship.setText(kdpos);
} catch (JSONException e) {
e.printStackTrace();
}
}
thanks in advance
This is my code i am very tried to show item in spinner but all is vain
list show when press spinner arrow but does not select and does not show in toast so please help me and guide me where I am wrong
public class MakeComplain extends AppCompatActivity implements
OnItemSelectedListener {
private Spinner spinner,spinner1,spinner3;
private TextView txtCategory;
private ArrayList<String> Station;
private JSONArray result;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_complain);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
spinner1 = (Spinner) findViewById(R.id.station);
spinner3 = (Spinner) findViewById(R.id.generator);
spinner = (Spinner) findViewById(R.id.complain);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Get data from the list which you had set to the adapter of spinner1
Toast.makeText(MakeComplain.this, "Spinner1 Item Clicked: "+position, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Get data from the list which you had set to the adapter of spinner3
Toast.makeText(MakeComplain.this, "Spinner3 Item Clicked: "+position, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
ArrayAdapter arrayAdapter = ArrayAdapter.createFromResource(this, R.array.Complain, android.R.layout.simple_spinner_item);
spinner.setAdapter(arrayAdapter);
spinner1.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, this.fetchTwitterPublicTimeline()));
spinner3.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, this.fetchGeneratorList()));
}
public ArrayList<String> fetchTwitterPublicTimeline()
{
final ArrayList<String> listItems = new ArrayList<String>();
new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL("http://bigbi.com/cs/Station.php");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
InputStream stream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString("name"));
}
}
bufferedReader.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
return listItems;
}
public ArrayList<String> fetchGeneratorList()
{
final ArrayList<String> listItems = new ArrayList<String>();
new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL("http://biges.com/12/get.php");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
//urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0");
InputStream stream = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(stream);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
JSONArray ja = new JSONArray(line);
for (int i = 0; i < ja.length(); i++) {
JSONObject jo = (JSONObject) ja.get(i);
listItems.add(jo.getString("gen_no"));
}
}
bufferedReader.close();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
return listItems;
}
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
Please try with this,
spinner1.setAdapter(new ArrayAdapter<String>(this, R.layout.spinner_item, fetchTwitterPublicTimeline()));
spinner3.setAdapter(new ArrayAdapter<String>(this, R.layout.spinner_item,fetchGeneratorList()));
for clicking on item can add.
public void onItemSelected(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(getActivity(), "Item clicked",
Toast.LENGTH_LONG).show();
}
You have missed two things.
You haven't added the listener for selecting an item. Add the following to add the listener.
spinner.setOnItemSelectedListener(this);
Add the same for other spinners if you want.
Add the code for showing toast in onItemSelected() method. Something like this
Toast.makeText(this, "Item Clicked", Toast.LENGTH_SHORT).show();
You had implemented listener for onItemSelection for spinner but you didn't set the onItemSelection to the spinner, so update your onCreate like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_make_complain);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
spinner1 = (Spinner) findViewById(R.id.station);
spinner3 = (Spinner) findViewById(R.id.generator);
spinner = (Spinner) findViewById(R.id.complain);
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Get data from the list which you had set to the adapter of spinner1
Toast.makeText(this, "Spinner1 Item Clicked: "+position, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Get data from the list which you had set to the adapter of spinner3
Toast.makeText(this, "Spinner3 Item Clicked: "+position, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//Get data from the list which you had set to the adapter of spinner
Toast.makeText(this, "Spinner Item Clicked: "+position, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
ArrayAdapter arrayAdapter = ArrayAdapter.createFromResource(this, R.array.Complain, android.R.layout.simple_spinner_item);
spinner.setAdapter(arrayAdapter);
Station=this.fetchTwitterPublicTimeline();
spinner1.setAdapter(new ArrayAdapter<String>(this, R.layout.spinner_item,R.id.txt, this.fetchTwitterPublicTimeline()));
spinner3.setAdapter(new ArrayAdapter<String>(this, R.layout.spinner_item,R.id.txt, this.fetchGeneratorList()));
}
Individually I set here setOnItemSelectedListener to spinners because if we override one method as you are doing then you will not able to find out which spinners item selection is callback.
So for this remove the implementation for implements
OnItemSelectedListener from your Activity and relatively it's overrided methods also and do as I answered.
I was tried to retrieve data from database based selected item on spinner.
Here is my database structure
Here is my Activity:
public class help_activity extends Activity implements OnClickListener{
Spinner spinner1;
SQLiteConnector sqlConnect;
ListView lvUsers;
Button b1;
String colors[] = {"Bristleback","Sven","Tiny","Undying", "Naix","Weaver","Spectre","Lich"};
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_help);
spinner1 = (Spinner) findViewById(R.id.spinner1);
lvUsers = (ListView) findViewById(R.id.listView1);
b1 = (Button) findViewById(R.id.btn1);
sqlConnect = new SQLiteConnector(this);
addListenerOnSpinnerItemSelection();
final String nameSelected = spinner1.getSelectedItem().toString();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1, sqlConnect.getAllRecord(nameSelected));
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (nameSelected.equals("Bristleback")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else if (nameSelected.equals("Sven")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else if (nameSelected.equals("Tiny")) {
lvUsers.setAdapter(adapter);
}
else if (nameSelected.equals("Undying")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else if (nameSelected.equals("Naix")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else if (nameSelected.equals("Weaver")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else if (nameSelected.equals("Spectre")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
else if (nameSelected.equals("Lich")) {
lvUsers.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
// TODO Auto-generated method stub
}
});
}
public void addListenerOnSpinnerItemSelection() {
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_spinner_dropdown_item,colors );
spinner1.setAdapter(spinnerArrayAdapter);
}
#Override
public void onClick(View v) {
}
}
And this my method to retrieve data from database:
public List<String> getAllRecord(String nameSelected) {
List<String> namagambar = new ArrayList<String>();
String selectQuery = "SELECT * FROM " + TABLE_RECORD + " WHERE "
+ HERO_NAME + "=?";
database = dbHelper.getReadableDatabase();
cursor = database.rawQuery(selectQuery, new String[]{nameSelected});
if (cursor.moveToFirst()) {
do {
namagambar.add(cursor.getString(1));
} while (cursor.moveToNext());
}
database.close();
return namagambar;
}
So, when user selected an item on spinner, then the data at nama_hero will showed at listview based on the selected name hero on spinner. But when i running my code, it just showed the top of data on the database
So when i selected name Sven on spinner, the name that showed on listview not "sven" but "bristleback". And it happened also when I choose other hero name.
I think my method to get the name of the selected item in the spinner does not work
Please help me to fix this problem.
SOLVED !!!
Done !!
I already solved this problem, thanks stackoverflow
I change my setOnclickListener become like this b1.setOnClickListener(this);
And move all the items that were in previous to:
public void onClick(View v) {
}
Try to get selected item inside ClickListener
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String nameSelected = spinner1.getSelectedItem().toString();
I have an SQLite table and in the certain activity I obtain all the names fom the table and populate a listview with these names.
Inside the listview listener, the user have can delete the selected item.
The problem is when I delete the item the app crashes.
Please take a look on my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mylocations);
tv_counter = (TextView) findViewById(R.id.counter);
tv_testCounter = (TextView) findViewById(R.id.testCounter);
lv = (ListView) findViewById(R.id.mylist);
mpoh = new MP_DB(this);
db = mpoh.getWritableDatabase();
cv = new ContentValues();
if (hasRecords()) {
Toast.makeText(getBaseContext(), getRowsNum()+" row(s)", Toast.LENGTH_SHORT).show();
get_MPNames();
arrayToArrayList();
setListView();
lv.setOnItemClickListener(listViewListener);
} else {
Toast.makeText(getBaseContext(), "NO RECORDS"+","+getRowsNum()+"rows", Toast.LENGTH_SHORT).show();
}
}
Here are the method to convert the array to arraylist, and the listview listener:
private void arrayToArrayList() {
int s = str.length;
al = new ArrayList<String>();
for (int i=0; i < s; i++) {
al.add(str[i]);
}
}
private int getRowsNum() {
return mpoh.getCurrentRowNumber();
}
OnItemClickListener listViewListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
pos = arg2;
showDialoge();
}
};
Here how I delete element from the DB and the ListView:
private void deleteMPfromListView(int pos) {
al.remove(pos);
adapter.notifyDataSetChanged();
Toast.makeText(getBaseContext(), al.size()+" rows left in list view", Toast.LENGTH_SHORT).show();
}
private void deleteMPFromDB(int pos) {
mpoh.deleteMP(pos);
Toast.makeText(getBaseContext(), getRowsNum()+" rows left in DB", Toast.LENGTH_SHORT).show();
}
private Boolean hasRecords() {
if (getRowsNum() == 0) {
return false;
} else {
return true;
}
}
private void setListView() {
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
android.R.id.text1, al);
lv.setAdapter(adapter);
}
private void get_MPNames() {
str = new String[getRowsNum()];
for (int i=0; i <= getRowsNum()-1; i++) {
str[i] = mpoh.getMP_Name(i+1);
} //tv_testCounter.setText(str[87]);
}
Removing from the database has nothing to do with removing them from the ListView. I have not code of your implementation but you may try something like this too dynamically add or remove items:
public class LVDemo extends ListActivity {
// handles the ListView data
ArrayAdapter<String> adapter;
// Items that are displayed
ArrayList<String> listItems=new ArrayList<String>();
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
listItems);
setListAdapter(adapter);
}
/**
* Remove item.
*/
public void removeItem(int index) {
listItems.remove(index);
adapter.notifyDataSetChanged();
}
}
In General: You change the the ArrayList containing the element and then notify the adapter for the ListView
I have one class that shows me a list of Items. Right now I am selecting this items with click (setOnItemClickListener), but i don't want that. What i want is: when i open the class automatically is selecting the last item on the list.
Can anyone tell me how I can do it?
Thanks for any help
public class SelectCodIncidence extends Activity {
private ArrayList<String> datos;
protected netAppApplication app;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.codincidence);
datos = new ArrayList<String>();
//datosCod = new ArrayList<String>();
try {
NotesCenter messageCenter = new NotesCenterImpl();
List<CodIncidence> codincidence = messageCenter.getCodIncidence();
for (CodIncidence e : codincidence) {
//datosCod.add("1");
datos.add(e.id);
}
} catch (Exception ex) {
// showMessage(ex);
Log.v("blah", ex.getMessage());
}
ArrayAdapter<String> adaptador =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, datos);
final TextView lblMessage = (TextView)findViewById(R.id.MensajeCodIncidence);
final GridView grdOptions = (GridView)findViewById(R.id.GridCodIncidence);
grdOptions.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, android.view.View v, int position, long id) {
CodIncidence codincidenceSelected = new CodIncidence();
codincidenceSelected.id = datos.get(position);
app = (netAppApplication)getApplicationContext();
app.setcodincidenceActual(codincidenceSelected);
SharedPreferences prefs = getSharedPreferences("netAppSetup",2);
SharedPreferences.Editor editor = prefs.edit();
editor.putString("CODINCIDENCE", codincidenceSelected.id);
editor.commit();
finish();
}
});
grdOptions.setAdapter(adaptador);
}
}
Something like:
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
int count = spinner.getCount();
if (count > 0){
spinner.setSelection(count-1,true);
}