NullPointerException while using adapter.getItem(position) - android

I have the following code in WeekDays.java
ArrayAdapter<TaskInAWeek> adapter1 = (ArrayAdapter<TaskInAWeek>) getListAdapter() ;
TaskInAWeek taski;
ArrayList<Long> checkedItms = new ArrayList<Long>();
ArrayList<Long> uncheckedItms = new ArrayList<Long>();
for(int i=0;i<values.size();i++)
{
Log.i("value's size:" +values.size()," ");
if(EditStatusAdapter.tog==1)
{
Log.i("i::"+i," ");
taski = adapter1.getItem(i);
long id = taski.getId();
Log.i("nid:"+id," ");
checkedItms.add(id);
}
else
{
Log.i("i::"+i," ");
taski = adapter1.getItem(i);
long id = taski.getId();
Log.i("nid:"+id," ");
uncheckedItms.add(id);
}
}
Its custom Array Adapter is EditStatusAdapter.java. I get a NullPointerException at this pttaski = adapter1.getItem(i);.
I have used similar one in one of my activity but it did work fine. I guess its due to the custom array adapter. But I could not ignore it as well. Can anyone tel me how to clear the exception?

Related

How to compare two different lists and get the difference of both list?

I have two different lists, one is List<MainCategoriesAPI.Datum> datumList = new ArrayList<>(); and second is List<SubCategoryEnt> subCategoryEnts1 = new ArrayList<>();.
What I want is to compare these two lists and get those ids which are not present in datumList. And then, I want to delete the data regarding these ids from SubCategoryEnt.
If you are targeting above Android N
List<String> a1 = Arrays.asList("2009-05-18", "2009-05-19", "2009-05-21");
List<String> a2 = Arrays.asList("2009-05-18", "2009-05-18", "2009-05-19", "2009-05-19", "2009-05-20", "2009-05-21","2009-05-21", "2009-05-22");
List<String> result = a2.stream().filter(elem -> !a1.contains(elem)).collect(Collectors.toList());
or you can use the Collection interface's removeAll method.
// Create a couple ArrayList objects and populate them
// with some delicious fruits.
Collection firstList = new ArrayList() {{
add("apple");
add("orange");
}};
Collection secondList = new ArrayList() {{
add("apple");
add("orange");
add("banana");
add("strawberry");
}};
// Show the "before" lists
System.out.println("First List: " + firstList);
System.out.println("Second List: " + secondList);
// Remove all elements in firstList from secondList
secondList.removeAll(firstList);
// Show the "after" list
System.out.println("Result: " + secondList);
You have to use for loop to find the similar ids and the again use for loop to remove ids from datumList;
List<MainCategoriesAPI.Datum> datumList = new ArrayList<>();
List<SubCategoryEnt> subCategoryEnts1 = new ArrayList<>();
List<Integer> results = new ArrayList<Integer>();// this is for storing same ids
To get different ids
// to get same ids
if (datumList.size() == subCategoryEnts1.size()) {
for (int i=0; i<datumList.size();i++){
int datIds = datumList.get(i);
for (int j=0; j<subCategoryEnts1.size();j++){
int subId = subCategoryEnts1.get(j);
if (datIds!=subId){
results.add(subId);
break;
}
}
}
}
to remove ids
// to remove same id
for (int i=0; i<results.size();i++){
int datIds = results.get(i);
for (int j=0; j<datumList.size();j++){
int subId = datumList.get(j);
if (datIds==subId){
datumList.remove(j);
break;
}
}
}
Hope this will help you.
Check below to find missing items of subCategoryEnts1
List missingIds = new ArrayList<SubCategoryEnt>();
for (SubCategoryEnt subCategory : subCategoryEnts1) {
for (MainCategoriesAPI.Datum datam : datumList) {
if (datam.id == subCategory.id){
missingIds.add(subCategory);
break;
}
}
}
Now remove those from subCategoryEnts1
subCategoryEnts1.removeAll(missingIds);

How to get items from Listadapter in android?

