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));
Related
Is there any possible way to add items in listview using setAdapter which only contains specific items? for example I want to add in listview an items which contains a date of "Feb. 15, 2015" only.
Following the codes:
final ListAdapter adapter = new SimpleAdapter(CalendarActivity.this, eventsList, R.layout.calendar_event_list, new String[]{TAG_PID,
TAG_EVENTTITLE,TAG_EVENTSTART,TAG_EVENTEND},
new int[]{R.id.pid, R.id.eventname, R.id.eventstart, R.id.eventend});
ListView myList = (ListView) findViewById(android.R.id.list);
SimpleDateFormat formatdate = new SimpleDateFormat("MMM. dd, yyyy");
String selecdate = formatdate.format(date);
if (eventDates.contains(selecdate)) {
myList.setAdapter(adapter); //these line I want only to add items in listview which contains the value of 'selectdate'
}
else {
myList.setAdapter(null);
}
SimpleAdapter is used for static data. Since you want to dynamically filter the data you should implement a custom adapter to do this. However, a cheap solution would be to filter the data before you setup the adapter. Like this:
ListView myList = (ListView) findViewById(android.R.id.list);
SimpleDateFormat formatdate = new SimpleDateFormat("MMM. dd, yyyy");
String selecdate = formatdate.format(date);
// Filter selected events
List<Map<String, Object>> filteredEventsList = new ArrayList<Map<String, Object>>();
for (Map<STring, Object> row : eventsList) {
if (row should be shown) {
filteredEventsList.add(row);
}
}
final ListAdapter adapter = new SimpleAdapter(CalendarActivity.this, filteredEventsList, R.layout.calendar_event_list, new String[]{TAG_PID,
TAG_EVENTTITLE,TAG_EVENTSTART,TAG_EVENTEND},
new int[]{R.id.pid, R.id.eventname, R.id.eventstart, R.id.eventend});
myList.setAdapter(adapter);
I have a RadioButton in a list view I am fetching the data from server and assigning to the ListView but in the list view there is a RadioButton How can I assign check in RadioButton.
Code:
for(int i=0;i<..........)
{
HashMap<String, String> map = new HashMap<String, String>();
map.put(ID,(((Node) node_list_variables.getDoc_id().item(0)).getNodeValue()));
map.put(ANSWER, (((Node) node_list_variables.getAnswer().item(0)).getNodeValue()));
map.put(QUESTION_ID, (((Node) node_list_variables.getQuestion_id().item(0)).getNodeValue()));
map.put(DESCRIPTION, i+1+", "+(((Node) node_list_variables.getQuestion().item(0)).getNodeValue()));
menuItems.add(map);
}
// Adding menuItems to ListView
// All filed data are not shown in the list KEY_ID is hidden
ListAdapter adapter = new SimpleAdapter(this, menuItems,R.layout.certification_question_item,
new String[] { DESCRIPTION, QUESTION_ID, ANSWER, ID },
new int[] {R.id.questionText, R.id.question_id, R.id.answer });
setListAdapter(adapter);
R.id.answer is my radio buttonGroup Id
Why don't you just use an ArrayAdapter instead?
View layout = inflater.inflate(R.layout.whatever_you_called_your_layout_file, (ViewGroup)findViewById(R.id.whatever_you_called_your_layout_if_its_not_already_inflated));
ListView theList = (ListView)layout.findViewById(R.id.whatever_you_called_the_listview);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, android.R.id.text1, theNameOfTheStringArrayContainingYourValues);
theList.setAdapter(adapter);
theList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
theList.setItemChecked(checkedItem, true);
Just make sure you have set the int checkedItem to the value of the index in your String[] for the item you want checked.
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();
I am feeding a ListView from a database in this way (nothing special), except
COL_TXT_TRANSL2 contains html formatting:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle extras = getIntent().getExtras();
mCurrBookID = extras.getString("BookID");
mCurrChapterNum = extras.getString("ChapterNum");
mCurrChapterTitle = extras.getString("ChapterTitle");
mGitaDB= Central.mDB;
this.setTitle(mCurrChapterNum+"."+mCurrChapterTitle);
setContentView(R.layout.chapterdisplay);
//set chapter intro
TextView tvIntro=(TextView) findViewById(R.id.textIntro);
tvIntro.setText(Html.fromHtml(extras.getString("ChapterIntro")));
try {
String[] columns = new String[] { mGitaDB.COL_TXT_TEXT_NUM, mGitaDB.COL_TXT_TRANSL2 };
int[] to = new int[] { R.id.number_entry, R.id.title_entry };
mCursor=mGitaDB.GetGitaTexts(mCurrBookID, mCurrChapterNum);
mAdapter = new SimpleCursorAdapter(this,
R.layout.textslist_row, mCursor, columns, to);
setListAdapter(mAdapter);
}
catch (Exception e) {
String err="Error: " + e.getMessage();
Toast toast = Toast.makeText(Central.context, err, 15000);
toast.show();
}
}
Now the problem is that the text displayed in this ListView has HTML formatting.
How can I make listview display this HTML formatting? Currently it is displayed as a plain text with all tags.
Assuming the HTML is fairly simple you can run it through this method: http://developer.android.com/reference/android/text/Html.html#fromHtml(java.lang.String) The resulting Spannable can be sent to a TextView in the ListView. Beware the fromHtml method is very slow and may slow down scrolling, you might want to cache the Spannables.
Define a CharSequence ArrayList, include all the elements from your database to be displayed in this arraylist as HTML. Include a personal TextView layout for the individual entities of the listView, and display the Charsequence in the list. I had made use of the following code for my app:
List<CharSequence> styledItems = new ArrayList<CharSequence>();
droidDB.open();
articles = droidDB.getAllArticleTitles(feed.feedId);
droidDB.close();
for (Article article : articles) {
styledItems.add(Html.fromHtml(article.title));
}
ArrayAdapter<CharSequence> notes =
new ArrayAdapter<CharSequence>(this, R.layout.feeds_row,styledItems);
setListAdapter(notes);
For the feeds_row.xml:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#FFFFFF"/>
Hope this helps.
My problem was similar to yours. I was reading data from file in json format, where I have objects with id and text fields. text field is html. I have resolved problem this way:
ArrayList<MyObject> myObjectsList = new ArrayList<MyObject>();
ArrayList<HashMap<String, CharSequence>> tableElements = new ArrayList<HashMap<String, CharSequence>>();
String keyword = in.getStringExtra(TAG_KEYWORD);
InputStream is = this.getResources().openRawResource(R.raw.data);
JSONParser jParser = new JSONParser();
myObjectsList = jParser.searchForObjects(is, keyword);
for (MyObject element : myObjectsList)
{
String id = Integer.toString(element.id);
CharSequence text = Html.fromHtml(element.text);
// creating new HashMap
HashMap<String, CharSequence> map = new HashMap<String, CharSequence>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEXT, text);
// adding HashList to ArrayList
tableElements.add(map);
}
ListAdapter adapter = new SimpleAdapter(this,tableElements,
R.layout.search_item,
new String[] { TAG_ID, TAG_TEXT.toString()}, new int[] {
R.id.exercise_id, R.id.text });
setListAdapter(adapter);
I want to set color for particular row in listview.That row will know at runtime. I ahve done list view like this :
ArrayList<SalesRoutes> routeList = getSalesRoute();
ArrayList<HashMap<String, String>> routhPath = new ArrayList<HashMap<String, String>>();
for (int i = 0; i < routeList.size(); i++) {
if(Integer.parseInt(routeList.get(i).getOutlets()) >0){
HashMap<String, String> map = new HashMap<String, String>();
map.put("routeCode",((SalesRoutes) routeList.get(i)).getRouteCode());
map.put("routeName",((SalesRoutes) routeList.get(i)).getDescription());
map.put("outlets", ((SalesRoutes) routeList.get(i)).getOutlets());
routhPath.add(map);
}
}
ListView list = getListView();
sd = new SimpleAdapter(this, routhPath, R.layout.route_path,new String[] {"routeCode","routeName","outlets" },new int[] { R.id.routeCode,R.id.routeName,R.id.outlets});
row = getLayoutInflater().inflate(R.layout.route_path_row, null, false);
getListView().addHeaderView(row);
list.setAdapter(sd);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
list.setSelected(true);
//list.setSelection(0);
list.setTextFilterEnabled(true);
list.setItemsCanFocus(true);
list.setItemChecked(positions, true);
list.setSelectionAfterHeaderView();
Please tell me how can i do this...
Thanks in advance
One way is to use the index of the row you want to get like
getListView().getChildAt(index).setBackground(#ff0000);
Otherwise you would need to create a custom adapter and overwrite the getView method which is called before rendering each row. You can use that to check any conditions and set the background accordingly.
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/
The above is a tutorial about that.