Array List Null Pointer Exception - Android - java

I am trying to create an application which retrieves the users favourite book quote however I am stuck on how to display this information back to the user. I created an ArrayList which will store all the information. However when displaying this information, I keep getting the error:
java.lang.NullPointerException
when it tries to execute the code
temp[i] = new HashMap<String,String>();
This class is shown below:
public class FavouriteQuotesActivity extends ListActivity {
static final ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
private void getFavorites() {
DataBaseHelper myDbHelper = new DataBaseHelper(this);
String favorites [] = myDbHelper.getFavourites();
if(list.size() > 0)
{
list.removeAll(list);
}
for(int i = 0;i < favorites.length; i++)
{
String quotes = favorites[i];
String[] quoteArray = quotes.split(":");
HashMap<String,String> temp[] = null;
temp[i] = new HashMap<String,String>();
temp[i].put("Author",(quoteArray[2]));
temp[i].put("Quote",(quoteArray[4]));
list.add(temp[i]);
}
}
Any help would be greatly appreciated.

Look at this code:
HashMap<String,String> temp[] = null;
temp[i] = new HashMap<String,String>();
You've just assigned a null value to the temp variable (which would more typically have a declaration of HashMap<String, String>[] temp) - so of course you'll get a NullPointerException when you then try to access temp[i] on the very next statement.
It's not clear why you're using an array at all in that code - why aren't you just using:
HashMap<String, String> map = new HashMap<String, String>();
map.put("Author", quoteArray[2]);
map.put("Quote", quoteArray[4]);
list.add(map);
Additionally it's unclear why you're using a map at all here, given that it will always have the same two keys. Why not create a Quote class with name and author properties? Also, using a static variable here seems like a bad idea - why doesn't getFavorites create a new list on each invocation, and return it at the end of the method?

You are declaring and using temp wrong. You don't need an array of HashMap, just a single HashMap, since list is an ArrayList<HashMap>:
HashMap<String,String> temp = new HashMap<String,String>();
temp.put("Author",(quoteArray[2]));
temp.put("Quote",(quoteArray[4]));
list.add(temp);

temp doesn't point to an array. You are setting it to null.
You declared the variable temp as an array (by writing HashMap temp[]).
Without being it an actual array, you can't set any elements.

Related

For loop of Hashmap to ArrayList is not holding the correct values. How to fix?

I have the following code which surprisingly doesn't work;
needsInfoView = (ListView) findViewById(R.id.needsInfo);
needsInfoList = new ArrayList<>();
HashMap<String, String> needsInfoHashMap = new HashMap<>();
for (int i = 0; i < 11; i++) {
needsInfoHashMap.put("TA", needsTitleArray[i]);
needsInfoHashMap.put("IA", needsInfoArray[i]);
Log.e("NIMH",needsInfoHashMap.toString());
//Here, I get the perfect output - TA's value, then IA's value
needsInfoList.add(needsInfoHashMap);
Log.e("NIL",needsInfoList.toString());
//This is a mess - TA, IA values for 12 entries are all the same, they are the LAST entries of needsTitleArray and needsInfoArray on each ArrayList item.
needsInfoAdapter = new SimpleAdapter(getBaseContext(), needsInfoList,
R.layout.needsinfocontent, new String[]{ "TA", "IA"},
new int[]{R.id.ta, R.id.ia});
needsInfoView.setVerticalScrollBarEnabled(true);
needsInfoView.setAdapter(needsInfoAdapter);
}
Please see the comment below the log lines. That explains the output I receive. How do I make the ArrayList values pass to the two text fields in my ListView via the SimpleAdapter?
Thank you
For loop of Hashmap to ArrayList is not holding the correct values
Because your are adding same instance HashMap in your needsInfoList
You need to add new instance HashMap in your needsInfoList list like below code
Also you need to set your needsInfoAdapter to your needsInfoView listview outside the loop like below code
Try this
needsInfoList = new ArrayList<>();
needsInfoView = (ListView) findViewById(R.id.needsInfo);
for (int i = 0; i < 11; i++) {
HashMap<String, String> needsInfoHashMap = new HashMap<>();
needsInfoHashMap.put("TA", needsTitleArray[i]);
needsInfoHashMap.put("IA", needsInfoArray[i]);
needsInfoList.add(needsInfoHashMap);
}
needsInfoAdapter = new SimpleAdapter(getBaseContext(), needsInfoList,
R.layout.needsinfocontent, new String[]{"TA", "IA"},
new int[]{R.id.ta, R.id.ia});
needsInfoView.setVerticalScrollBarEnabled(true);
needsInfoView.setAdapter(needsInfoAdapter);
You are adding the same HashMap instance multiple times to the List, which means the entries you put in the Map on each iteration replace the entries put by the previous iteration.
You should create a new HashMap instance on each iteration:
for (int i = 0; i < 11; i++) {
HashMap<String, String> needsInfoHashMap = new HashMap<>();
needsInfoHashMap.put("TA", needsTitleArray[i]);
needsInfoHashMap.put("IA", needsInfoArray[i]);
needsInfoList.add(needsInfoHashMap);
....
}

TreeMap using a string key and an arraylist

I am brand new to using collections, so I am confused on how to do this. I am trying to use a TreeMap to hold a word as the key and then an ArrayList to hold one or more definitions for the word.
public class Dict {
Map<String, ArrayList<String>> dic = new TreeMap<String, ArrayList<String>>();
public void AddCmd(String word, String def) {
System.out.println("Add Cmd " + word);
if(dic.get(word)==null){
dic.put(word, new ArrayList.add(def));
}
}
}
I am getting an error on "new ArrayList.add(def)". I thought this was the correct way to do this, but I am obviously wrong. Does anyone have any ideas as to what I am doing wrong?
Calling ArrayList#add returns a boolean which is not the desired value for your Map, thus getting the compiler error.
You need to insert the ArrayList and then add the element. Your code should look like this:
ArrayList<String> definitions = dic.get(word);
if (definitions == null) {
definitions = new ArrayList<String>();
dic.put(word, definitions);
}
definitions.add(def);
dic.put(word, new ArrayList.add(def)); is the culprit.
since you have declared map to take Arraylist of string as a value. the value to pass for map must be Arraylist of string.
but this line is adding a value as new ArrayList.add(def) since you are trying to create a list and adding element , add method returns boolean -> true if it can add false if it fails.
so it means value to the map is going as a boolean not as arraylist which is against the map declaration.
so use code as below
ArrayList<String> listOfString = dic.get(word);
if (listOfString == null) {
listOfString = new ArrayList<String>();
listOfString .add(def);
}
dic.put(word, listOfString );
You have to break it up, because add does not return the original ArrayList:
ArrayList<String>> NewList = new ArrayList<String>();
NewList.add(def);
dic.put(word, NewList);
You are not actually creating a new ArrayList. Try this:
ArrayList<String> newDef = new ArrayList<String();
newDef.add(def);
dic.put(word, newDef);

LinkedHashMap with ArrayList - How to load ArrayList?

I am fairly new to Java and am trying to load a LinkedHashMap that contains an ArrayList of values. I am trying to load the values from a query result from an API based query result (Salesforce).
Here is the error: "Cannot refer to a non-final variable breakdown inside an inner class defined in a different method" - the breakdown variable is underlined in red giving this message, Ive noted the line in concern below.
CODE
public LinkedHashMap<String, ArrayList<String>> sfFundIdsByContact;
public ArrayList<String> getFundsIDsForContact(Contact aContact)
{
QueryResult queryResults = null;
ArrayList<String> ids = new ArrayList<String>();
int index = 0;
Boolean done = false;
String contactid = aContact.getId();
String SCCPBId = null;
if(sfFundIdsByContact == null || sfFundIdsByContact.size() <= 0){
//Do the Salesforce API CALL and Return the results
...
while (! done)
{
SObject[] records = queryResults.getRecords();
for ( int i = 0; i < records.length; ++i )
{
if(sfFundIdsByContact.containsKey(breakdown.getSalesConnect__Contact__c())){
sfFundIdsByContact.get(breakdown.getSalesConnect__Contact__c()).add(breakdown.getId());
} else {
//Line below in the add(breakdown.getId() - contains the error
sfFundIdsByContact.put(breakdown.getSalesConnect__Contact__c(), new ArrayList<String>() {{ add(breakdown.getId()); }});
}
}
All suggestions are appreciated.
In your else block, instead of:
new ArrayList<String>() {{ add(**breakdown.getId()**); }}
you can use:
new ArrayList<String>(Arrays.asList(breakdown.getId())
or, since you just want a single element ArrayList, you can use Collections.singletonList that avoids the creation of temporary varargs array:
new ArrayList<String>(Collections.singletonList(breakdown.getId())
The { ... } after the new ArrayList<>() creates an anonymous subclass of ArrayList, which is an inner class only. Inside an inner class you cannot access non-final local variables.
You can ease the code by always retrieving the List value in the for loop, then if it is null create a new one and add it to your Map, otherwise add the value to the list.
for (int i = 0; i < records.length; i++) {
List<String> value = sfFundIdsByContact.get(breakdown.getSalesConnect__Contact__c());
if (value == null) {
value = new ArrayList<String>();
sfFundIdsByContact.put(breakdown.getSalesConnect__Contact__c(), value);
}
value.add(breakdown.getId());
}
As a recommendation, change the definition of
LinkedHashMap<String, ArrayList<String>> sfFundIdsByContact
to
Map<String, List<String>> sfFundIdsByContact
Refer to What does it mean to "program to an interface"?

Dynamically creating objects using a for loop

I'm relatively new to Java and trying to create an application to help with my trading. I have a method to read a csv file that I input, which is table with x number of rows and 3 columns. It reads it as multidimensional String array (String[][]) Eg
Pair----- Buy Price ---Sell Price
AUDUSD 0.9550 --- 0.9386
EURUSD 1.3333 --- 1.3050
GBPUSD 1.5705 --- 1.5550
(please excuse my formatting)
I have a constructor called ForexPair that looks like this:
public class ForexPair extends PriceWarning{
public String pairName;
public double buyPrice;
public double sellPrice;
public ForexPair(String pair, String buy, String sell) {
pairName = pair;
buyPrice = Double.valueOf(buy);
sellPrice = Double.valueOf(sell);
}
My question is this: Can I use a 'for' loop to create an object for each row in my CSV file? I believe I can use an ArrayList for this. However I want the name of each object I create to be the Pair Name in the first column of my csv file. For example:
ForexPair AUDUSD = new ForexPair(pairNames[0], (myArray[0][1]),(myArray[0][2]));
But how do I create the object called AUDUSD using a for loop? So that each object has a different name?
Currently I have this code:
public static void main(String[] args) {
String[][] myArray = getInputArray();
String[] pairNames = new String[myArray.length];
for(int i = 0; i < pairNames.length; i++){
pairNames[i] = myArray[i][0]; //Creates 1D String array with pair names.
ForexPair pairNames[i] = new ForexPair(pairNames[i], (myArray[i][1]),(myArray[i][2]));
}
}
Variable names are not relevant - they aren't even kept track of after your code is compiled. If you want to map names to objects you can instead place ForexPair instances in a Map<String, ForexPair>, i.e.
Map<String, ForexPair> map = new HashMap<String, ForexPair>();
...
// in the for-loop:
map.put(pairNames[i], new ForexPair(pairNames[i], myArray[i][1],myArray[i][2]));
Although this seems slightly redundant, as you already have the name as a field in each ForexPair, so you might want to consider removing this field and keeping track of the name only via the map.
Yes you can. Use a HashMap.
rough example:
HashMap<String, ForexPair> myMap = new HashMap<String, ForexPair>();
myMap.put("AUDUSD", new ForexPair(pairNames[0], (myArray[0][1]),(myArray[0][2])));
ForexPair pair = myMap.get("AUDUSD");
1.
Can I use a 'for' loop to create an object for each row in my CSV file?
Yes, that's possible:
BufferedReader br = new BufferedReader(new FileReader(yourCsvFile));
String line;
while((line = br.readLine()) != null) {
// do something with line.
}
2.
But how do I create the object called AUDUSD using a for loop? So that each object has a different name?
I think your mixing up two different concepts: name of variable and value of your variable called pair
The value of your variable is the important point, while the name of your variable only provides code quality!
final TableLayout tview = (TableLayout) findViewById(R.id.tblGridStructure);
final JSONArray JarraymenuItems = {item1,it3m1mwer,wer,ds};//your list of items
for (int i = 0; i < JarraymenuItems.length(); i++)
{
ableRow tr = new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tview.addView(tr, LayoutParams.FILL_PARENT, 45);
T
final TextView etprice = new TextView(this);
etprice.setText("your text value wat u want to display");
tr.addView(etprice );
int count = tview.getChildCount();
if (count % 2 != 0)
tr.setBackgroundColor(Color.parseColor("#E3E3E3"));
}

Java hashmap from python dict command?

I have a weird problem that I don't fully understand how to solve. Could someone please give me some pointers on hashmaps?
I have a variable:
/servlet/charting?base_color=grey&chart_width=288&chart_height=160&chart_type=png&chart_style=manufund_pie&3DSet=true&chart_size=small&leg_on=left&static_xvalues=10.21,12.12,43.12,12.10,&static_labels=blue,red,green,purple"
I basically want 10.21,12.12,43.12,12.10 to be associated with blue,red,green,purple (in the order displayed)
In python I created a method that does this with:
def stripChart(name):
name = str(name)
name = urlparse.urlparse(name)
name = cgi.parse_qs(name.query)
name = dict(zip( name['static_labels'][0].split(','), name['static_xvalues'][0].split(',')))
Not sure how to do this in java. So far I have:
URL imgURL = new URL (imgTag);
String[] result = imgURL.getFile().split("&");
for (int x=0; x<result.length; x++)
System.out.println(result[x]);
This gives me:
chart_width=288
chart_height=160
chart_type=png
chart_style=manufund_pie
3DSet=true
chart_size=small
leg_on=left
static_xvalues=10.21,12.12,43.12,12.10,
static_labels=blue,red,green,purple,
At this point I'm confused how to link static_labels and static_xvalues values.
Thanks so much. Any pointers would be awesome.
You want to look at StringTokenizer
Something like this (assuming you stored the labels into the String 'static_labels' and the values in the String 'static_xvalues'):
HashMap<String, Double> colorMap = new HashMap<String, Double>();
StringTokenizer labelTok = new StringTokenizer(static_labels, ",");
StringTokenizer valuesTok = new StringTokenizer(static_xvalues, ",");
while(labelTok.hasMoreElements()){
assert(valuesTok.hasMoreElements());
colorMap.put(labelTok.nextElement(), Double.parseDouble(valuesTok.nextElement()));
}
Look at using java.util.HashMap. Let's say you have stored the static_xvalues and static_labels request parameters into corresponding string variables. Something like the following will create the mapping for you:
String[] vals = static_xvalues.split(",");
String[] labels = static_labels.split(",");
HashMap<String,String> map = new HashMap<String,String>();
for (int i=0; i < vals.length; ++i) {
map.put(labels[i], values[i]);
}
You do not say if the xvalues need to be stored as floats or not. If so, you will need to convert the vals array into a Float (or Double) array first, and modify the HashMap instantiation accordingly:
HashMap<String,Float> = new HashMap<String,Float>();

Categories