I've been having this error where this class(DataProvider) for my project that I just created will not seem to accept .add or .put. But my MainActivity class accepts them just fine. I’ve already done the Invalidate Caches and Restart. Can someone explain to me why this is happening and what I can do to fix it?
DataProvider:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DataProvider {
public static HashMap<String, List<String>> getInfo()
HashMap<String, List<String>> MoviesDetails = new HashMap<String, List<String>>();
List<String> Action_Movies = new ArrayList<String>();
//'.add' would be an error in red. Cannot resolve symbol 'add'.
Action_Movies.add("");
List<String> Romantic_Movies = new ArrayList<String>();
Romantic_Movies.add("");
List<String> Horror_Movies = new ArrayList<String>();
Horror_Movies.add("");
List<String> Comedy_Movies = new ArrayList<String>();
Comedy_Movies.add("");
}
MainActivity:
import android.app.Activity;
import android.os.Bundle;
import android.widget.ExpandableListView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends Activity {
HashMap<String, List<String>> Movies_categories;
List<String> Movies_list;
ExpandableListView Exp_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<String> Test = new ArrayList<String>();
Test.add("Test");
}
}
You are missing a semicolon at the end of this line:
public static HashMap<String, List<String>> getInfo()
Which makes the code analysed go crazy and not see your objects correctly as their types. Just add the semicolon.
Also, you will probably want to remove the parenthesis at the end of the line, as it suggests it it a method. So do something like this:
public static HashMap<String, List<String>> getInfo;
Or this:
public static HashMap<String, List<String>> getInfo(){
//Some actual code here, which returns a HashMap
};
Now I see that your whole class tructure is messed up. Try the below code:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class DataProvider {
public static HashMap<String, List<String>> getInfo;
public DataProvider() {
HashMap<String, List<String>> MoviesDetails = new HashMap<String, List<String>>();
List<String> Action_Movies = new ArrayList<String>();
Action_Movies.add("");
List<String> Romantic_Movies = new ArrayList<String>();
Romantic_Movies.add("");
List<String> Horror_Movies = new ArrayList<String>();
Horror_Movies.add("");
List<String> Comedy_Movies = new ArrayList<String>();
Comedy_Movies.add("");
}
}
On another side note, consider creating your variables outside of the constructor and initializing them inside the constructor.
public class DataProvider {
public static HashMap<String, List<String>> getInfo;
HashMap<String, List<String>> movieDetails;
List<String> actionMovies;
List<String> romanticMovies;
List<String> horrorMovies;
List<String> comedyMovies;
public DataProvider() {
movieDetails = new HashMap<String, List<String>>();
actionMovies = new ArrayList<String>();
actionMovies.add("");
romanticMovies = new ArrayList<String>();
romanticMovies.add("");
horrorMovies = new ArrayList<String>();
horrorMovies.add("");
comedyMovies = new ArrayList<String>();
comedyMovies.add("");
}
}
These lines may have been added inside the class but outside the constructor or method. Make sure the instructions are within a method.
Related
I want to store some data in string format and again retrive object from that string using gson in android.
My storing function is
public void storeData(HashMap<String, List<String>> data) {
String d = new Gson().toJson(data);
storeToXYZ(d);
}
Getting data function
public HashMap<String, List<String>> getData() {
String d = getFromXYZ();
// Assume not default data present
if(!d.equals("")) {
Type type = new TypeToken<HashMap<String, List<String>>>(){}.getType();
return new Gson().fromJson(d, type);
}
return null;
}
I am getting error at this line in getData() function
return new Gson().fromJson(d, type);
Stacktrace
java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to java.util.HashMap
Thanks in advance.
Try to change HashMap to Map:
Type type = new TypeToken<Map<String, List<String>>>(){}.getType();
Details:
From LinkedTreeMap.java:
LinkedTreeMap<K, V> extends AbstractMap<K, V>
The AbstractMap inherits from Map interface and not from HashMap
What do I have in my project:
1) private HashMap<String, File> imagesMap;<br>
2) sharedPreferencesEditor.putString(IMAGES_MAP_KEY, new Gson().toJson(imagesMap)).apply();<br>
3) imagesMap = new Gson().fromJson(imagesMapString, new TypeToken<HashMap<String, File>>(){}.getType());
It works well.
BTW, I use
compile 'com.google.code.gson:gson:2.8.1'
in dependencies.
Please check gson version, also please ensure, that you transfer exactly HashMap into storeData().
Okay, let's try another way:
I created new project, added gson in dependencies. And here is code of MainActivity:
package com.example.eugenegoltsev.hashmaptest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private HashMap<String, List<String>> data;
private String jsonString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initData();
storeData(data);
HashMap<String, List<String>> data2 = getData();
}
private void initData() {
data = new HashMap<>();
List<String> list1 = new ArrayList<>();
list1.add("l1 one");
list1.add("l1 two");
list1.add("l1 three");
List<String> list2 = new ArrayList<>();
list2.add("l2 one");
list2.add("l2 two");
list2.add("l2 three");
data.put("First", list1);
data.put("Second", list2);
}
public void storeData(HashMap<String, List<String>> data) {
jsonString = new Gson().toJson(data);
}
public HashMap<String, List<String>> getData() {
Type type = new TypeToken<HashMap<String, List<String>>>(){}.getType();
return new Gson().fromJson(jsonString, type);
}
}
getData() works well, just like it should.
So your problem is somewhere in other place.
You can create test HashMap, like in my code and test with it.
I have a hashMap with the following declaration:
Map<String, Integer> terms = new HashMap<>();
and a List as follow:
List<String> allTerms = new ArrayList<>();
The hashMap and the List contain Strings.
I want to remove all Strings stored in the hashMap not listed in the declared List.
What is the better way to do that?
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Test {
static boolean match = true;
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<String, Integer>();
Map<String, Integer> map1 = new HashMap<String, Integer>();
List<String> list = Arrays.asList("Test1", "Test2", "Test3", "Test4", "Test5", "Test6", "Test7");
map.put("Test1", 1);
map.put("Test66", 2);
map.put("Test3", 3);
map.put("Test4", 4);
map.put("Test123", 5);
map.forEach((k, v) -> {
match = false;
list.forEach(s -> {
if (k.equals(s))
match = true;
});
if(match)
map1.put(k,v);
});
map = map1;
map.forEach((k,v)->System.out.println(k));
}
}
Output:
Test1
Test4
Test3
I have the below java class
public class DataStruc {
private List<String> TradeRef;
private List<String> TMS;
public DataStruc(List<String> TradeRef, List<String> TMS) {
setTradeRef(TradeRef);
setTMS(TMS);
}
//setters and getters for them
}
I have the below map which is as shown below and into which i am explicitly creating the list
Map<String, DataStruc> newdatamap = new HashMap<String, DataStruc>();
List<String> B1TradeRef = Arrays.asList("TradRefr", "tr1");
List<String> B1TMS = Arrays.asList("TS", "TMSW");
List<String> B2TradeRef = Arrays.asList("TradRefrtsy", "tr1ty");
List<String> B2TMS = Arrays.asList("TWES", "TUYTMSW");
newdatamap.put("B1", new DataStruc (B1TradeRef,B1TMS));
newdatamap.put("B2", new DataStruc (B2TradeRef,B2TMS));
below is the output of the above program as shown below
output :-
*******
B1 = com.asd.ert.DataStruc#1394894
B2 = com.asd.ert.DataStruc#1394894
Now I want to retrieve the value of above HashMap named newdatamap as I want to store it like this format in another map named finalmap.Please advise how to achieve this?
lets say my finalmap declartion is like
Map<String , String> finalmap = new HashMap<String , String>();
so if newdatamap.keyset is equal to B1 then following should be stored in finalmap.Please advise how to achieve this
TradRefr TradeRef
tr1 TradeRef //class member name declartions
TS TMS
TMSW TMS //class member name declartions
Try this:
Map<String , String> finalmap = newdatamap.values().stream()
.flatMap(d -> Stream.concat(
d.getTradeRef().stream().map(s -> new SimpleEntry<>(s, "TradeRef")),
d.getTMS().stream().map(s -> new SimpleEntry<>(s, "TMS"))))
.collect(Collectors.toMap(e -> e.getKey(), e -> e.getValue()));
System.out.println(finalmap);
// -> {TUYTMSW=TMS, tr1=TradeRef, TradRefrtsy=TradeRef, TWES=TMS, TradRefr=TradeRef, TMSW=TMS, TS=TMS, tr1ty=TradeRef}
class SimpleEntry is an public inner class of java.util.AbstractMap.
TMSW TMS //class member name declartions
So you want to extract field names here of class DataStruc. There is only one way to do that in java, which is using reflection API.
Your DataStruc class
import java.util.List;
public class DataStruc {
private List<String> TradeRef;
private List<String> TMS;
public DataStruc(List<String> TradeRef, List<String> TMS) {
this.TradeRef = TradeRef;
this.TMS = TMS;
} // setters and getters for them
}
Calling class.
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MainClass {
public static void main(String[] args) throws IllegalArgumentException,
IllegalAccessException {
Map<String, DataStruc> newdatamap = new HashMap<String, DataStruc>();
List<String> B1TradeRef = Arrays.asList("TradRefr", "tr1");
List<String> B1TMS = Arrays.asList("TS", "TMSW");
List<String> B2TradeRef = Arrays.asList("TradRefrtsy", "tr1ty");
List<String> B2TMS = Arrays.asList("TWES", "TUYTMSW");
newdatamap.put("B1", new DataStruc(B1TradeRef, B1TMS));
newdatamap.put("B2", new DataStruc(B2TradeRef, B2TMS));
Map<String, String> finalmap = new HashMap<String, String>();
// loop through current map
for (Map.Entry<String, DataStruc> entry : newdatamap.entrySet()) {
String key = entry.getKey();
DataStruc dataStruc = entry.getValue();
// get all the fields of object dataStruc
for (Field field : dataStruc.getClass().getDeclaredFields()) {
field.setAccessible(true);
String fieldName = field.getName();
// check if field is List<String>
if (field.get(dataStruc) instanceof List) {
List<String> fieldValue = (List<String>) field.get(dataStruc);
// if yes then add the List entries to your final map with
// current field name
for (String str : fieldValue) {
finalmap.put(str, fieldName);
}
}
}
}
for (Map.Entry<String, String> entry : finalmap.entrySet())
System.out.println(entry.getKey() + "-" + entry.getValue());
}
}
Output after running Main class
TUYTMSW-TMS
tr1-TradeRef
TradRefrtsy-TradeRef
TWES-TMS
TradRefr-TradeRef
TMSW-TMS
tr1ty-TradeRef
TS-TMS
I have 1 object(Goods) have 2 attributes: String and boolean. How to input object Goods to ArrayList<HashMap<String, Object>> ? Because I want input ArrayList<HashMap<String, Object>> to SimpleAdapter
public class Goods {
private String goodsName;
private boolean isCheck = false;
public String getGoodsName() {
return goodsName;
}
public void setGoodsName(String goodsName) {
this.goodsName = goodsName;
}
public boolean isCheck() {
return isCheck;
}
public void setCheck(boolean isCheck) {
this.isCheck = isCheck;
}
}
package ngo;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Goods g = new Goods();
g.setGoodsName("foo");
g.setCheck(true);
Map<String, Goods> map = new HashMap<String, Goods>();
map.put(g.getGoodsName(), g);
List<Map<String, Goods>> list = new ArrayList<Map<String, Goods>>();
list.add(map);
System.out.println(list.get(0).get("foo").isCheck());
}
}
Displays true
This should be an acceptable, if simple, structure for the data parameter of SimpleAdapter's constructor. A more exhaustive example of it's use can be found here
The following is the basic example, not runnable in itself.
ArrayList<HashMap<String, Goods>> listOfMappedGoods = new ArrayList<HashMap<String, Goods>>();
HashMap<String, Goods> goodsList = new HashMap<String, Goods>();
Goods g = new Goods();
g.setGoodsName("foo");
g.setCheck(true);
goodsList.add(g.getGoodsName(), g);
listOfMappedGoods.add(goodsList);
The point to note, is that just like every new Goods object needs to be created using new Goods(), each new goodsList needs to be created also using new HashMap<String, Goods>().
If you use something like goodsList.clear(), then you are still referring to the original map that was first added to the listOfMappedGoods, so you will clear that instead.
package com.assignment;
import java.util.ArrayList;
import java.util.HashMap;
public class Interview {
private HashMap<String,Integer> stateCounts = null;
private HashMap<String,String> stateNames;
private ArrayList<InputData> inputList = null;
public void loadStateNames(String stateKey,String stateName)
{
stateNames.put(stateKey, stateName);
}
public static void main(String Args[])
{
Interview interview = new Interview();
interview.loadStateNames("NY", "New York");
}
}
When I try to pass to strings to loadStateNames. I get a null pointer exception. Can't figure out whats causing this error.
Exception in thread "main" java.lang.NullPointerException
at com.assignment.Interview.loadStateNames(Interview.java:41)
at com.assignment.Interview.main(Interview.java:57)
You have not initialised the Map ,change it to ::
private HashMap<String,String> stateNames = new HashMap<String,String>();
You forgot to initialize your HashMap, change:
private HashMap<String,String> stateNames;
to:
private HashMap<String,String> stateNames = new HashMap<String,String>();
You are not initializing them. You should do this in the constructor:
public Inteview() {
stateNames = new HashMap<>();
}
Also, I doubt you want to give a null reference to stateCounts and inputList. They should also be initialized in the constructor:
public Inteview() {
stateNames = new HashMap<>();
stateCounts = new HasMap<>();
inputList = new ArrayList<>();
}
When you declare a class variable like this:
private HashMap<String,String> stateNames;
or like this:
private HashMap<String,String> stateNames = null;
it is initialized with null.
You cannot add keys/values to it when it is null.
Either initialize it in a constructor or at declaration time.
private HashMap<String,String> stateNames = new HashMap<String,String>()
You should create an instance:
private HashMap<String,String> stateNames = new HashMap<String, String>();
And for others too. BTW use interface in left side for polymorphism and in Java 7+ you don't need provide types in right side:
private Map<String,String> stateNames = new HashMap<>();