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
Related
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
I'm aware that this is very simple question but I'm a newbie in Android development so please go easy on me.
Problem that I have is in one of the fragments (AsyncTask specifically) that lays in my main activity.
AsyncTask sends out data to php script which then returns according data in json format. This is then processed and saved to jsonlist array. Up until post execute everything works fine data is downloaded, processed etc. However when program reaches post execute problems start to pop out. And basically i'm unable to list out all the data from jsonlist to listview
//setting up an array
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
//creating list view variable
ListView listview;
//Define work in progress dialog
private ProgressDialog mProgressDialog;
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Please wait");
// Set progressdialog message
mProgressDialog.setMessage("Fetching data...");
mProgressDialog.setIndeterminate(false);
}
#Override
protected Boolean doInBackground(String... params) {
//To do in the background
//Define variable of JSON parser type
JSONParser jParser = new JSONParser();
//Pass url to json parser class to fetch and save it into array variable
JSONArray json = jParser.getJSONFromUrl(url);
//loop from 0 to length of an array by increasing by 1
for (int i = 0; i < json.length(); i++) {
//Try and catch routine to prevent any crashes
try {
//Get an object defined in { ... } in original json file
JSONObject c = json.getJSONObject(i);
//Separate object by obtaining values for each of the sections
String vtitle = c.getString(title);
String vcontent = c.getString(content);
String vuser = c.getString(user);
HashMap<String, String> map = new HashMap<String, String>();
//Fill up an array with data extracted
map.put(title, vtitle);
map.put(content, vcontent);
map.put(user, vuser);
//Add values into jsonlist
jsonlist.add(map);
} catch (JSONException e)
{
//In case of any error Stack trace will be returned
e.printStackTrace();
}
}
//Once everything has been done return null value
return null;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
//Insert all data downloaded through list adapter
ListAdapter adapter = new SimpleAdapter(getActivity(), jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
// Locate the listview
//listview = (ListView) findViewById(R.id.list);
// Set the adapter to the ListView
//listview.setAdapter(adapter);
//Get rid off dialog when operation of fetching data has been done
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
As you can see i have tried the commented code but listview = (ListView) findViewById(R.id.list); returns following error:
Cannot resolve method findViewById(int)
which prevents me from executing program. This is very upsetting because I literally have all the data i need in an array but only one line of code stops me from displaying it.
I have also tried:
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
setListAdapter(adapter);
lv = getListView();
But as in previous case error of unresolved method is returned. Which is due to the fact that fragment is extended by fragment and adding anything to it crashes it
public class Fragment2 extends Fragment, ListActivity {...}
Add this to your code in Fragment2 class.
private ListView listview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.YOUR_FRAGMENT_LAYOUT, container, false);
listview = (ListView) v.findViewById(R.id.R.id.list);
return v;
}
Since you are in a Fragment you have to call getView() before findViewById, like this
//Insert all data downloaded through list adapter
ListAdapter adapter = new SimpleAdapter(getActivity(), jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
// Locate the listview
listview = (ListView) getView().findViewById(R.id.list);
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);
}
I'm new to Android and I have Adapter - ListView model to display array.
I set it's value's so:
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.bank_list,
new String[] { TAG_NAME, TAG_central_office_address }, new int[] {
R.id.bank_name, R.id.central_office_address});
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, android.view.View view,
int position, long id) {
Intent in = new Intent(getApplicationContext(), BankExchangersListActivity.class);
in.putExtra("Bank_id", TAG_ID);
startActivity(in);
}
});
I get my values from JSON:
url = "http://192.168.1.4:3000/banks.json";
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
banks = json.getJSONArray(TAG_BANKS);
// looping through All Contacts
for(int i = 0; i < banks.length(); i++){
JSONObject c = banks.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String central_office_address = c.getString(TAG_central_office_address);
// Phone number is agin JSON Object
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_central_office_address, name);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
As you can see in JSON I have ID field, but i didn't set it in ListView. For next query I click on ListView element and go to other activity, but I need to get TAG_ID of this element. Maybe I did something wrong? How to get element's TAG_ID on which I click, without displaying it on ListView?
JUST send tag_id of clicked item!
The position parameter of the onItemClick method gives the index of the selected item in the adapted list. So you can find the TAG_ID of the original item at
((Map<String, String>) adapter.getItem(position)).get(TAG_ID)
make the adapter final so that you can reference it inside the listener:
final ListAdapter adapter = ...
Hope this helps you.
you can get Postion of ListSelectedItemId and passed it with Intentand get it in SecondActivity now Here get FirstActivity HashMap with define it static
now use foreachloop to get all values from HashMap like
public static void printMap(Map mp) {
Iterator it = mp.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pairs = (Map.Entry)it.next();
System.out.println(pairs.getKey() + " = " + pairs.getValue());
}
}
now with specific position of ListSelectedItemId you can get values from currentList
or like
for (Map.Entry<String, Object> entry : map.entrySet()) {
String key = entry.getKey();
Object value = entry.getValue();
// ...
}
I am adding a map to a list and then refreshing the array adapter. This was working perfectly earlier, but now that I am using an addItem() method from two different methods, it throws a NullPointer. I hope my code will clear up what I am saying:
SimpleAdapter adapter;
List<HashMap<String, String>> painItems = new ArrayList<HashMap<String, String>>();
ListView listthings;
int[] to;
String[] from;
String painLevelString, timeOfPainString, textTreatmentString,
painLocation, row1, row2, name;
OnCreate(){
if(getIntent().getStringExtra("newPainLevel")!= null){
createNewEditedEntry();
}
adapter = new SimpleAdapter(this, painItems, R.layout.mylistlayout,
from, to);
listthings.setAdapter(adapter);
}
private void createNewEditedEntry() {
String newPainLevel = this.getIntent().getStringExtra("newPainLevel");
String newPainTime =this.getIntent().getStringExtra("newPainTime");
String newTreatment =this.getIntent().getStringExtra("newTreatment");
painLevelString = newPainLevel;
timeOfPainString = newPainTime;
textTreatmentString = newTreatment;
row1 = "sample1";
row2 = "sample2";
addItem();
//painItems.remove(getIntent().getStringExtra("position"));
//adapter.notifyDataSetChanged();
}
#Override
// on the activityresult,get the string extra, then add the item to the list
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == 1) {
row1 = data.getStringExtra("com.painLogger.row1");
row2 = data.getStringExtra("com.painLogger.row2");
painLevelString = data.getStringExtra("com.painLogger.painLevel");
painLocation = data.getStringExtra("painLocation");
timeOfPainString = data.getStringExtra("com.painLogger.painTime");
textTreatmentString = data
.getStringExtra("com.painLogger.treatment");
addItem();
}
}
// to add the item, put it in the map, and add the map into the list
private void addItem() {
HashMap<String, String> map = new HashMap<String, String>();
map.put("row_1", row1);
map.put("row_2", row2);
map.put("row_3", painLevelString);
map.put("row_4", painLocation);
map.put("row_5", timeOfPainString);
map.put("row_6",textTreatmentString);
painItems.add(map);
adapter.notifyDataSetChanged(); //Null Pointer **HERE**
}
Just to be clear, createNewEditedEntry() and onActivityResult() are never called at the same time and never clash. They are two completely different occurrences. It was working with just the OnActivityResult, but now when I use CreateNewEditedEntry(), it has stopped working. I have also checked and made sure that none of the Strings that I fetch from my intent are null.
You need to initialize adapter before you call createNewEditedEntry in onCreate:
OnCreate(){
adapter = new SimpleAdapter(this, painItems, R.layout.mylistlayout, from, to);
if(getIntent().getStringExtra("newPainLevel")!= null){
createNewEditedEntry();
}
// ...
}
Otherwise, adapter will be null in addItem called from there (last line of createNewEditedEntry).
You should also be aware that your call to addItem can fail if your activity was destroyed by Android while you were in the sub-activity. Have a read of my answer to this question to understand what can happen when resources get low.