Put Hashmap into Arraylist<HashMap> - java

I'm new at android. I trying to get the data from Database and put it into HashMap. But I got a little problem here. I got an error when I try to put the data that I get.
I put a comment on the error line in my code. You can check it below
Here's my class
private static final String TAG_ITEM_NAME = "item_name";
// Hashmap for ListView
ArrayList<HashMap<String, String>> searchlist;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search);
searchlist = new ArrayList<HashMap<String, String>>();
Intent search = getIntent();
String searchResult = search.getStringExtra("TAG_SEARCH");
DatabaseHandler db = new DatabaseHandler(
List <AllItem> allItems = new ArrayList<AllItem>();
allItems = db.getAllSearchResult(searchResult);
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
for(AllItem cn : allItems) {
String item_name = cn.getItem_name();
//AllItem item_name = all_Items.put(cn.getItem_name(), cn);
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
}
searchlist.add(all_Items);
ListAdapter adapter = new SimpleAdapter(
Search.this, searchlist,
R.layout.searchlayout, new String[] {TAG_ITEM_NAME},
new int[] { R.id.category_name}
);
// Assign adapter to ListView
listview.setAdapter(adapter);
}
The error said The Method put(String, Allitem) int type Hashmap<String,Allitem> is not applicable for the argument (String, String)
How to fix this error? Thanks before :D

all_items takes a String and an AllItem, but you are placing two Strings into it in this line:
// TAG_ITEM_NAME is a String and item_name is also a String
all_Items.put(TAG_ITEM_NAME,item_name);

You try to put in the map as a value string but you map expect as a value AllItem, so you must modify your code in this way:
for(AllItem cn : allItems) {
String item_name = cn.getItem_name();
all_Items.put(item_name , cn );
}
This code will add your class object to the map with the key which equals to your object name.

all_Items is defined as a hashmap to contain <String, AllItem> key value pairs as defined here:
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
but you are trying to push <String,String> key value pair into your all_Items hashmap :
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
It seems you want to push the AllItem object against its item_name, which can be done as:
all_Items.put(item_name, cn);

Your HashMap is as follows:
HashMap<String, AllItem> all_Items = new HashMap<String, AllItem>();
This means it has String keys and AllItem values. You can put a AllItem object inside this HashMap.
When you write
all_Items.put(TAG_ITEM_NAME,item_name); // I got error here
you are putting a String inside the HashMap hence it is giving error.
You should be doing:
all_Items.put(TAG_ITEM_NAME,cn);

Your hashmap is <String, Allitem>. While you try to put <String, String> in it.
all_Items.put(TAG_ITEM_NAME, item_name);
should be changed to
all_Items.put(TAG_ITEM_NAME, cn);
Hope you got the difference.

I dont see connection in the code but using the given information, your error probably is related to your searchlist variable in your code.
change this:
ArrayList<HashMap<String, String>> searchlist;
to this:
ArrayList<HashMap<String, AllItem>> searchlist;

it's because you declared HashMap<String, AllItem> and you try to putall_Items.put(TAG_ITEM_NAME,item_name); which would probably be HashMap<String, String>().

Related

Comparing two ArrayList using Gson?

I am trying to compare two ArrayList< Map< String, Object>> objects but the problem is that I need to compare them in different app sessions. So I am saving the first ArrayList in SharedPreferences after converting it to String using Gson. Then I query the string in next session to compare it. I tried converting it back to ArrayList then comparing it with the list generated during the new session. Also tried converting the new list into json and then comparing both texts. But the result is same. Below is the relevant code:
Declaration:
ArrayList<Map<String, Object>> tweetMapArray = new ArrayList<>();
Then in some method :
List<twitter4j.Status> statuses = twitter.getUserTimeline(params[0], new Paging(1, 200));
tweetMapArray.clear(); // I am also reusing it
for (twitter4j.Status status : statuses) {
Map<String, Object> valuesToPutInMarker = new HashMap<>();
valuesToPutInMarker.put("id", status.getId());
valuesToPutInMarker.put("status", status.getText());
tweetMapArray.add(valuesToPutInMarker);
}
Now saving tweetMapArray in SharedPreferences:
String jsonStr = gson.toJson(tweetMapArray);
editor = configData.edit();
editor.putString("tweetData", jsonStr);
editor.apply();
Querying data:
private boolean seeIfTheDataIsNew() {
String dataFromSharedPreferences = configData.getString("tweetData", null);
Type collectionType2 = new TypeToken<ArrayList<Map<String, Object>>>() {
}.getType();
ArrayList<Map<String, Object>> oldTweets = gson.fromJson(dataFromSharedPreferences, collectionType2);
String jsonStr = gson.toJson(tweetMapArray);
return jsonStr.equalsIgnoreCase(dataFromSharedPreferences);
// OR
return !(oldTweets.containsAll(tweetMapArray) && tweetMapArray.containsAll(oldTweets));
}
Here, both methods in last two lines return true. In the testing sample, they should return false.

Hashmap only saving the last item

