Android ListView Adapter shows only last element - android

I have a little problem with getting all data from SQLite database and showing them in ListView. The code I'm using is showing only the last item. Here is the code which I'm using :
ListView lv1 = (ListView) findViewById(R.id.saved_codes_listview);
SystemDatabaseHelper systemDbHelper = new SystemDatabaseHelper(this, null, 1);
systemDbHelper.initialize(this);
String sqlQuery = "SELECT code_id, code_string FROM saved_codes";
Cursor cursor = systemDbHelper.executeSQLQuery(sqlQuery);
if(cursor.getCount()==0){
Log.i("No Saved Codes","There is no Saved Codes.");
} else if(cursor.getCount()>0){
for(cursor.move(0); cursor.moveToNext(); cursor.isAfterLast()){
String codeString = cursor.getString(cursor.getColumnIndex("code_string"));
ArrayList<String> codes = new ArrayList<String>();
codes.add(codeString);
Log.i("Code String","Code String : "+codeString);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, codes);
lv1.setAdapter(adapter);
}
}
I have 3 entries in my database as an example : shosho, bosho, gosho and as a result I have only gosho in my listview. Any idea how to fix that?
Thanks in advance!

Change your code so that you initialize array list before for loop, and also set ArrayAdapter AFTER the loop.
ArrayList<String> codes = new ArrayList<String>();
for(cursor.move(0); cursor.moveToNext(); cursor.isAfterLast()){
String codeString = cursor.getString(cursor.getColumnIndex("code_string"));
codes.add(codeString);
Log.i("Code String","Code String : "+codeString);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, codes);
lv1.setAdapter(adapter);

Like this:
ArrayList<String> codes = new ArrayList<String>();
for(cursor.move(0); cursor.moveToNext(); cursor.isAfterLast()){
String codeString = cursor.getString(cursor.getColumnIndex("code_string"));
codes.add(codeString);
Log.i("Code String","Code String : "+codeString);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, codes);
lv1.setAdapter(adapter);
}
You re-create a new ArrayList<String> codes in every loop so the last loop the list containing only one element, which is the last.

Change for(cursor.move(0); cursor.moveToNext(); cursor.isAfterLast())
to for(cursor.move(0);; cursor.isAfterLast(); cursor.moveToNext())
or use
while(cursor.isAfterLast())
cursor.moveToNext();

Related

Android how to trim sharedpreferences name

I'm getting all sharedpreferences created by my app and I insert them in a spinner but every sharedpreferences displayed like "example.xml" etc. I want to trim .xml extension let them just names like "example".
File prefsdir = new File(getApplicationInfo().dataDir,"shared_prefs");
if(prefsdir.exists() && prefsdir.isDirectory()){
String[] list = prefsdir.list();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_expandable_list_item_1, android.R.id.text1,list);
Spinner sp = (Spinner) findViewById(R.id.tum_ilaclar);
sp.setAdapter(adapter);
}
You can use something like this create a new method:
String[] getList(String[] list){
String values[] = new String[list.length];
for(int i=0; i<list.length; i++){
String value = list[i];
values[i]=value.contains(".xml")?value.replace(".xml",""):value;
}
return values;
}
Then in your code change :
String[] list = prefsdir.list();
to
String[] list = getList(prefsdir.list());
This will remove the .xml part.

How to add a default selected value in android dropdown

I have a dropdown which takes its values from a database, I then want to add a default value to the existing drop down values. In this case the default value would be the selected value.
StringBuilder strbuilder = new StringBuilder();
ArrayList<String> arr_list = new ArrayList<String>();
List<String> m = new ArrayList<String>();
//This get the data values from database
m = db.getData();
int ms = m.size();
String str = strbuilder.toString();
String[] str1 = str.split(",");
try {
if (ms > 1) {
//This is my default value
m.add("Default Value");
for (int i = 0; i < ms; i++) {
m.get(0);
}
} else {
m.get(0);
}
} catch (Exception e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item, m);
dropdown.setAdapter(adapter);
The codes above is able to add the values from the database to the dropdown and the Default Value is added but it doesn't appear to be the selected value.
For instance if the values from the database are "Apple, Mango,Pineapple" and the default value is "ALL FRUITS".
EXPECTED DROPDOWN
ALL FRUITS
Apple
Mango
Pineapple
Please how can I do make the default value the selected value? Thanks in advance.
I think you need below code.
List<String> categories = new ArrayList<String>();
categories = db.getData();
categories.add(0,"your_default_value");
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);
spinner.setSelection(0);
Remember when you want to add any value to the very first of Arraylist you just do
arraylist.add(0,"value");
This will add the value to the very first index of arraylist and push all other element down.
In case you need any other element to be selected not first one
Spinner spinner = (Spinner) findViewById(R.id.spinner);
List<String> categories = new ArrayList<String>();
categories.add("Automobile");
categories.add("Business Services");
categories.add("Computers");
categories.add("Education");
categories.add("Personal");
categories.add("Travel");
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);
int i=categories.indexOf("Education");
spinner.setSelection(i);
If the default value is always going to be at the 0 index, just get a reference to your dropdown/spinner, then set:
spinner.setSelection(0);
And here is a previously answered question detailing how to set it by value, if you'd rather do that.
https://stackoverflow.com/a/4228121/3299157

Items from ListView to SQLite, SQLite to ListView

