Android ListView Subitems - java

I recently created a new ListView object for an Android application, but I am encountering some errors. When I try using a Simple Adapter to create an Item that includes a subitem on my list, The newest item created overlaps the other ones. I am using a List of Maps to create the items.
For example, If I add an item to my map list that displays "1" with a subitem that displays "A1", the item and subitems will be displayed. But if I add an new item to my map list named "2" with a subitem "B2", the "1" and "A1" will be replaced with "2" and "B2". There will still be 2 items on the ListView, but one of them is empty and the other one is "2" and "B2"
Here is my code:
List<Map<String, String>> data = new ArrayList<Map<String, String>>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView)findViewById(R.id.listView1);
Map<String, String> datum = new HashMap<String, String>();
datum.put("RouterName", "Test1");
datum.put("RouterIP", "SubTest1");
data.add(datum);
Map<String, String> datum2 = new HashMap<String, String>();
datum.put("RouterName", "Test2");
datum.put("RouterIP", "SubTest2");
data.add(datum2);
SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] {"RouterName", "RouterIP"}, new int[] {android.R.id.text1, android.R.id.text2});
lv.setAdapter(adapter);
}
Changing the list type will not work because the Simple Adapter specifically uses a Map List.

Hi I found some minor mistakes while storing in Hashmap. In that HashMap object is not creating. Previous instance is getting deleted.
Kindly use the below code. Hope it will help you.
ArrayList<HashMap<String, String>> data;
private String[] titleArray,subItemArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
ListView lv = (ListView)findViewById(R.id.listview);
data = new ArrayList<HashMap<String, String>>();
titleArray=new String[]{"Test1","Test2"};
subItemArray=new String[]{"SubTest1","SubTest2"};
for(int i=0;i<titleArray.length;i++){
HashMap<String,String> datum = new HashMap<String, String>();
datum.put("RouterName", titleArray[i]);
datum.put("RouterIP", subItemArray[i]);
data.add(datum);
}
SimpleAdapter adapter = new SimpleAdapter(this, data, android.R.layout.simple_list_item_2, new String[] {"RouterName", "RouterIP"}, new int[] {android.R.id.text1, android.R.id.text2});
lv.setAdapter(adapter);
}

Related

Application crashing when click on any item in ListView

I am a beginner in Android studio and I am having hard time to debug this issue.
when any item in my ListView gets clicked the application crashes, here is the class for the OnItemClick. The objective is to change the ListView from the Categories to the items inside the categories. The Categories and items are stored in a HashMap <String, String[]>, so passing the value of cat.toString() should return the string containing the category. Lastly using myList (Stored outside of the function) should return an array of string containing the items. However, when I click any of the items the application instantly crashes. Thanks for your help!
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Choosen category
TextView cat = (TextView) view;
ArrayList<String> tempItems = new ArrayList<String>();
//Toast.makeText(this, cat.getText().toString(),Toast.LENGTH_SHORT).show();
listAdapter.clear();
for(String val : myList.get(cat.getText().toString())){
tempItems.add(val);
}
listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,tempItems);
listAdapter.notifyDataSetChanged();
}
Variables
ListView myViewList;
Map<String, String[]> myList = new HashMap<String, String[]>();
ArrayAdapter<String> listAdapter;
Populating the ListView
//Creating a list of all categories
Set<String> myListKeys = myList.keySet();
ArrayList<String> categories = new ArrayList<String>();
for(String val : myListKeys){
categories.add(val);
}
//String[] categories = myListKeys.toArray(new String[myListKeys.size()]);
//Populating list
myViewList = (ListView) findViewById(R.id.groceryList);
listAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,categories);
myViewList.setAdapter(listAdapter);
myViewList.setOnItemClickListener(this);
You are getting exception because you are using listAdapter.clear(); which tries to clear the List inside the adapter. But apparently you have passed an array (String[] categories) which cannot be cleared. You should convert the array to ArrayList, (not just List) by iterating through it and pass it into the adapter.
You should create the adapter by passing ArrayList
What do you think you're doing by creating a new adapter inside the onItemClick of old adapter?
Inside the onItemClick, don't create a new adapter. Instead, after clearing the adapter and creating a temp ArrayList, add all the temp ArrayList to the adapter.
listAdapter.addAll(tempItems);
Also to get text from a TextView, use cat.getText().toString(); instead of cat.toString();