I have a Listadapter wherein there are 4 different strings, and storing them to my listview. Now I want to get all the items from one of those strings and parse it to "date", so how can I able to populate my calendar dates from my listadapter?
Following the codes:
// Get User records from SQLite DB
ArrayList<HashMap<String, String>> eventsList = controller.getAllevents();
// If users exists in SQLite DB
if (eventsList.size() != 0) {
// Set the User Array list in ListView
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);
myList.setAdapter(adapter);
String eventstart = adapter.toString(); //I got null exception here..
Date edate = ParseDate(eventstart);
if (caldroidFragment != null) {
caldroidFragment.setBackgroundResourceForDate(R.color.Green, edate);
caldroidFragment.refreshView();
}
}
If you want to fetch an item from your adapter you can use
adapter.getItem(position);
which will return the item at the specified position. In your case, that method will return the HashMap<String, String> at the specified position:
Example:
/* adapter.getCount() returns the count of how many items
(HashMaps, in your case) that is represented in this adapter. */
for(int i = 0; i < adapter.getCount(); i++){
HashMap<String, String> myHashMap = adapter.getItem(i);
//"myKey" is the key that you provided, when mapping your key-values
String myVal = myHashMap.get("myKey");
Date edate = ParseDate(myVal);
/* Handle your Date object here. I'm just printing it to the console
in this example. */
System.out.println("Item at position " + i + " " + edate.toString());
}
Problem solved! Just simply put inside the loop and change the 'position' variable into the variable that handles the loop e.g for (int i = 0; i < eventsList.size(); i++) change adapter.getItem(position) to adapter.getItem(i)

Show data with hidden ID with android

I have JSONArray with several JSONObjects and each JSONObject contains Name and ID. How can I show only the name and leave the ID hidden. I need to be able to get the ID afterwards by knowing which row was pressed. I don't care how to show it, with list view, table, grid or whatever. This is how I get the data from the JSONArray:
for (int i = 0; i < ans.length(); i++) {
int id = Integer.parseInt(ans.getJSONObject(i).getString("UserID"));
String disName = ans.getJSONObject(i).getString("DisplayName");
adapter.add(disName + " - " + id);
}
Thank you in advance
After the first answer I created a Class name DisNameID containing diaplyName and ID and the toString is return displayName. The listView on this activity is called "frndLst". This is the code that should fill the listview:
ListView lstFrnd = (ListView) findViewById(R.id.frndLst);
ArrayList<String> listItems = new ArrayList<String>();
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this, android.R.layout.XXX, listItems);
for (int i = 0; i < ans.length(); i++) {
int id = integer.parseInt(ans.getJSONObject(i).getString("UserID"));
String disName = ans.getJSONObject(i).getString("DisplayName");
DisNameID dis = new DisNameID(disName, id);
adapter.add(disName + " - " + id);
}
Now I have 2 new questions: How to change the adapter to hold my new class - DisNameID? What to write instead of the XXX on the new adapter constructor?
Create Holder object, override toString:
class Holder {
private String name;
private String id;
//getters and setters;
public String toString(){ return name };
}
Then add such objects to your adapter. This way, the name will be displayed, but you can get Holder objects from your adapter using this method and use the id.

BaseAdapter not getting refreshed after data set is changed: Android

I am using a list adapter and feeding a list to it, which is made from a TreeMap.
Treemap is required as I need that the data for the list comes from three places and I need to collect it all and then have it sorted basing on a time stamp.
Now, when the new data comes in, the adapter doesn't update, even when I call notifyDataSetChanged().
I have attached my code below:
LinkedList<DeviceDataInfo> tsDataList = response
.getDeviceDataInfoList();
for (DeviceDataInfo data : tsDataList) {
// if (data.getAttrValue().equals("14")){
String eventMsg = null;
if (data.getAttrValue() != null) {
eventMsg = getEventMessage(
Float.valueOf(data.getAttrValue()),
data.getAttrName());
if (eventMsg != null) {
long time = data.getTime();
String eventDate = mCurrentDoorSensor
.getFormattedDate(time);
String eventTime = mCurrentDoorSensor
.getFormattedTime(time);
SensorListModel item = new SensorListModel(eventTime,
eventDate, eventMsg);
if (!mDoorSensorHistory.containsKey(time)) {
// add item to the tree
mDoorSensorHistory.put(time, item);
}
}
}
}
SensorListModel[] list = new SensorListModel[mDoorSensorHistory
.size()];
list = mDoorSensorHistory.values().toArray(list);
mList = new ArrayList<SensorListModel>(Arrays.asList(list));
mSensorProgressBar.setVisibility(View.GONE);
mSensorProgressBarText.setVisibility(View.GONE);
if (isAdded()) {
if (mSensorAdaptor == null) {
mSensorAdaptor = new SensorListAdaptor(getActivity(),
mList, "DOOR");
mSensorList.setAdapter(mSensorAdaptor);
} else {
// mSensorAdaptor = new SensorListAdaptor(getActivity(),
// mList, "DOOR");
((BaseAdapter) mSensorList.getAdapter())
.notifyDataSetChanged();
}
}
Could someone, please, let me know what is going wrong?
Thanks
For future reference: This solved it
#Sunny : try mSensorAdaptor.addAll(list);mSensorAdaptor.notifyDataSetChanged(); if addAll method is not available then you will need to define addAll method in SensorListAdaptor which all two ArrayLists – ρяσѕρєя K 15 mins ago

