NullPointerException with listview on android - java

I am want to show this json data in to listview. Iam having this problem:
java.lang.NullPointerException: Attempt to invoke virtual method 'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object reference
private String[] arrow() throws JSONException {
json = new JSONObject();
JSONArray com= null;
String[] list = new String[10];
try {
com = json.getJSONArray("parameters"); // this have 10 different values
} catch (JSONException e) {
e.printStackTrace();
}
for (int i = 0; i < 10; i++)
try {
json = com.getJSONObject(i);
String forward= json.getString("forward");
String back= json.getString("back");
list[i]="Forward: " + forward + "\n" + "Backward: " + back;
} catch (JSONException e) {
e.printStackTrace();
}
return list;
}
I did it with textview but cant do it with listview, i get this nullpointer..
Please help. Thanks.

There are multiple problems. The first problem is that you are using two try/catch. If you get exception in first one, you still go to 2nd try and try to run code.
json = com.getJSONObject(i);
this line is in 2nd try catch. In your case it seems com is null because there was exception in 1st try/catch.
try {
com = json.getJSONArray("parameters"); // this have 10 different values
for (int i = 0; i < com.length(); i++) {
json = com.getJSONObject(i);
String forward= json.getString("forward");
String back= json.getString("back");
list[i]="Forward: " + forward + "\n" + "Backward: " + back;
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

Java - ArrayIndexOutofBoundsException when trying to populate arrays by iterating over a JSONArray [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 4 years ago.
I am trying to populate the server and the itemsId by iterating over a JSONArray.
String jsonString = '"[{\"label\":\"Label 1\",\"srvid\":1},{\"label\":\"label 2\",\"srvid\":2}]"';
String[] servers = new String[100];
Integer itemsId[] = new Integer[100];
try {
JSONArray array = new JSONArray(jsonString);
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
servers[i] = o.getString("label");
itemsId[i] = o.getInt("srvid");
}
} catch (JSONException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
However, I am getting ArrayIndexOutOfBoundsException here but I don't know how to further solve this. I wonder what could be wrong in the declaration of the arrays and how they are populated.
The only problem I can see here is the single quotes that are enclosing the JSON string. Other than that, the code works flawlessly in Intellij IDEA 2018.1.3.
String jsonString = "[{\"label\":\"Label 1\",\"srvid\":1},{\"label\":\"label 2\",\"srvid\":2}]";
String[] servers = new String[100];
Integer itemsId[] = new Integer[100];
try {
JSONArray array = new JSONArray(jsonString);
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
servers[i] = o.getString("label");
itemsId[i] = o.getInt("srvid");
}
System.out.println(Arrays.toString(servers)); //Added for testing purposes
System.out.println(Arrays.toString(itemsId)); //Added for testing purposes
} catch (JSONException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
The two System.out.println(Arrays.toString(arr)) calls gives the expected output. No problems.
I Executed the following code which is a replica of yours (changed the jsonString).
String jsonString = "[{'label':'Label 1','srvid':1},{'label':'label 2','srvid':2}]";
String[] servers = new String[100];
Integer itemsId[] = new Integer[100];
try {
JSONArray array = new JSONArray(jsonString);
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
servers[i] = o.getString("label");
System.out.println(servers[i]);
itemsId[i] = o.getInt("srvid");
System.out.println(itemsId[i]);
}
} catch (JSONException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}
And got the response.
Label 1
1
label 2
2
So code looks good, if there is nothing wrong with JSON String.
So what I did is I have initialized the length of the arrays by the size of the JSONArray. And taken them inside the try catch.
try {
JSONArray array = new JSONArray(jsonString);
String[] servers = new String[array.length()];
Integer[] itemsId = new Integer[array.length()];
for (int i = 0; i < array.length(); i++) {
JSONObject o = array.getJSONObject(i);
servers[i] = o.getString("label");
itemsId[i] = o.getInt("srvid");
}
//REST OF THE CODES
} catch (JSONException e) {
e.printStackTrace();
} catch(Exception e) {
e.printStackTrace();
}

Parse json string to json array? [duplicate]

This question already has answers here:
Convert string to JSON array
(10 answers)
Closed 5 years ago.
i need help to convert json string to json array as i given below
{"level":[{"id":"1","name":"first","time":"00:02:00"},{"id":"2","name":"second","time":"00:03:00"},{"id":"3","name":"math","time":"00:03:00"},
{"id":"4","name":"language ","time":"00:03:00"},{"id":"5","name":"sport","time":"00:04:00"}]}
to use it in android studio
Try this
try
{
JSONObject resObject = new JSONObject("your json response");
JSONArray jsonArray = resObject.getJSONArray("level");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i("id", "" + jsonObject.getString("id"));
Log.i("name","" + jsonObject.getString("name"));
Log.i("time", "" + jsonObject.getString("time"));
}
}
catch (JSONException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
OUTPUT
Try this
try {
JSONObject jsonObject=new JSONObject(yourresponsestring);
JSONArray jsonArray=new JSONArray(jsonObject.getJSONArray("level"));
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject1=jsonArray.getJSONObject(i);
String id=jsonObject1.getString("id");
String name=jsonObject1.getString("name");
String time=jsonObject1.getString("time");
}
} catch (JSONException e) {
e.printStackTrace();
}
You can try below code to convert the data to JSON:
try {
JSONObject jsonObject = new JSONObject("{\"level\":[{\"id\":\"1\",\"name\":\"first\",\"time\":\"00:02:00\"},{\"id\":\"2\",\"name\":\"second\",\"time\":\"00:03:00\"},{\"id\":\"3\",\"name\":\"math\",\"time\":\"00:03:00\"}, {\"id\":\"4\",\"name\":\"language \",\"time\":\"00:03:00\"},{\"id\":\"5\",\"name\":\"sport\",\"time\":\"00:04:00\"}]}");
JSONArray level = jsonObject.getJSONArray("level");
for (int i = 0; i < level.length(); i++) {
JSONObject data = level.getJSONObject(i);
String id = data.getString("id");
String name = data.getString("name");
String time = data.getString("time");
Log.d("JSONDATA--->", "Data at: " + i + " " + id + ":" + name + ":" + time);
}
} catch (JSONException e) {
e.printStackTrace();
}

How to fix input getting cut off by output

So, I'm trying to create a function (If not pretty) IRC client using no libraries, written in Java. I've gotten almost everything working, the only problem is that I'm currently getting user input using System.in. And if someone else in the channel sends a message while I'm in the middle of typing, it cuts off what I currently have, and I need to guess where I am in the string. I want to know if there's a way to separate user input from the output of the program, so that this doesn't happen. This is the code in question:
new Thread(() -> {
while(connected[0]) {
String output = sc.nextLine();
if(!output.startsWith("~") && !output.startsWith("/")) {
try {
writeToSocket("PRIVMSG " + focused[0] + " " + output);
} catch (IOException e) {
e.printStackTrace();
}
}
if(output.substring(1).toLowerCase().startsWith("quit")) {
String[] split = output.substring(5).split(" ");
StringBuilder sb = new StringBuilder();
for (int i = 0; i < split.length; i++) {
if(i == 0) {
sb.append(split[i]);
}
sb.append(" ").append(split[i]);
}
try {
writeToSocket("QUIT " + sb.toString());
connected[0] = false;
} catch (IOException e) {
e.printStackTrace();
}
}else if(output.substring(1).toLowerCase().startsWith("focus")) {
String get = output.substring(7);
if(!channels.contains(get)) {
print("Not connected to channel");
}else {
try {
writeToSocket("PART " + focused[0]);
writeToSocket("JOIN " + get);
} catch (IOException e) {
e.printStackTrace();
}
focused[0] = get;
}
}else if(output.substring(1).toLowerCase().startsWith("join")) {
String get = output.substring(6);
channels.add(get);
}
if(output.startsWith("/") && output.substring(1).toLowerCase().startsWith("msg")) {
String[] split = output.substring(5).split(" ");
String username = split[0];
StringBuilder msg = new StringBuilder();
for(int i = 1; i < split.length; i++) {
if(i == 1) {
msg.append(split[i]);
continue;
}
msg.append(" ").append(split[i]);
}
try {
writeToSocket("PRIVMSG " + username + " " + msg.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}).start();

Create ordered Arrays with JSONObject

Let me explain my problem.
(I'm new to java so maybe this type of thing might be easy but I can't figure it out !)
I have a JSONObject which looks like :
{
notes:[
{
"scolaryear":2013,
"codemodule":"B-CPE-042",
"titlemodule":"B1 - Unix & C Lab Seminar",
"codeinstance":"NCE-1-1",
"codeacti":"acti-134315",
"title":"Piscine Jour 1",
"date":"2013-10-04 13:33:51",
"correcteur":"ramassage-tek",
"final_note":0,
"comment":"Ex_00 -> output differs"
},
{} // And so on ..
]
}
For now I can get all the data doing something like :
try {
// Pulling items from the array
JSONArray notesArr = jsonObject.getJSONArray("notes");
try {
ListView lv = (ListView) _modulesActivity.findViewById(R.id.listView);
List < String > notesList = new ArrayList < String > ();
for (int i = 0; i < notesArr.length(); i++) {
JSONObject tmp = notesArr.getJSONObject(i);
String code_module = tmp.getString("codemodule");
String module = tmp.getString("titlemodule");
String title = tmp.getString("title");
String final_note = tmp.getString("final_note");
String year = tmp.getString("scolaryear");
String comment = tmp.getString("comment");
String display = year + " | " + title + " | " + final_note;
notesList.add(display);
}
ArrayAdapter < String > arrayAdapter = new ArrayAdapter < String > (
_mainContext, android.R.layout.simple_list_item_1, notesList);
lv.setAdapter(arrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
So with that technique I got all my data in one array and an only listView which looks like :
2014 | PROJECT #1 | 13/20
2015 | PROJECT #2 | 20/20
But I need to order my data with year, and module.
It would look like :
> YEAR (year)
> TITLE OF MODULE (module) - MODULE CODE (codemodule)
> PROJECT NAME (title) | MARK (final_note)
- COMMENT (comment)
You have a first header with the year, when you click on a year, you can see all the module :
> MODULE #1
> MODULE #2
...
And when you click on a module you can see all project :
> PROJECT #1 | MARK : 20
> PROJECT #2 | MARK : 13
...
And finally when you click on a project you can see the comment !
^ PROJECT #1 | MARK : 20
- Great project .. bla bla bla
(or maybe display a popup window which contains the comments if it's possible)
I know it may be a complexe thing but I really want to achieve that !
Thanks in advance for your help !
In my opinion you have two possibilities:
Implement a Note Java object, during the form initialize this objects and put them in an ArrayList. In the end sort it with some algorithm.
For example it would look like:
List<Note> notesList = new ArrayList<Note>();
for (int i = 0; i < notesArr.length(); i++) {
JSONObject tmp = notesArr.getJSONObject(i);
noteListe.add(new Note(tmp.getString("codemodule"), tmp.getString("titlemodule"),...);
}
Now sort it with a proper method and in the end print it maybe overriding toString() Note method.
If possible sort the JsonObjectArray when you create it.
Hope it can help you
So I found a solution !
I used this library : https://github.com/bmelnychuk/AndroidTreeView
Here is my Code :
try {
// Pulling items from the array
TreeNode root = TreeNode.root();
TreeNode child;
String year = "YEAR";
String moduleName = "";
YearHolder.IconTreeItem nodeItem = new YearHolder.IconTreeItem(1, year);
ModuleHolder.IconTreeItem nodeModule = new ModuleHolder.IconTreeItem(1, moduleName);
TreeNode parent = new TreeNode(nodeItem).setViewHolder(new YearHolder(_mainContext));
TreeNode parentModule = new TreeNode(nodeModule).setViewHolder(new ModuleHolder(_mainContext));
JSONArray modArr = jsonObject.getJSONArray("notes");
try {
for (int i = 0; i < modArr.length(); i++) {
JSONObject tmp = modArr.getJSONObject(i);
/*String title = tmp.getString("title");*/
String final_note = tmp.getString("final_note");
String newModuleName = tmp.getString("titlemodule");
String newYear = tmp.getString("scolaryear");
if (!(newYear.equals(year))) {
year = newYear;
nodeItem = new YearHolder.IconTreeItem(1, year);
parent = new TreeNode(nodeItem).setViewHolder(new YearHolder(_mainContext));
root.addChild(parent);
}
if (!(newModuleName.equals(moduleName))) {
moduleName = newModuleName;
nodeModule = new ModuleHolder.IconTreeItem(1, moduleName);
parentModule = new TreeNode(nodeModule).setViewHolder(new ModuleHolder(_mainContext));
parent.addChild(parentModule);
}
NoteHolder.IconTreeItem nodeNote = new NoteHolder.IconTreeItem(1, final_note);
child = new TreeNode(nodeNote).setViewHolder(new NoteHolder(_mainContext));
parentModule.addChildren(child);
/*String display = year + " | " + title + " | " + final_note;*/
}
AndroidTreeView tView = new AndroidTreeView(_notesActivity, root);
_notesActivity.setContentView(tView.getView());
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(_mainContext, "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
YearHolder class looks like this :
public class YearHolder extends TreeNode.BaseNodeViewHolder<YearHolder.IconTreeItem> {
public YearHolder (Context context ) {
super(context);
}
#Override
public View createNodeView(TreeNode node, IconTreeItem value) {
final LayoutInflater inflater = LayoutInflater.from(context);
final View view = inflater.inflate(R.layout.custom_notes_view, null, false);
TextView tvValue = (TextView) view.findViewById(R.id.text_title);
tvValue.setText(value.text);
return view;
}
public static class IconTreeItem {
public int icon;
public String text;
IconTreeItem(int icon_, String text_) {
this.icon = icon_;
this.text = text_;
}
}
}
Super easy to use !

Parsing a flat JSON array with no indice

I am scratching my head to figure out how to parse the following JSON object.
[
{
"result": true,
"response": "Successfully got list of users in radius of 10km"
},
{
"username": "elize",
"photo": "http://www.embedonix.com/apps/mhealth/images/elize/elize.png"
},
{
"username": "mario",
"photo": "http://www.embedonix.com/apps/mhealth/images/mario/mario.png"
}
]
This is I guess a single index json array. The first part tells that the operation of building the json object was ok.
Then there are pairs of username and photo which I have to parse them and put them in a list:
public class User {
private String mName;
private String mPhotoURl;
public User(String name, String url)
{
///
}
}
So if the first entry of json is result -> true I should have a ArrayList<User>.
I tried to do the following but it always raises the JSONParse exception:
try {
JSONObject json = new JSONObject(data);
int length = json.length();
for (int i = 0; i < length; i++) {
JSONArray obj = json.getJSONArray(String.valueOf(i));
Log.i(TAG, i + " username: " + obj.getString(i));
}
} catch (JSONException e) {
e.printStackTrace();
}
Just try this way
try {
JSONArray jsonArray = new JSONArray(data);
int length = jsonArray.length();
for (int i = 1; i < length; i++) {
JSONObject obj = jsonArray.getJSONObject(i);
Log.i(TAG, i + " username: " + obj.getString("username"));
Log.i(TAG, i + " photo: " + obj.getString("photo"));
}
} catch (JSONException e) {
e.printStackTrace();
}
Try this way,hope this will help you to solve your problem.
try {
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
if(i==0){
Log.i(TAG, i + " result: " + obj.getString("result"));
Log.i(TAG, i + " response: " + obj.getString("response"));
}else{
Log.i(TAG, i + " username: " + obj.getString("username"));
Log.i(TAG, i + " photo: " + obj.getString("photo"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
Try Code...something like this..
try {
JSONArray json = new JSONArray(data);
int length = json.length();
for (int i = 0; i < length; i++) {
JSONObject childObject = json.getJSONObject(i);
if(i==0){
String result = child.getBoolean("result");
String resp = child.getString("response");
} else {
String username = child.getString("username");
String photo = child.getString("photo");
Log.i(TAG, i + " username: " + username);
}
}
} catch (JSONException e) {
e.printStackTrace();
}

Categories