I'm getting multiple values from an ArrayList and saving them in a variable:
For each code:
static ArrayList<HashMap<String, String>> test = new ArrayList<HashMap<String, String>>();
for (RoomHandler roomHandler : roomHandlerArrayList) {
HashMap<String, String> item = new HashMap<String, String>();
item.put(ROOM_ID, Integer.toString(roomHandler.getRoomID()));
item.put(ROOM_NAME, roomHandler.getRoomName());
test.add(item);
}
And I'm calling these variables on my adapter. But when I try to print both variables, I only get the ROOM_NAME variable, when I print the ROOM_ID, I get the ROOM_NAME value, which it means that the last value is being recorded twice.
Adapter code:
String getRoomName = (String) ((Map) getItem(position))
.get(RoomsActivity.ROOM_NAME);
String getRoomID = (String) ((Map) getItem(position))
.get(RoomsActivity.ROOM_ID);
roomName.setText(getRoomName + getRoomID); //prints ROOM_NAME + ROOM_NAME
What am I doing wrong?

Custom View Layout - " List<Map> cannot be converted to List<? extends Map<String,?>> "

I have a custom list view which allows clicking on items in the list.
The code that worked well, similar to many examples on google's own site, and compiled successfully until more recent java, is this:
List<Map> myMapList = new ArrayList<Map>();
Map<String, String> myMap = new HashMap<String, String>();
private ListView myListView;
for (int i = 0; i < mydata.length(); i++) {
JSONObject t = mydata.getJSONObject(i);
myMap = new HashMap<String, String>();
myMap.put("field_1", t.getString("field_1"));
.... (more of these)
myMapList.add(myMap);
}
String[] layoutNames = new String[] { "field_1", "field_2", "field_3",
"field_4", "field_5" };
int[] layoutIDs = new int[] { R.id.field_1, R.id.field_2, R.id.field_3,
R.id.field_4, R.id.field_5};
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
(List<? extends Map<String, ?>>) myMapList, R.layout.my_list_row,
layoutNames, layoutIDs );
myListView.setAdapter(adapter);
At first, warnings were given, but now it is a compile-time error.
error: incompatible types: List<Map> cannot be converted to List<? extends Map<String,?>>
So how to I feed my String / Integer combo into List<> with the new rules?
Solution Note:
Answer Goes to Aeshang, see below. Note that this solution also gets rid of the need for the "(List>)" cast, so that line now reads:
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(),
myMapList, R.layout.my_list_row, layoutNames, layoutIDs );
Easier on the eyes, too.
You have to change this line
List<Map> myMapList = new ArrayList<Map>();
to
List<Map<String, String>> myMapList = new ArrayList<Map<String, String>>();

Not Allowing change the hashmap value after adding in arraylist

I have this arraylist and another for hashmap
ArrayList<HashMap<String, String>> agentList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> agentproperty = new HashMap<String, String>();
I have received jArray from php file. and trying to put it in the array using hashmap.
JSONArray jArray = jsonObj.getJSONArray(TAG_AGENT);
String id = null;
String name = null;
for (int i = 0; i < jArray.length(); i++) {
JSONObject a = jArray.getJSONObject(i);
id = a.getString(TAG_AGENTID);
name = a.getString(TAG_NAME);
agentproperty.put("AGENTID", id);
agentproperty.put("NAME", name);
Log.d("id",id);
Log.d("name",name);
agentList.add(agentproperty);
}
Log.d("firstperson",String.valueOf(agentList.get(0)));
Log.d("secondperson",String.valueOf(agentList.get(1)));
I can get
id 1, hame cathy; id 2, name john
for the log inside loop. But from the last log, I am getting
id 2, name john; id 2, name john
It seems the value of agentproperty is changed even after adding in arraylist.
I tried taking the agentList.add(agentproperty); outside of loop. Didnt work. Only inserts the last value (id 2, name john). Any idea how can i populate this array with all the values I get from loop. I will need to use agentList in listview.
yes it is. You have to create a new instance of the HashMap at every iteration, otherwise you will override the value for a given key, if an entry already exists
Move
HashMap<String, String> agentproperty = new HashMap<String, String>();
inside the for loop

ArrayList<HashMap<String, String>> has no values

My ArrayList<HashMap<String, String>> songslist has no values in it. In my doInBackground method i have for-loop that should fill this ArrayList. The Strings "id", "interpret"... have also values in it. Where is the problem? Here the code:
JSONArray charts = json.getJSONArray(TAG_CHARTS);
// looping through All Products
for(int i=0;i<charts.length();i++) {
JSONObject json_data = charts.getJSONObject(i);
String id = json_data.getString(TAG_ID);
String interpret = json_data.getString(TAG_INTERPRET);
String titel = json_data.getString(TAG_TITEL);
String album = json_data.getString(TAG_ALBUM);
String albumcover = json_data.getString(TAG_ALBUMCOVER);
String likes = json_data.getString(TAG_LIKES);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_INTERPRET, interpret);
map.put(TAG_TITEL, titel);
map.put(TAG_ALBUM, album);
map.put(TAG_ALBUMCOVER, albumcover);
map.put(TAG_LIKES, likes);
songslist.add(map);
}
but List is empty. The JSONArray includes the values.
The code that creates the map and puts the elements in the list is ok. So its either
1) songslist is messed up. You don't show where/how its created
2) you think charts has items in it, but it doesn't.
You're not entering into the loop. Your posted code its OK. charts.length() == 0

Categories