I want to get all username from my user table to be displayed in my spinner for selection but instead of displaying all username from my list it displays only one which is the first user from my database.. how can i get all username?
String q = "SELECT * FROM " + User.TABLE;
Cursor cursor = dbHelper.getReadableDatabase().rawQuery(q, null);
String[] ComRep = new String[0];
if (cursor.moveToFirst()) {
String rep = cursor.getString(cursor.getColumnIndex(User.KEY_username));
do {
ComRep = new String[]{rep};
} while (cursor.moveToNext());
}
cursor.close();
Comrep = (Spinner) findViewById(R.id.spincomrep);
ArrayAdapter<CharSequence> adapterrep = new ArrayAdapter<CharSequence>(this, R.layout.spinner_item, ComRep);
adapterrep.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Comrep.setAdapter(adapterrep);
Comrep.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Comrep.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
thanks in advance..
You're not actually accumulating any values in your array. You're making a new array each time you go through the loop.
ArrayList<String> values = new ArrayList<String>();
while (cursor.moveToNext()) {
String rep = cursor.getString(cursor.getColumnIndex(User.KEY_username));
values.add(rep);
}
cursor.close();
ArrayAdapter<CharSequence> adapterrep = new ArrayAdapter<CharSequence>(this, R.layout.spinner_item, values.toArray(new String[values.size]));
You should look at CursorAdapter. You could make an adapter directly from your cursor so you don't need to code the loop.
Related
Hi I have been working through several different tutorials on getting data from a sql database into a listview. I can add data, get data from database and populate the list view, and have a working onclick listener (will fire off a Toast message). However I can not get any data from the listview when clicked. I have tried different combinations of getitem and getItemAtPosition but they all return a empty string(blank toast). Would someone be kind enough to look at my code and tell me if what I am trying to do is possible. In my listview i have four items in each entry, I would like to either get the fourth item directly or get all the items (as string?) then I can pull out the data I need.
Thanks in advance for your time.
public class ListViewActivity extends Activity {
SQLiteHelper SQLITEHELPER;
SQLiteDatabase SQLITEDATABASE;
Cursor cursor;
SQLiteListAdapter ListAdapter ;
ArrayList<String> ID_ArrayList = new ArrayList<String>();
ArrayList<String> GENRE_ArrayList = new ArrayList<String>();
ArrayList<String> NAME_ArrayList = new ArrayList<String>();
ArrayList<String> URL_ArrayList = new ArrayList<String>();
ListView LISTVIEW;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
LISTVIEW = (ListView) findViewById(R.id.listView1);
SQLITEHELPER = new SQLiteHelper(this);
}
#Override
protected void onResume() {
ShowSQLiteDBdata() ;
super.onResume();
}
private void ShowSQLiteDBdata() {
SQLITEDATABASE = SQLITEHELPER.getWritableDatabase();
cursor = SQLITEDATABASE.rawQuery("SELECT * FROM demoTable1", null);
ID_ArrayList.clear();
GENRE_ArrayList.clear();
NAME_ArrayList.clear();
URL_ArrayList.clear();
if (cursor.moveToFirst()) {
do {
ID_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_ID)));
GENRE_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Genre)));
NAME_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Name)));
URL_ArrayList.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.KEY_Url)));
} while (cursor.moveToNext());
}
ListAdapter = new SQLiteListAdapter(ListViewActivity.this,
ID_ArrayList,
GENRE_ArrayList,
NAME_ArrayList,
URL_ArrayList
);
LISTVIEW.setAdapter(ListAdapter);
LISTVIEW.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// String text = (String) LISTVIEW.getAdapter().getItem(position);
String text = (String) LISTVIEW.getItemAtPosition(position);
//String text = (String) lv.getItemAtPosition(0);
// Object item = (Object) LISTVIEW.getItemAtPosition(position);
Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT).show();
}
});
cursor.close();
}
}
LISTVIEW.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String value1 = ID_ArrayList.get(position);
String value2 = GENRE_ArrayList.get(position);
String value3 = NAME_ArrayList.get(position);
String value4 = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(),value1+" "+value2+" "+value3+" "+value4, Toast.LENGTH_SHORT).show();
}
});
try to change the line
String text = (String) LISTVIEW.getItemAtPosition(position);
with
String text = (String) parent.getItemAtPosition(position);
this should be the way ListView works.
Also i suggest you to not use Capital Cases with variables, usually in Java is used a CamelCase convention. And also have a look at RecyclerView, that usually is implemented today much more than ListView, because allow a great level of customization
Pls use below code within listview setOnItemClickListener :-
String genreID = ID_ArrayList.get(position);
String genre = GENRE_ArrayList.get(position);
String genreName = NAME_ArrayList.get(position);
String genreUrl = URL_ArrayList.get(position);
Toast.makeText(getApplicationContext(), genreID+", "+genre+","+genreName+", "+genreUrl+", "+, Toast.LENGTH_SHORT).show();
its return render data of listview.
try this,
ShowSQLiteDBdata() in onCreate() instead of onResume() method
thanks for your help
I'm trying populate a spinner with data from an embedded database, and everything seems right:
public ArrayList<String[]> getCountries()
{
ArrayList<String[]> array = new ArrayList<>();
String columnas[] = new String[]{"COUNTRY","COUNTRYCODE"};
Cursor c = db.query("countryCodT",columnas,null,null,null,null,null);
if(c.moveToFirst()){
do{
String[] obj = new String[2];
obj[0]=c.getString(0);
obj[1]=c.getString(1);
array.add(obj);
}while(c.moveToNext());
c.close();
db.close();
}
return array;
}
with this code the spinner is populated:
public void popSpinnerC(){
BDCountries bdCountries = new BDCountries(this);
final ArrayList<String[]> dataGot = bdCountries.getCountries();
ArrayAdapter<String[]> dataAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item,dataGot);
spnCountry.setAdapter(dataAdapter);
spnCountry.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
String listId = Integer.toString(i);
strCounty = listId + dataGot.get(i)[0] + dataGot.get(i)[1];
msgData.setText(strCounty);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
the spinner text shown is wrong, the data amount is correct, when something is selected is shown the right information in a text view with test purposes, how can I correct it?
Results:
The spinner option list is a list of string arrays rather than strings so it is printing toString() of each string array as a spinner item.
Look at your getCountries() method. It is returning ArrayList<String[]> instead of ArrayList<String>.
this is a succesor to this question
At first everything worked fine but after 2 deletes the misery starts. The database entries start with ID 1, then 2 and so on. Lets say I have three database entries. The listview IDs for these three entries are 2,1 and 0.
The database entries are 1,2 and 3. 1 and 2 will be deleted with the onitemclicklistener but since the listview doesn´t have an ID 3, the corresponding database entry will never ever be deleted.
So the question is, how can I "sync" those two IDs?
Listview-Class
public class anzeigen extends AppCompatActivity {
private static final String TAG = anlegen.class.getSimpleName();
private static final String FILENAME = TAG + ".kdf";
private List valueList = new ArrayList<String>();
final VorgangDataSource dataSource = new VorgangDataSource(this);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_anzeigen);
Log.d(TAG,"Die Datenquelle wird geöffnet!");
dataSource.open();
final List<vorgangsdaten> vorgangsdatenList = dataSource.getAllVorgangsDaten();
final ArrayAdapter<vorgangsdaten> VorgangArrayAdapter = new ArrayAdapter<>(
this,
R.layout.mylistlayout,
vorgangsdatenList
);
final ListView lv = (ListView)findViewById(R.id.listView);
lv.setAdapter(VorgangArrayAdapter);
lv.setItemsCanFocus(false);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s_id = String.valueOf(id);
Log.d(s_id,"id_in_onitem");
String p_id = String.valueOf(position);
Log.d(p_id,"position_on_item");
int pos = position;
vorgangsdatenList.remove(pos);
dataSource.deleteRow(id);
VorgangArrayAdapter.notifyDataSetChanged();
}
});
//ActionBar Costumization
android.support.v7.app.ActionBar ab = getSupportActionBar();
ab.setIcon(R.drawable.search1);
ab.setDisplayShowHomeEnabled(true);
ab.setDisplayUseLogoEnabled(true);
}
#Override
protected void onDestroy() {
super.onDestroy();
dataSource.close();
}
}
deleteRow-Method:
public void deleteRow(long id){
String s_id;
s_id = String.valueOf(id);
Log.d(s_id,"id_value");
database.delete(VorgangDbHelper.TABLE_VORGAENGE_LIST,VorgangDbHelper.COLUMN_ID + " = ?", new String[] {s_id});
long deleteID = database.delete(VorgangDbHelper.TABLE_VORGAENGE_LIST,VorgangDbHelper.COLUMN_ID + " = ?", new String[] {s_id});
String s_del = String.valueOf(deleteID);
Log.d(s_del,"delete_row_value");
}
If you need more code just let me know :)
You have no synchronicity between your Database and the ListView items.
When selecting the data, select the ID from the table, and keep it in memory as well.
Since vorgangsdaten looks german or sweden, I am having trouble understanding the meaning of those words. The ListView has its own "id" for each item, to keep a list of them shown, and the rest "hidden". What you must do is have an Object with details that are syncronized with the database, and when a list item is clicked, the "list id" is used to query an Object and delete from the database.
An example would be:
ArrayList<MyObject> arrayListData = new ArrayList<>();
ArrayList<String> arrayListNames = new ArrayList<>();
MyObject stuffs = database.query(); // In here, fetch the data
/* I am simplifing the MyObject to [String name, String aValue, int aNumber] */
for(MyObject s: stuffs){
arrayListData.add(s);
arrayListNames.add(s.name);
}
arrayAdapter = new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_1,
arrayListNames
);
listView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MyObject thing = arrayListData.get(position);
database.delete(thing.aNumber);
}
}
);
listView.setAdapter(arrayAdapter);
After trying Bonattis answer and experimenting a little bit I found another answer.
deleteRow-Method
public void deleteRow(long id){
String s_id; //String for long id
s_id = String.valueOf(id); //assign String value of id
String s_rowId = null; //String for rowid
long rowId = 0;
long deleteId = 0;
String s_deleteId = null;
Log.d(s_id,"id_value");
Cursor cursor = database.query(VorgangDbHelper.TABLE_VORGAENGE_LIST,columns,null,null,null,null,null);
if(cursor.moveToFirst()) {
s_rowId = cursor.getString(cursor.getColumnIndex(VorgangDbHelper.COLUMN_ID));
rowId = Long.parseLong(s_rowId);
deleteId = rowId + id;
s_deleteId = String.valueOf(deleteId);
Log.d(s_rowId,"rowID");
Log.d(s_deleteId,"deleteID");
}
database.delete(VorgangDbHelper.TABLE_VORGAENGE_LIST,VorgangDbHelper.COLUMN_ID + " = ?", new String[] {s_deleteId});
}
How does it work now?
So the deleteRow-Method(dRM) gets the id of the first database entry (s_rowId) and converts it to long (rowId).
Now I take the long id passed from the listview and add it to rowId which is my deleteId. With this I have the correct database value to what I clicked in the listview and can pass it over to database.delete
I am working on EditText and Spinner . When I set text for EditText it were fine but when I try to set text for Spinner it give error.
this is code for set text EditText
New_Name.setText(NewName);
here New_Name is EditText
this is code for set text Spinner
New_Quantity.setText(NewQuantity);
here New_Quantity is Spinner
this is the full code.
public class UpdateFoodActivity extends Activity {
EditText Name_Search,New_Name,New_Calorie,New_Fat,New_Protein,New_Sugar,New_carbohydrates;
Spinner New_Quantity;
TextView title_text;
String SearchName,NewName,NewQuantity,NewCalorie,NewFat,NewProtein,NewSugar,Newcarbohydrates;
FoodDbHelper foodDbHelper;
SQLiteDatabase sqLiteDatabase;
Button UpdateButton;
ArrayAdapter<CharSequence> adapter;
private Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.update_food_activity);
Name_Search = (EditText)findViewById(R.id.name_search);
New_Name = (EditText)findViewById(R.id.new_name);
New_Quantity = (Spinner)findViewById(R.id.new_quantity);
adapter = ArrayAdapter.createFromResource(this, R.array.quant, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
New_Quantity.setAdapter(adapter);
New_Quantity.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
New_Calorie = (EditText)findViewById(R.id.new_calorie);
New_Fat = (EditText)findViewById(R.id.new_fat);
New_Protein = (EditText)findViewById(R.id.new_protein);
New_Sugar = (EditText)findViewById(R.id.new_sugar);
New_carbohydrates = (EditText)findViewById(R.id.new_vitamins);
UpdateButton = (Button)findViewById(R.id.update_button);
title_text = (TextView)findViewById(R.id.title_text);
New_Name.setVisibility(View.GONE);
New_Quantity.setVisibility(View.GONE);
New_Calorie.setVisibility(View.GONE);
New_Fat.setVisibility(View.GONE);
New_Protein.setVisibility(View.GONE);
New_Sugar.setVisibility(View.GONE);
New_carbohydrates.setVisibility(View.GONE);
UpdateButton.setVisibility(View.GONE);
title_text.setVisibility(View.GONE);
}
public void searchFood(View view){
SearchName = Name_Search.getText().toString();
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getReadableDatabase();
Cursor cursor = foodDbHelper.getFood(SearchName,sqLiteDatabase);
if (cursor.moveToFirst()) {
NewQuantity = cursor.getString(0);
NewCalorie = cursor.getString(1);
NewFat = cursor.getString(2);
NewProtein = cursor.getString(3);
NewSugar = cursor.getString(4);
Newcarbohydrates = cursor.getString(5);
NewName = SearchName;
New_Name.setText(NewName);
New_Quantity.setText(NewQuantity);
New_Calorie.setText(NewCalorie);
New_Fat.setText(NewFat);
New_Protein.setText(NewProtein);
New_Sugar.setText(NewSugar);
New_carbohydrates.setText(Newcarbohydrates);
New_Name.setVisibility(View.VISIBLE);
New_Quantity.setVisibility(View.VISIBLE);
New_Calorie.setVisibility(View.VISIBLE);
New_Fat.setVisibility(View.VISIBLE);
New_Protein.setVisibility(View.VISIBLE);
New_Sugar.setVisibility(View.VISIBLE);
New_carbohydrates.setVisibility(View.VISIBLE);
UpdateButton.setVisibility(View.VISIBLE);
title_text.setVisibility(View.VISIBLE);
}
else
{
Toast.makeText(getApplicationContext(),
"No Dish Found " ,
Toast.LENGTH_SHORT).show();
}
}
public void updatebutton(View view)
{
foodDbHelper = new FoodDbHelper(getApplicationContext());
sqLiteDatabase = foodDbHelper.getWritableDatabase();
String name,quantity,calorie,fat,protein,sugar,carbohydrates;
name = New_Name.getText().toString();
quantity = New_Quantity.getSelectedItem().toString();
calorie = New_Calorie.getText().toString();
fat = New_Fat.getText().toString();
protein = New_Protein.getText().toString();
sugar = New_Sugar.getText().toString();
carbohydrates = New_carbohydrates.getText().toString();
int count = foodDbHelper.updateInformation(SearchName,name,quantity,calorie,fat,protein,sugar,carbohydrates,sqLiteDatabase);
Toast.makeText(getApplicationContext(),count+" dish updated",Toast.LENGTH_LONG).show();
Intent intent = new Intent(this,UpdateFoodActivity.class);
startActivity(intent);
}
}
In order to add entries to the spinner you need to define an Adapter i give you an example:
spinner = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.spinner_item, list);
spinner.setAdapter(dataAdapter);
Spinner likes ListView, need an adapter for rendering data. Adapter, in simple term, is a collection of items. (As you see ListView always contains list of item and also Spinner). Nevertheless, Adapter of spinner often a list of string. (because spinner just represents user choice)
In your example, You can simply create ArrayAdapter and assign again to Spinner.
private void setTextForSpinner(Spinner spinner) {
String[] items = {"Stack", "Over", "Flow"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
spinner.setAdapter(adapter);
}
If apply above code to your example, you can change again to:
private void setTextForSpinner(Spinner spinner, String NewName) {
String[] items = {NewName};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
spinner.setAdapter(adapter);
}
Hope this help :)
Good day, I have one question, I always need refresh names in spinner, when I get in main_activity and I don't know how can I make it. Here is the piece of code, which I need repeat everytime when I get in main_activity:
arrTblNames = new ArrayList<String>();
Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name!='android_metadata'", null);
if (c.moveToFirst()) {
while ( !c.isAfterLast() ) {
arrTblNames.add( c.getString( c.getColumnIndex("name")) );
c.moveToNext();
}
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, arrTblNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(
new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
selectedtable = spinner.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
}
);