simple adapter cant update database

Hey guys i have made a listview of data from my database using simple adapter but i dont know how to update it everytime the database changes.Any help?The notifyDataSetChanged(); method doesnt work and i cant find out what to do.
MainActivity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_general_discussion);
db = new SQLiteHandler(this);
ArrayList<HashMap<String, String>> emaillist = db.getMessage();
if (emaillist.size() != 0) {
ListAdapter adapter = new SimpleAdapter(MainActivity.this, emaillist,
R.layout.raw_layout,
new String[]{"user_posted", "post", "posted_at", "post_id"}, new int[]{
R.id.text_user_name, R.id.text_user_post, R.id.text_user_date, R.id.text_user_number});
setListAdapter(adapter);
}
HelperClass
public ArrayList<HashMap<String, String>> getMessage(){
ArrayList<HashMap<String, String>> message = new ArrayList<HashMap<String, String>>();
String selectQuery = "SELECT * FROM " + TABLE_POSTING;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if ( cursor.moveToFirst()) {
do {
HashMap<String, String> map = new HashMap<String, String>();
map.put("post_id", cursor.getString(0));
map.put("user_posted", cursor.getString(1));
map.put("post", cursor.getString(2));
map.put("posted_at", cursor.getString(3));
message.add(map);
} while (cursor.moveToNext());
}
return message;
}
Declare your adapter & list global level
class example{
ListAdapter adapter;
ArrayList<HashMap<String, String>> emaillist;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_general_discussion);
db = new SQLiteHandler(this);
emaillist = db.getMessage();
if (emaillist.size() != 0) {
adapter = new SimpleAdapter(MainActivity.this, emaillist,
R.layout.raw_layout,
new String[]{"user_posted", "post", "posted_at", "post_id"}, new int[]{
R.id.text_user_name, R.id.text_user_post, R.id.text_user_date, R.id.text_user_number});
setListAdapter(adapter);
}
When you want to update just
adapter.notifyDataSetChanged();
Declare your adapter as Public and just call
adapter.notifyDatasetChange();
when ever wherever you want to. This would update.
Hope this helps.
i don't think there is a direct way to check if something changed in database
but you can make an action like Refresh.
make your adapter as global, when the action is triggered fill the adapter again and write adapter.notifyDatasetChange();
another way is to use Thread, put it into inner class of type AsyncTask
then refill the array every minute
then write adapter.notifyDatasetChange(); after every check like this
doInBackground(){
while(true){
checkDataBase();
refillAdapter();
adapter.notifyDatasetChange();
Thread.sleep(1000*60);// sec * 60 sec =1min
}
}
look at this link how to use AsyncTask class http://developer.android.com/reference/android/os/AsyncTask.html

Spinner subitem