Why does my SparseArray return an ArrayList with zero elements?

I'm iterating through a cursor and populating a SparseArray with ArrayList's containing bundles of information from the cursor:
// An ArrayList to hold all of our components per section
ArrayList<ObjectKanjiLookupChar> al = new ArrayList<ObjectKanjiLookupChar>();
// We'll hold on to all of the above ArrayLists and process them at once
SparseArray<ArrayList<ObjectKanjiLookupChar>> compArray = new SparseArray<ArrayList<ObjectKanjiLookupChar>>();
do
{
// Read values from the cursor
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String component = cursor.getString(cursor.getColumnIndex("component"));
int compStrokes = cursor.getInt(cursor.getColumnIndex("strokes"));
// Create a new object for this component so we can display it in the GridView via an adapter
ObjectKanjiLookupChar oklc = new ObjectKanjiLookupChar();
oklc.setCharacterID(id);
oklc.setCharacter(component);
oklc.setStrokeCount(compStrokes);
al.add(oklc);
// Add headers whenever we change stroke groups
if(compStrokes != strokesSection)
{
compArray.put(strokesSection, al);
al.clear();
strokesSection = compStrokes;
}
}
while(cursor.moveToNext());
// Add the final group of components to the array
compArray.put(strokesSection, al);
Immediately afterwards, I iterate through the SparseArray:
for(int i = 0; i < compArray.size(); i++)
{
Integer strokes = compArray.keyAt(i);
ArrayList<ObjectKanjiLookupChar> alComp = compArray.get(strokes);
// DEBUG
Log.i("DialogKanjiLookup", "Components in Section " + strokes + ": " + alComp.size());
ll.addView(createNewSection(String.valueOf(strokes), alComp));
}
For some unknown reason, the Log() call above reports that alComp has zero entries. I verified that ArrayList.size() was returning numbers greater than 0 when I put() them into the SparseArray, so I must be doing something incorrect when iterating through the SparseArray. What is going on?
I suspect that the problem comes from this piece of code:
if(compStrokes != strokesSection)
{
compArray.put(strokesSection, al);
al.clear(); // Here
strokesSection = compStrokes;
}
You cleared the array list after you added to the SparseArray. You might think that after you have added the list to the SparseArray, SparseArray would keep a copy of the ArrayList. However, they actually share the same reference. Since you cleared the ArrayList, you cleared out the one inside SparseArray too.
The following code should fix the problem.
// We'll hold on to all of the above ArrayLists and process them at once
SparseArray<ArrayList<ObjectKanjiLookupChar>> compArray = new SparseArray<ArrayList<ObjectKanjiLookupChar>>();
do
{
// Read values from the cursor
int id = cursor.getInt(cursor.getColumnIndex("_id"));
String component = cursor.getString(cursor.getColumnIndex("component"));
int compStrokes = cursor.getInt(cursor.getColumnIndex("strokes"));
// Create a new object for this component so we can display it in the GridView via an adapter
ObjectKanjiLookupChar oklc = new ObjectKanjiLookupChar();
oklc.setCharacterID(id);
oklc.setCharacter(component);
oklc.setStrokeCount(compStrokes);
ArrayList<ObjectKanjiLookupChar> al = compArray.get(comStrokes);
if(al == null) {
al = new ArrayList<ObjectKanjiLookupChar>();
compArray.put(comStrokes, al);
}
al.add(oklc);
}
while(cursor.moveToNext());

Categories

Resources