How to solve InvocationTargetException in for loop? (seeking entire stack trace) - java

Currently, I'm having problem with my work.
List<Map<String,String>> tmp = //blahblahblah//(for my privacy)
int size = tmp.size();
String[] linearr = new String[size];
String[] numarr= new String[size];
String[] namearr= new String[size];
String[] datearr= new String[size];
int i = 0;
for (i = 0; i < size; i++) {
linearr[i] = (String) tmp.get(i).get("line").toString();
numarr[i] = (String) tmp.get(i).get("number").toString();
namearr[i] = (String) tmp.get(i).get("name").toString();
datearr[i] = (String) tmp.get(i).get("date").toString();
}
I made a List<Map<String,String>> however when i got to for-loop. InvocationTargetException came up.
And I could not debug anymore and cannot track it
I tried the code surrounds with try and catch block with throws InvocationTargetException e
but Eclipse told me to remove it.
please help
specifically it said that invocationtargetexception.<init>(throwable) line: not available

You may find this link helpful. However, I'd like to suggest that you need to make sure that all keys are available in your map.
P.S. You don't need to use toString() and (String) cast.

You Don't want to use List ? And if you don't have the exact keys in map ,it will throw Exception . Using get or default will prevent it.
List<String> line = new ArrayList<>();
List<String> number = new ArrayList<>();
List<String> name = new ArrayList<>();
List<String> date = new ArrayList<>();
for(Map<String, String> map:tmp){
line.add(map.getOrDefault("line",""));
number.add(map.getOrDefault("number",""));
name.add(map.getOrDefault("name",""));
date.add(map.getOrDefault("date",""));
}

Related

Convert JSON String to Arraylist for Spinner

I got my JSON string from my server which contains this values:
{"server_response":[{"violation":"Driving with No Helmet"},{"violation":"Try"}]}
What I'm trying to do is convert this JSON string into String Array or Arraylist
with the values of Driving with no Helmet and Try and use it as options on an Autocomplete Textview. But I cant seem to convert them correctly. Any help or tips on what I should do? Currently I am getting the JSON String from another activity and passing it to the activity where it should be used using this:
String json_string2 = getIntent().getExtras().getString("json_data");
Anyone has time I'm willing to learn. :) Thanks
PS: Managed to get it working. #Suhafer's answer is perfect. Thanks to everyone for the warm help! :)
I think first, you need to parse the json to get the list of string that you want:
String json_string2 = getIntent().getExtras().getString("json_data");
List<String> lStringList = new ArrayList<>();
try {
JSONObject lJSONObject = new JSONObject(json_string2);
JSONArray lJSONArray = lJSONObject.getJSONArray("server_response");
for (int i = 0; i < lJSONArray.length(); i++)
{
lStringList.add(
lJSONArray.getJSONObject(i).getString("violation"));
}
}
catch(Exception e)
{
e.printStackTrace();
}
Then, you need to set that list to your adapter:
ArrayAdapter<String> yourListAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, lStringList);
Next, implement the adapter to your AutoCompleteTextView.
lAutoCompleteTextView.setAdapter(lStringArrayAdapter);
Hope, that helps you.
Reading your comment I think you want this list to populate on an AutoCompleteTextView. I have written thoroughly what to do this will surely help If you follow these steps carefully.
First get the response and convert it to List<String> list = new ArrayList<>() format, Create a ArrayAdapter of this list by
yourListAdapter = new ArrayAdapter<String>(YourActivity.this,
android.R.layout.simple_list_item_1, list);
After this set your yourAutoCompleteTextBoxName.setAdapter(yourListAdapter);
In your Activity initialize this:
yourAutoCompleteTextBoxName.setOnEditorActionList(...){...}
also if you want your list to be clicked from AutoComplete TextView then do this:
yourAutoCompleteTextBoxName.setOnItemClickListener(...){...}
You can do this as below by using jettinson.jar
try {
String data = "{\"server_response\":[{\"violation\":\"Driving with No Helmet\"},{\"violation\":\"Try\"}]}";
JSONObject jsonObject = new JSONObject(data);
JSONArray temp = jsonObject.getJSONArray("server_response");
int length = temp.length();
if (length > 0) {
String[] recipients = new String[length];
for (int i = 0; i < length; i++) {
JSONObject nObject = new JSONObject(temp.getString(i));
recipients[i] = nObject.getString("violation");
}
}
} catch (JSONException ex) {
Logger.getLogger(JavaApplication2.class.getName()).log(Level.SEVERE, null, ex);
}
For getting your list of strings:
You can use Jackson's ObjectMapper class.
public class Data {
String violation;
...
}
List<Data> violations = objectMapper.readValue(json, new TypeReference<List<Data>>(){});
Below: "array" will have all the violations. (You will require some try / catch to surround with). Have a good day!
JSONObject json = new JSONObject(json_string2);
JSONArray violations = json.getJSONArray("server_response");
String[] array = new String[violations.length()];
for(int i = 0; i < violations.length(); i++) {
JSONObject violation = new JSONObject(violations.getString(i));
array[i] = violation.getString("violation");
}
You can use Gson library https://github.com/google/gson
Generate Plain Old Java Objects from JSON or JSON-Schema http://www.jsonschema2pojo.org/
YourJsonData jsonObject;
String json_string2 = getIntent().getExtras().getString("json_data");
Gson gson = new Gson();
jsonObject = gson.fromJson(json_string2, YourJsonData.class);
from jsonObject you can get your list i.e server_response array list.

What should i use to store multiple images?

