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();
Related
I am trying to refresh my listview for every insert, update, delete data from/into sqlite database.But, it can not work. I already used finishActivityFromChild(getParent(),1); but sometimes my app can not open.
How can i use notifyDataSetChanged(); for this code or any way ?
public class MainActivity extends AppCompatActivity {
DbHelper myDB;
Button btn_feedback;
FloatingActionButton btn_fab;
private String selectedName;
private int selectedID;
private boolean isUserClickedBackButton = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDB = new DbHelper(this);
final ListView listView = (ListView)findViewById(R.id.listview_main);
registerForContextMenu(listView);
Intent receivedIntent = getIntent();
selectedID = receivedIntent.getIntExtra("id",-1);
selectedName = receivedIntent.getStringExtra("item");
final ArrayList<String> theList = new ArrayList<>();
Cursor data = myDB.getListContents();
if (data.getCount() == 0){
Toast.makeText(getApplicationContext(),"Data Empty !",Toast.LENGTH_SHORT).show();
}
else {
while (data.moveToNext()){
theList.add(data.getString(1));
ListAdapter listAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1,theList);
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long l) {
String item1 = parent.getItemAtPosition(position).toString();
Toast.makeText(getApplicationContext(),"You Select - " + theList.get(position),Toast.LENGTH_SHORT).show();
Cursor data = myDB.getItemID(item1);
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Intent editScreenIntent = new Intent(getApplicationContext(), Edit_Main.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("ITEM1",item1);
startActivity(editScreenIntent);
}
else{
Toast.makeText(getApplicationContext(),"No ID Associated With That Name !",Toast.LENGTH_SHORT);
}
}
});
}
}
btn_fab = (FloatingActionButton)findViewById(R.id.fab);
btn_fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), Create_Main.class));
}
});
}}
Just Clear your arrayList inside while loop as below :
while (data.moveToNext()){
//////////////////////////////////////////////////
if(theList!=null && theList.size()>0){
theList.clear();
}
/////////////////////////////////////
theList.add(data.getString(1));
.....
.....
}
Hope, it helps.
I have an adapter, which get second parameter from "while" loop, so it must show me a query result in the ListView but it only shows me the last meaning of variable "string_word" instead. But even log.d output what I want line by line. Here is the code :
public class MainActivity extends Activity implements OnClickListener {
final String LOG_TAG = "myLogs";
IdDB idh;
SynDB sqh;
SQLiteDatabase sqdb, iddb;
Button btnOk;
EditText etWord;
String eWord;
ListView lvMain;
public ArrayAdapter<String> adapter;
public String string_word;
public String[] syns;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etWord = (EditText) findViewById(R.id.etWord);
btnOk = (Button) this.findViewById(R.id.btnOk);
lvMain = (ListView) findViewById(R.id.lvMain);
btnOk.setOnClickListener(btnOkListener);
//initialize our class-cover IdDB
idh = new IdDB(this);
// initialize our class-cover SynDB
sqh = new SynDB(this);
// we need db to read and write
sqdb = sqh.getWritableDatabase();
iddb = idh.getWritableDatabase();
}
public void displayListView(){
// создаем адаптер
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, syns);
}
public OnClickListener btnOkListener = new OnClickListener(){
#Override
public void onClick(View v) {
eWord = etWord.getText().toString();
switch (v.getId()){
case R.id.btnOk:
String query = //long SQL query (return "word")
Log.d(LOG_TAG, query);
Log.d(LOG_TAG, "--- Rows in mytable: ---");
// query to get Cursor
Cursor cursor = sqdb.rawQuery(query, null);
int wordColIndex = cursor.getColumnIndex(SynDB.Word);
while (cursor.moveToNext()) {
string_word = cursor.getString(wordColIndex);
Log.d(LOG_TAG, "word = "+ string_word);
syns = new String[] {string_word};
displayListView();
// присваиваем адаптер списку
lvMain.setAdapter(adapter);
}
cursor.close();
break;
default:
break;
} // close switch
} // close onClick
};
protected void onStop() {
super.onStop();
sqdb.close();
sqh.close();
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public void onClick(View view) {
}
}
What it does:
Create an array with one item string_word calls displayListView and set another adapter to the ListView
And do it everytime i gets a value from the list.
To do what you want, you should change your logic a bit.
You will create the adapter only one time.
You will add every string to a List (more flexible than an array since here you don't know how many words you will have)
So:
Delete all displayListView method calls and add one in the onCreate. (and every lvMain.setAdapter(adapter);)
Your displayListView should be the only one which sets the adapter to the ListView
public void displayListView(){
// создаем адаптер
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, syns);
lvMain.setAdapter(adapter);
}
Something like:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
etWord = (EditText) findViewById(R.id.etWord);
btnOk = (Button) this.findViewById(R.id.btnOk);
lvMain = (ListView) findViewById(R.id.lvMain);
btnOk.setOnClickListener(btnOkListener);
//initialize our class-cover IdDB
idh = new IdDB(this);
// initialize our class-cover SynDB
sqh = new SynDB(this);
// we need db to read and write
sqdb = sqh.getWritableDatabase();
iddb = idh.getWritableDatabase();
displayListView();
}
Go in the top where is
public String[] syns;
and change it type to List<String> (ArrayAdapter have a constructor with List, so don't worry.)
public List<String> syns;
Here your
int wordColIndex = cursor.getColumnIndex(SynDB.Word);
while (cursor.moveToNext()) {
string_word = cursor.getString(wordColIndex);
Log.d(LOG_TAG, "word = "+ string_word);
syns = new String[] {string_word};
displayListView();
// присваиваем адаптер списку
lvMain.setAdapter(adapter);
}
should look like
int wordColIndex = cursor.getColumnIndex(SynDB.Word);
while (cursor.moveToNext()) {
string_word = cursor.getString(wordColIndex);
Log.d(LOG_TAG, "word = "+ string_word);
syns = new String[] {string_word};
}
Now you should add to the List every word the Cursor return, so you should use .add method.
int wordColIndex = cursor.getColumnIndex(SynDB.Word);
while (cursor.moveToNext()) {
string_word = cursor.getString(wordColIndex);
Log.d(LOG_TAG, "word = "+ string_word);
syns.add(string_word);
}
When ready, call adapter.notifyDataSetChanged() to notify to the Adapter that you finished to change your data and can redraw the items in the ListView
hello I try to put in my java Code a Spinner, but it shows in the else if statement error:
private EditText textName;
private EditText textContent;
private Spinner CategorySpinner;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text);
configureButton1();
configureButton2();
textName = (EditText) findViewById(R.id.editTextName);
textContent = (EditText) findViewById(R.id.editContent);
CategorySpinner = (Spinner) findViewById(R.id.editCategorySpinner);
}
private void configureButton1() {
Button del = (Button)findViewById(R.id.btNewText);
del.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent myIntent = new Intent(v.getContext(), StartActivity.class);
v.getContext().startActivity(myIntent);
}
});
}
private void configureButton2() {
Button save = (Button) findViewById(R.id.btSave);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (textName.getText().length() == 0) {
textName.requestFocus();
return;
} else if (textContent.getText().length() == 0) {
textContent.requestFocus();
return;
} else if (CategorySpinner.**getText**().length() == 0) {
CategorySpinner.requestFocus();
return;
} else {
//next Step: get the mood
Intent myIntent = new Intent(v.getContext(), Activity2.class);
myIntent.putExtra("textName", textName.getText().toString());
myIntent.putExtra("textContent", textContent.getText().toString());
myIntent.putExtra("CategorySpinner", CategorySpinner.**getText()**.toString());
v.getContext().startActivity(myIntent);
}
}
}
});
}
it shows in the CategorySpinner.getText() an error. I hope you can help me.
I´ve tried a lot, but not found a solution.
private void initSpinnerList() {
spinner = (Spinner) findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(listner);
categories = new ArrayList<String>();
categories.add("S");
categories.add("T");
categories.add("U");
categories.add("V");
categories.add("W");
categories.add("X");
categories.add("Y");
categories.add("Z");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, categories);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
}
private OnItemSelectedListener listner = new OnItemSelectedListener() {
/*
* (non-Javadoc)
*
* #see
* android.widget.AdapterView.OnItemSelectedListener#onItemSelected(
* android .widget.AdapterView, android.view.View, int, long)
*/
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
String item = parent.getItemAtPosition(position).toString();
/// on item selected data
}
/*
* (non-Javadoc)
*
* #see
* android.widget.AdapterView.OnItemSelectedListener#onNothingSelected
* (android .widget.AdapterView)
*/
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
#Override
public void onClick(View v) {
if (spinner != null && categories != null) {
Log.v("Selected Spinner Item ",
categories.get(spinner.getSelectedItemPosition()));
}
}
You haven't provided adapter to spinner. please use below code for adapter:
Spinner spinner = new Spinner(this);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
spinner.setAdapter(spinnerArrayAdapter);
after that if u want text of an item than use below code:
String value = spinnerArray[spinner.getSelectedItemPosition()];
which will return value of selected item in spinner. Default it is 0.
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
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