I want to populate a Spinner with items which have a main text and a sub text, just like Android Studio shows when building the view on the "Designer" tab.
So far I was able to fill it with the main text only.
I am doing it via code. Using a SimpleAdapter.
I tried the following but with no success, it just gives me same result (only main text):
Spinner spinner = (Spinner) findViewById(R.id.mySpinner);
List<Map<String, String>> itens = new ArrayList<>();
Map<String, String> item = new HashMap<>(2);
item.put("text", "MAIN TEXT");
item.put("subText", "SUB TEXT");
itens.add(item);
SimpleAdapter adapter = new SimpleAdapter(spinner.getContext(), itens,
android.R.layout.simple_spinner_dropdown_item,
new String[]{"text", "subText"},
new int[]{android.R.id.text1, android.R.id.text2}
);
// i am not sure what this does
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
I had the same problem and have used the OP's code as a base to create this solution:
final Spinner spinner = (Spinner)fragmentView.findViewById(R.id.spinner);
List<Map<String, String>> items = new ArrayList<Map<String, String>>();
Map<String, String> item0 = new HashMap<String, String>(2);
item0.put("text", "Browse aisles...");
item0.put("subText", "(Upgrade required)");
items.add(item0);
Map<String, String> item1 = new HashMap<String, String>(2);
item1.put("text", "Option 1");
item1.put("subText", "(sub text 1)");
items.add(item1);
Map<String, String> item2 = new HashMap<String, String>(2);
item2.put("text", "Option 2");
item2.put("subText", "(sub text 2)");
items.add(item2);
SimpleAdapter adapter = new SimpleAdapter(getActivity(), items,
android.R.layout.simple_spinner_item, // This is the layout that will be used for the standard/static part of the spinner. (You can use android.R.layout.simple_list_item_2 if you want the subText to also be shown here.)
new String[] {"text", "subText"},
new int[] {android.R.id.text1, android.R.id.text2}
);
// This sets the layout that will be used when the dropdown views are shown. I'm using android.R.layout.simple_list_item_2 so the subtext will also be shown.
adapter.setDropDownViewResource(android.R.layout.simple_list_item_2);
spinner.setAdapter(adapter);
You can also substitute android.R.layout.simple_spinner_item and/or android.R.layout.simple_list_item_2 with your own custom views (that would typically reside in your layout folder).
This is a much better solution than PhoneGap!! :D
You will have to create a custom ArrayAdapter that creates a custom view for your Spinner dropdown. This link gives a good example: How to customize the Spinner dropdown view

Add spinner to HashMap Android

I have a ListView, and the list view is populated with an HashMap. I can add text without in issue. I have an issue adding spinners.
How would I go about adding spinners to a HashMap in Android?
Here is the code for my HashMap:
final Spinner hashSpinner = (Spinner)findViewById(R.id.spinner1);
ArrayAdapter<String> array = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, array);
hashSpinner.setAdapter(hashSpinner);
mapTwo = new HashMap<String, String>();
mapTwo.put("zero", "OK");
mapTwo.put("one", " 2");
mapTwo.put("two", " 3");
listTwo.add(mapTwo);
try {
adapter = new SimpleAdapter(this, listOne, R.layout.row_two,
new String[] { "zero", "one", "two" }, new int[] {
R.id.spinner1, R.id.spinner2, R.id.spinner3 });
listViewOne.setAdapter(adapter);
} catch (Exception e) {
}
row_two already contains the spinners, the issue is, I can't get it to display. How will I go about adding the spinners to the ListView?

Why does my ListView not display the list of items?

I am trying to display my list of alarms in the ListActivity but it does not work. There rows appear but there is no text visible. I'm not sure if it's retrieving the data from the HashMap and inserting into the rows correctly.
Here is my code:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_list);
List<Alarm> list;
Database db = new Database(AlarmListActivity.this);
list = db.getAllAlarms();
List<HashMap<String, String>> alarmMap = new ArrayList<HashMap<String, String>>();
for (Alarm alarm: list) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(Integer.toString(alarm.getID()), alarm.toString());
alarmMap.add(map);
}
if(!list.isEmpty() && list != null)
{
System.out.println("inside list");
System.out.println(list);
ListAdapter adapter = new SimpleAdapter(
AlarmListActivity.this,
alarmMap,
R.layout.list_item,
new String[] { "id", "hour"},
new int[] { R.id.id, R.id.time});
setListAdapter(adapter);
}
else
{
Toast.makeText(AlarmListActivity.this, "No Alarms Set",
Toast.LENGTH_SHORT).show();
}
}
This is what I get. You can vaguely see the lines of each row. But there is no text or anything. All the System.out.println() work as expected which print out the HashMap. It's just nothing is being displayed in the list. I've even added: android:text="Testing" to no avail

Categories

Resources