What should i use to store multiple images that i retrieve from for loop? array or list? Is there any example functions that i can use? Below is my example for loop where i get my data.
JSONObject mainObject = new JSONObject(response.toString());
JSONArray uniObject = mainObject.getJSONArray("result");
for(int i = 0; i < uniObject.length(); i++) {
JSONObject rowObject = uniObject.getJSONObject(i);
co.img1 = ipAddress +"img/store/" + rowObject.getString("store_banner");
}
Use ArrayList<>(); It's away more flexible than the normal array;

FreeMarker get variable value by concatenating another variable value

public class Main {
public static void main(String[] args) throws IOException, TemplateException{
Configuration freemarkerConfig = new Configuration();
freemarkerConfig.setClassForTemplateLoading(Main.class, "");
Template template = freemarkerConfig.getTemplate("template.ftl");
Map<String, String> data = new HashMap<String, String>();
for(int i=1;i<=10;i++){
data.put("map_"+i, "value"+i);
}
Writer out = new StringWriter();
template.process(data, out);
System.out.println(out.toString());
}
}
Here is my FTL code to access the variable:
<#assign containerIndex=1>
${map_containerIndex}
This gives error
I want to evaluate ${map_1}
You can read variables with such runtime generated names like .vars['map_' + i]. It's the same trick than tom has used in his answer, but applied for reading a top-level variable.
Instead of trying to create a variable (which I don't think is possible that way) I'd suggest providing an array to the template.
Like so
String[] stringArray = new String[11];
for (int i = 1; i<= 10; i++) {
stringArray[i] = "value"+i;
}
data.put("map", stringArray);
Access in Freemarker should look like
<#assign containerIndex=1>
${map[containerIndex]}
or something like that, can't try it out atm
Also note, that by starting the for-loop with 1 (as in your example) the first array-slot won't be used.
I'd suggest
String[] stringArray = new String[10];
for (int i = 0; i < 10; i++) {
stringArray[i] = "value"+i;
}

put/add is replacing all entires in a map or list

I am trying to convert a map: Map<String, Map<String, Map<String, Map<String, String>>>>to a Map<String, Settings>.
The Settings class contains all the possible map keys and will be set to true when looping through this particular key.
The problem is when in the deepest map, when adding to a global Map<String, Settings>, the Settings will be replaved with the last Settings for every entry.
Can someone help me find out where i do wrong?
public void loop(Map map, Settings settings){
List keys = new ArrayList(map.keySet());
if(map.get(keys.get(0)) instanceof Map){
//is a map, so continue loop + add to vorm
for(int i = 0; i < keys.size(); i++){
Settings tmp = settings;
String field = keys.get(i).toString();
Method method = null;
try {
//Set some booleans for key
method = tmp.getClass().getMethod(field, boolean.class);
method.invoke(tmp, true);
loop((Map) map.get(keys.get(i).toString()), tmp);
} catch (Exception e) {
e.printStackTrace();
}
}else{
for(int i = 0; i < keys.size(); i++) {
Settings tmp = settings;
String key = keys.get(i).toString();
String word = map.get(key).toString();
tmp.setWord(word);
Settings input = tmp;
settingsList.add(convert, input);//put into 2 arraylists
keyList.add(convert, woord);
convert++;
//vormen.put(word, tmp);//put into list
}
}
}
This method is called here:
public void convert(){
vormen = new HashMap();
settingsList = new ArrayList<>();
wordList = new ArrayList<>();
if(jsonMap.isEmpty()){
throw new NullPointerException("You are trying to convert a null map");
}else {
loop(jsonMap, new Settings());
}
}
Not every variable might be correctly named, i just renamed them.
Thanks for you help
EDIT: fixed, the temporary Settings that was put into the arrays was somehow being changed every time, acting like a pointer or something. I made a new Settings just before adding, and set the settings of tmp to that one. It works now.

How can I work around a list resizing issue when an ArrayList is not an option to use?

We have a search tool that displays results in a table. The list I have to compose and return has to be something like this:
List[] res = new List[(some_int_initializer];
return res;
The problem this poses is that this type of list is not re-sizeable. This problem poses a problem I have, in which I have to resize this list when I don't
while(collection.iterator().hasNext())
{
StringBuilder sb = new StringBuilder();
sb.append("C:\\test\\sage\\data\\");
List<String> myList = collection.iterator().next();
// iterate through string list and compose file paths
for(String name: myList)
{
Matcher matcher = samplePattern.matcher(sampleName);
if(matcher.find())
{
sb.append(matcher.group(1));
sb.append(matcher.group(2));
sb.append(matcher.group(3));
sb.append("000\\nmr\\");
sb.append(name);
}
File file = new File(sb.toString());
int counter = 0;
List[] res = new List[myList.size()];
if(file.exists())
{
File[] dirs = file.listFiles();
for(int step=0;step<dirs.length;step++)
{
List row = new ArrayList();
row.add(name);
row.add(dirs[step].getAbsolutePath());
res[counter++] = row;
}
}
}
}
The name and path have to be displayed on a row, but a name can have more than one path associated with it. Also, even if the file path does not exist, the name still show in the table. This is make it really difficult to resize the list, especially when I have to add each Array list to 'res'.
Any thoughts or ideas appreciated.
UPDATE
Thanks to all who have responded. This is the solution that worked for me:
List[] results = allRows.toArray(new List[allRows.size()]);
Thanks to all who have responded. This is the solution that worked for me:
List[] results = allRows.toArray(new List[allRows.size()]);

Categories

Resources