Reputation: 1924
In logcat I am getting a null pointer exception
for this code sample. I am trying to add the e.g oneObject.has(TAG_TITLE)
inside an Arraylist
but when I print currentPost.getid()
for example i am getting this nullpointer excepttion
. Can someone help me please.
// getting JSON string from URL
JSONArray jArray = jParser.getJSONFromUrl(url);
ArrayList<Post> PostList = new ArrayList<Post>();
Post currentPost = new Post();
// looping through All element
for(int i = 0; i < jArray.length(); i++){
try{
JSONObject oneObject = jArray.getJSONObject(i);
// Storing each json item in variable
if(oneObject.has(TAG_ID)){
id = oneObject.getString(TAG_ID);
currentPost.setId(id);
}
else{
id="";
}
if(oneObject.has(TAG_TITLE)){
title = oneObject.getString(TAG_TITLE);
currentPost.setTitle(title);
}
else{
title ="";
}
if(oneObject.has(TAG_CONTENT)){
content = oneObject.getString(TAG_CONTENT);
currentPost.setContent(content);
}
else{
content ="";
}
System.out.println("postlist: "+currentPost.getId());
PostList.add(currentPost);
currentPost = new Post();
Upvotes: 1
Views: 418
Reputation: 607
In your code
// Storing each json item in variable
if(oneObject.has(TAG_ID)){
id = oneObject.getString(TAG_ID);
currentPost.setId(id);
}
else{
id="";
}
You have missed to set the Id for current oneObject.has(TAG_ID)
returns false.
Best way to avoid this would be to return empty string from all your getters if the parameter is not being set.
EDIT:
Add make the change that is in bold.
// Storing each json item in variable
if(oneObject.has(TAG_ID)){
id = oneObject.getString(TAG_ID);
currentPost.setId(id);
}
else{
id="";
**currentPost.setId(id);**
}
Upvotes: 0
Reputation: 132982
you also need to set currentPost object fields values to default value if key name not exist in Json String as :
// your code here...
if(oneObject.has(TAG_ID)){
id = oneObject.getString(TAG_ID);
currentPost.setId(id);
}
else{
id="DEFAULT_VALUE";
currentPost.setId(id); //<<<< set default value here
}
// your code here...
Upvotes: 1