I'm trying to get all the items on my listview (I've attached some image uri) and put them in the database, then get them again and load them on the listview.
What I did is: String hex = array_list.toString(); and put that hex string in the database (sqlite).
FirstFragment:
ListView lv;
ArrayList<Uri> array_list = new ArrayList<Uri>();
ArrayAdapter<Uri> array_adapter;
OnCreate..
array_adapter = new ArrayAdapter<Uri>(getActivity(), android.R.layout.simple_list_item_1, array_list);
lv = (ListView) v.findViewById(R.id.list);
lv.setAdapter(array_adapter);
OnClick..
String hex = array_list.toString();
HashMap<String, String> rcfData = new HashMap<String, String>();
rcfData.put("dateTime", hex);
DataHolder dataHolder = new DataHolder(getActivity());
dataHolder.insertData(rcfData);
Here are the items before I put them in sqlite: (Before clicking OnClick)
SecondFragment:
ListView lv2;
ArrayList<Uri> array_list2 = new ArrayList<Uri>();
ArrayAdapter<Uri> array_adapter2;
OnCreate...
array_adapter2 = new ArrayAdapter<Uri>(getActivity(), android.R.layout.simple_list_item_1, array_list2);
lv2 = (ListView) v.findViewById(R.id.list2);
lv2.setAdapter(array_adapter2);
OnClick...
Intent intent = getActivity().getIntent();
String rcfDataId = intent.getStringExtra("unique_id");
DataHolder dataHolder = new DataHolder(getActivity());
HashMap<String, String> rcfData = dataHolder.get_rcfData(rcfDataId);
if(rcfData.size() !=0) {
String s = rcfData.get("dateTime");
Uri hello = Uri.parse(s);
array_list2.add(hello);
array_adapter2.notifyDataSetChanged();
}
The problem is, when I try to load that string from sqlite to listview of the SecondFragment, it became like this: (After clicking OnClick of SecondFragment)
What I want it to be like (after clicking OnClick of SecondFragment), is like this:
How can I load it like that?
I don't know DataHolder, and I don't know whether it's really backed by an sqlite DB, but this feels like a misuse - you'd probably want to insert each of your items from your ListView as a separate row to your table.
However, if you just want a quick workaround to make it work, you could just split the string you're reading, e.g:
if(rcfData.size() !=0) {
String s = rcfData.get("dateTime");
// Remove brackets
s = s.substring(1, s.length() - 1);
// Split string and insert to ListView
for(String sPart : s.split(", ")) {
Uri hello = Uri.parse(sPart);
array_list2.add(hello);
}
array_adapter2.notifyDataSetChanged();
}

How to add subitems in a ListView

I'm trying to add subItems in my ListView.
My listView should be organized with emails for items and their institution for the subitems, but with the following code I just added items, how can I add my subitems on it? I've tried so many things but it doesn't work.
List<Login> listEmails = JsonUtil.getAllEmails(json);
ArrayList<String> emails = new ArrayList<String>();
ArrayList<String> institutions = new ArrayList<String>();
for (Login loginObj : listEmails) {
emails.add(loginObj.getEmailAndress());
}
for (Login loginObj : listEmails) {
institutions.add(loginObj.getInstitution());
}
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, emails);
emailListView.setAdapter(adapter);
You need a custom adapter with two textviews and in its getView() method set the appropriate data to each of your textviews.
Also by now you are passing to your adapter only the emails array, you'll need a different structure to include institutions too.
The right way to do that is to create a HashMap for each item: Look the code below:
List<Login> listEmails = JsonUtil.getAllEmails(json);
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>(listEmails.size());
for (Login loginObj : listEmails) {
HashMap<String, String> item = new HashMap<String, String>();
item.put("email", loginObj.getEmailAndress());
item.put("institution", loginObj.getInstitution());
list.add(item);
}
String[] from = new String[] { "email", "institution" };
int[] to = new int[] { android.R.id.text1, android.R.id.text2 };
int nativeLayout = android.R.layout.two_line_list_item;
emailListView.setAdapter(new SimpleAdapter(this, list, nativeLayout , from, to));

Converting values of SQL Database into a String Array

I need to create a drop down list (spinner) in eclipse for Android whereby the drop down options can be created by the user.
To do this I've created a SQLiteDatabase, which I want to convert into a string array to be put into an array adapter, which can then be fed into the spinner.
Database details are:
DATABASE_NAME = "carddb"
DATABASE_TABLE = "cardtable"
Then the column I wish to read the values from is:
KEY_CARDDETAILS = "_carddetails";
Here is my code so far, adapted from another question on this site (Link: how to get the database value to a String array in android(sqlite Database))
myDB = cardtable.this.openOrCreateDatabase("carddb", MODE_PRIVATE, null);
Cursor cardcursor = cardDB.rawQuery("SELECT * FROM cardtable");
String[] cardstringarray = new String[cardcursor.getCount()];
cardcursor.moveToFirst();
int counter = 0;
while(cardcursor.moveToNext()){
String carddetailss = cardcursor.getString(cardcursor.getColumnIndex("NAME"));
cardstringarray[counter] = carddetailss;
counter++;
}
I'm getting an error under "myDB" and "cardtable", both errors saying they cannot be resolved into a variable!
PLEASE HELP!
Use this code
String[] displayName={};
ArrayList<String> List=new ArrayList<String>();
myDB = cardtable.this.openOrCreateDatabase("carddb", MODE_PRIVATE, null); Cursor cardcursor = cardDB.rawQuery("SELECT * FROM cardtable");
String[] cardstringarray = new String[cardcursor.getCount()];
cardcursor.moveToFirst();
int counter = 0;
while(cardcursor.moveToNext()){
String carddetailss = cardcursor.getString(cardcursor.getColumnIndex("NAME"));
List.add(carddetailss);
counter++;
}
if(List != null){
listEmail=(ListView)findViewById(R.id.listEmail);
listEmail.setVisibility(view.VISIBLE);
displayName=(String[])List.toArray(new String[0]);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, displayName);
// Assign adapter to ListView
listEmail.setAdapter(adapter);
}
This is work for you. Use spinner instead of listView.

Categories

Resources