JSON null Object Reference Error {Android} - java

I have made an application by this tutorial
http://javatechig.com/android/json-feed-reader-in-android
but when I run app in android studio there are following errors
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at com.example.administrator.myapplication5.FeedListActivity.getJSONFromUrl(FeedListActivity.java:127)
at com.example.administrator.myapplication5.FeedListActivity$DownloadFilesTask.doInBackground(FeedListActivity.java:85)
at com.example.administrator.myapplication5.FeedListActivity$DownloadFilesTask.doInBackground(FeedListActivity.java:67)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
This is FeedListActivity class
public class FeedListActivity extends Activity {
private ArrayList<FeedItem> feedList = null;
private ProgressBar progressbar = null;
private ListView feedListView = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posts_list);
progressbar = (ProgressBar) findViewById(R.id.progressBar);
String url = "http://javatechig.com/api/get_category_posts/?dev=1&slug=android";
new DownloadFilesTask().execute(url);
}
public void updateList() {
feedListView= (ListView) findViewById(R.id.custom_list);
feedListView.setVisibility(View.VISIBLE);
progressbar.setVisibility(View.GONE);
feedListView.setAdapter(new CustomListAdapter(this, feedList));
feedListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = feedListView.getItemAtPosition(position);
FeedItem newsData = (FeedItem) o;
Intent intent = new Intent(FeedListActivity.this, FeedDetailsActivity.class);
intent.putExtra("feed", newsData);
startActivity(intent);
}
});
}
private class DownloadFilesTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(Void result) {
if (null != feedList) {
updateList();
}
}
#Override
protected Void doInBackground(String... params) {
String url = params[0];
// getting JSON string from URL
JSONObject json = getJSONFromUrl(url);
//parsing json data
parseJson(json);
return null;
}
}
public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public void parseJson(JSONObject json) {
try {
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
feedList = new ArrayList<FeedItem>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
FeedItem item = new FeedItem();
item.setTitle(post.getString("title"));
item.setDate(post.getString("date"));
item.setId(post.getString("id"));
item.setUrl(post.getString("url"));
item.setContent(post.getString("content"));
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setAttachmentUrl(attachment.getString("url"));
}
feedList.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Also, I found this answer (Android strange error) but it didn't work
I would be thankful to consider this error and help me to solve that.

I know that maybe could be stupid but one error that was bother me was:
JSONObject.put(java.lang.String, java.lang.Object)' on a null object reference
This can happen even when you have not declared your json into your doInBackground.
So when you write your code don't forget to insert:
final JSONObject jsonresponse = new JSONObject();

Give your app permission to get connected to the internet in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

The exception is thrown here:
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
json is null, and JSONObject can't be created. Please check why json is not assigned and remains null in this code:
String json = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

Related

How to use GetJsonFromUrlTask.java in a fragment

I found the code below from a website and it seems it might help me in my android application. But the problem is, the code below is for an activity only and I need to run the code in a fragment. BTW my application is about downloading the images from the online database and storing it to a listview.
What should I do?
This is the code I want to use:
public class GetJsonFromUrlTask extends AsyncTask<Void, Void, String> {
private Activity activity;
private String url;
private ProgressDialog dialog;
private final static String TAG = GetJsonFromUrlTask.class.getSimpleName();
public GetJsonFromUrlTask(Activity activity, String url) {
super();
this.activity = activity;
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progress dialog
dialog = new ProgressDialog(activity);
// Set progress dialog title
dialog.setTitle("Getting JSON DATA");
// Set progress dialog message
dialog.setMessage("Loading...");
dialog.setIndeterminate(false);
// Show progress dialog
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
// call load JSON from url method
return loadJSON(this.url).toString();
}
#Override
protected void onPostExecute(String result) {
((CategoryListViewActivity) activity).parseJsonResponse(result);
dialog.dismiss();
Log.i(TAG, result);
}
public JSONArray loadJSON(String url) {
// Creating JSON Parser instance
JSONGetter jParser = new JSONGetter();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
return json;
}
private class JSONGetter {
private InputStream is = null;
private JSONArray jObj = null;
private String json = "";
// constructor
public JSONGetter() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),
8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
}
There is easy step to use AsyncTask within fragment just as follow
place code on activityCreateview
new GetJsonFromUrlTask(getActivity(), mListView).execute("");
getActivity() is method to getting your activity context in to Fragment class
Note: As you found code from website this code is a AsyncTask class you can call this code in to Activity,Fragment, any other Class also
Change code
public class GetJsonFromUrlTask extends AsyncTask<Void, Void, String> {
private Context activity;
private String url;
private ProgressDialog dialog;
private final static String TAG = GetJsonFromUrlTask.class.getSimpleName();
public GetJsonFromUrlTask(Context activity, String url) {
super();
this.activity = activity;
this.url = url;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progress dialog
dialog = new ProgressDialog(activity);
// Set progress dialog title
dialog.setTitle("Getting JSON DATA");
// Set progress dialog message
dialog.setMessage("Loading...");
dialog.setIndeterminate(false);
// Show progress dialog
dialog.show();
}
#Override
protected String doInBackground(Void... params) {
// call load JSON from url method
return loadJSON(this.url).toString();
}
#Override
protected void onPostExecute(String result) {
dialog.dismiss();
Log.i(TAG, result);
}
public JSONArray loadJSON(String url) {
// Creating JSON Parser instance
JSONGetter jParser = new JSONGetter();
// getting JSON string from URL
JSONArray json = jParser.getJSONFromUrl(url);
return json;
}
private class JSONGetter {
private InputStream is = null;
private JSONArray jObj = null;
private String json = "";
// constructor
public JSONGetter() {
}
public JSONArray getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"),
8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONArray(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
}

I want to display values on textview through JSONParser using given url

I want to display about_builder of given JSON url, but I am not able to declare properly JSONObject and JSONArray on MainActivity, so please anyone help me to display the data on TextView.
Error shown:
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.and_ws_builder/com.example.and_ws_builder.MainActivity}:
android.os.NetworkOnMainThreadException
MainActivity.java class
public class MainActivity extends Activity {
private static String url ="http://myfourwalls.in/services_microsite/project_builder.php";
private static final String TAG_Name = "about_builder";
JSONArray builder = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFormUrl(url);
try {
builder = json.getJSONArray(TAG_Name);
JSONObject c = builder.getJSONObject(0);
for (int i = 0; i < json.length(); i++) {
String name = c.getString(TAG_Name);
final TextView nam = (TextView) findViewById(R.id.txtname);
nam.setText(name);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jobj = null;
static String json = "";
public JSONParser() {
}
public JSONObject getJSONFormUrl(String url) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}catch (ClientProtocolException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null ){
sb.append(line +"\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error","Error converting result" + e.toString());
}
try {
jobj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parse","error Parsing data" + e.toString());
}
return jobj;
}
}
main_activity.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/txtname"
android:layout_width="fill_parent"
android:layout_height="100dp"/>
</RelativeLayout>
You are using Network related code in main thread. Use AsyncTask.
You are calling network calls inside the main thread means foreground which is not supported in android.So use assynctask class which will handle network calls in background.
1)inside on create method call like:
new GetJson().execute();
2) declare the following outside oncreate
private class GetJson extends AsyncTask<String, Void, String> {
JSONObject c=null;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFormUrl(url);
try {
builder = json.getJSONArray(TAG_Name);
c = builder.getJSONObject(0);
} catch (JSONException e) {
e.printStackTrace();
}
return c;
}
#Override
protected void onPostExecute(final JSONObject result) {
for (int i = 0; i < result.length(); i++) {
String name = result.getString(TAG_Name);
final TextView nam = (TextView) findViewById(R.id.txtname);
nam.setText(name);
}
}

NullPointerException error in android with json

I know there are many great explanations in StackOverFlow regarding this error. But I have spent countless hours trying to solve this error in my code but I couldn't. I am new to android programming. Hopefully you guys can help.
I am trying to store data in MySQL using PHP in this android app.
Here is my MainActivity
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private EditText userName, userContact, userAddress, userRequest;
private Spinner userStore;
private Button mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script
//localhost :
//testing on your device
//put your local ip instead, on windows, run CMD > ipconfig
//or in mac's terminal type ifconfig and look for the ip under en0 or en1
// private static final String LOGIN_URL = "http://xxx.xxx.x.x:1234/webservice/register.php";
//testing on Emulator:
private static final String LOGIN_URL = "http://10.0.2.2/callarocket/register.php";
//testing from a real server:
//private static final String LOGIN_URL = "http://www.yourdomain.com/webservice/register.php";
//ids
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner dropdown = (Spinner)findViewById(R.id.StoreSpinner);
String[] items = new String[]{"NZ Mamak", "Indo Shop", "NZ Supermarket"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
dropdown.setAdapter(adapter);
userName = (EditText)findViewById(R.id.EditName);
userContact = (EditText)findViewById(R.id.EditContact);
userAddress = (EditText)findViewById(R.id.EditAddress);
userStore = (Spinner)findViewById(R.id.StoreSpinner);
userRequest = (EditText)findViewById(R.id.EditRequest);
mRegister = (Button)findViewById(R.id.SubmitButton);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new CreateUser().execute();
}
class CreateUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Creating Request...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = userName.getText().toString();
String usercontact = userContact.getText().toString();
String useraddress = userAddress.getText().toString();
String userstore = userStore.getSelectedItem().toString();
String userrequest = userRequest.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("userName", username));
params.add(new BasicNameValuePair("userContact", usercontact));
params.add(new BasicNameValuePair("userAddress", useraddress));
params.add(new BasicNameValuePair("userStore", userstore));
params.add(new BasicNameValuePair("userRequest", userrequest));
Log.d("request!", "starting");
//Posting user data to script
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// full json response
Log.d("Login attempt", json.toString());
// json success element
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("User Created!", json.toString());
finish();
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once product deleted
pDialog.dismiss();
if (file_url != null){
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
Here is my JSONParser.java
public class JSONParser {
static InputStream is = null ;
static JSONObject jObj = null ;
static String json = " " ;
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
// Construct the client and the HTTP request.
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Execute the POST request and store the response locally.
HttpResponse httpResponse = httpClient.execute(httpPost);
// Extract data from the response.
HttpEntity httpEntity = httpResponse.getEntity();
// Open an inputStream with the data content.
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
// Create a BufferedReader to parse through the inputStream.
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declare a string builder to help with the parsing.
StringBuilder sb = new StringBuilder();
// Declare a string to store the JSON object data in string form.
String line = null;
// Build the string until null.
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
//Log.i("DATA","json data is :: "+json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// Try to parse the string to a JSON object
try {
jObj = new JSONObject(json);
//jarr = new JSONArray(json);
//jObj = jarr.getJSONObject(0);
//JSONParser parser = new JSONParser();
//Object obj = parser.parse(json);
//JSONObject jsonObj = (JSONObject) obj;
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// Return the JSON Object.
return jObj;
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
The full logcat
02-25 14:13:43.070 2708-2725/com.example.user.callarocket D/request!﹕ starting
02-25 14:13:43.132 2708-2723/com.example.user.callarocket W/EGL_emulation﹕ eglSurfaceAttrib not implemented
02-25 14:13:43.132 2708-2723/com.example.user.callarocket W/OpenGLRenderer﹕ Failed to set EGL_SWAP_BEHAVIOR on surface 0xa6c46c20, error=EGL_SUCCESS
02-25 14:13:43.318 2708-2725/com.example.user.callarocket E/JSON Parser﹕ Error parsing data org.json.JSONException: Value Posted of type java.lang.String cannot be converted to JSONObject
02-25 14:13:43.318 2708-2725/com.example.user.callarocket E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #2
Process: com.example.user.callarocket, PID: 2708
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.toString()' on a null object reference
at com.example.user.callarocket.MainActivity$CreateUser.doInBackground(MainActivity.java:129)
at com.example.user.callarocket.MainActivity$CreateUser.doInBackground(MainActivity.java:86)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
            at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
            at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
            at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
            at java.lang.Thread.run(Thread.java:818)
02-25 14:13:45.643 2708-2708/com.example.user.callarocket E/WindowManager﹕ android.view.WindowLeaked: Activity com.example.user.callarocket.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{279ba229 V.E..... R......D 0,0-1026,348} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:363)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:261)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:298)
at com.example.user.callarocket.MainActivity$CreateUser.onPreExecute(MainActivity.java:100)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at com.example.user.callarocket.MainActivity.onClick(MainActivity.java:82)
at android.view.View.performClick(View.java:4756)
at android.view.View$PerformClick.run(View.java:19749)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

Android errors when on second,third load

I am making 3 fragments pages app, and have 2 diffrent fragments with http json but with same code. The app work normaly but when i go to fragment and to another then back i get force close
threadid=1: thread exiting with uncaught exception (group=0x411f42a0)
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.fddaaf.Fragment3.updateList(Fragment3.java:55)
at com.example.fddaaf.Fragment3$thirdDownloadFilesTask.onPostExecute(Fragment3.java:83)
at com.example.fddaaf.Fragment3$thirdDownloadFilesTask.onPostExecute(Fragment3.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4898)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
at dalvik.system.NativeStart.main(Native Method)
this is Fragment3 class
public class Fragment3 extends Fragment {
private ArrayList<thirdFeedItem> thirdfeedList;;
private ProgressBar progresssbar;
private ListView thirdfeedListView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View thirdrootView = inflater.inflate(R.layout.third, container, false);
progresssbar = (ProgressBar)thirdrootView.findViewById(R.id.progresssBar);
String url = "";
new thirdDownloadFilesTask().execute(url);
return thirdrootView;
}
public void updateList() {
thirdfeedListView= (ListView)getActivity().findViewById(R.id.third_list);
thirdfeedListView.setVisibility(View.VISIBLE);
if (thirdfeedListView.isShown()) {
progresssbar.setVisibility(View.GONE);
}
thirdfeedListView.setAdapter(new thirdCustomListAdapter(getActivity(), thirdfeedList));
thirdfeedListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = thirdfeedListView.getItemAtPosition(position);
thirdFeedItem thirdData = (thirdFeedItem) o;
Intent intent = new Intent(getActivity(), thirdFeedDetailsActivity.class);
intent.putExtra("thirdfeed", thirdData);
startActivity(intent);
}
});
}
public class thirdDownloadFilesTask extends AsyncTask<String, Integer, Void> {
#Override
protected void onPostExecute(Void result) {
if (null != thirdfeedList) {
updateList();
}
}
#Override
protected Void doInBackground(String... params) {
String url = params[0];
// getting JSON string from URL
JSONObject json = getJSONFromUrl(url);
//parsing json data
parseJson(json);
return null;
}
}
public JSONObject getJSONFromUrl(String url) {
InputStream is = null;
JSONObject jObj = null;
String json = null;
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
public void parseJson(JSONObject json) {
try {
// parsing json object
if (json.getString("status").equalsIgnoreCase("ok")) {
JSONArray posts = json.getJSONArray("posts");
thirdfeedList = new ArrayList<thirdFeedItem>();
for (int i = 0; i < posts.length(); i++) {
JSONObject post = (JSONObject) posts.getJSONObject(i);
thirdFeedItem item = new thirdFeedItem();
item.setthirdTitle(post.getString("title"));
item.setthirdDate(post.getString("description"));
item.setthirdId(post.getString("id"));
item.setthirdUrl(post.getString("url"));
item.setthirdContent(post.getString("description"));
JSONArray attachments = post.getJSONArray("attachments");
if (null != attachments && attachments.length() > 0) {
JSONObject attachment = attachments.getJSONObject(0);
if (attachment != null)
item.setthirdAttachmentUrl(attachment.getString("url"));
}
thirdfeedList.add(item);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I checked everything, what can be a problem? thank you

Receiving JSON java.lang.string cannot be converted to jsonarray

im making an app for a website. It has an JSON API. The URL im trying to fetch the result from is: http://api.bayfiles.net/v1/account/login/<user>/<password>
I get the error: java.lang.string cannot be converted to jsonarray when logging the error using logcat.
My main activity is:
public class MainActivity extends SherlockActivity {
EditText un,pw;
TextView error;
Button ok;
private ProgressDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
un = (EditText)findViewById(R.id.user);
pw = (EditText)findViewById(R.id.psw);
ok = (Button)findViewById(R.id.button1);
error = (TextView)findViewById(R.id.textView1);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//error.setText("Clicked");
//Intent startNewActivityOpen = new Intent(LoginActivity.this, FilesActivity.class);
//startActivityForResult(startNewActivityOpen, 0);
JsonAsync asyncTask = new JsonAsync();
// Using an anonymous interface to listen for objects when task
// completes.
asyncTask.setJsonListener(new JsonListener() {
public void onObjectReturn(JSONObject object) {
handleJsonObject(object);
}
});
// Show progress loader while accessing network, and start async task.
//mDialog = ProgressDialog.show(this, getSupportActionBar().getTitle(),
// getString(R.string.loading), true);
asyncTask.execute("http://api.bayfiles.net/v1/account/login/spxc/mess2005");
}
});
}
private void handleJsonObject(JSONObject object) {
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
try {
JSONArray shows = object.getJSONArray("error");
for (int i = 0; i < shows.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = shows.getJSONObject(i);
//map.put("video_id", String.valueOf(i));
map.put("session", "" + e.getString("session"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data: " + e.toString());
}
error.setText("session");
/*
//Intent myIntent = new Intent(ListMoviesController.this,
// TestVideoController.class);
myIntent.putExtra("video_title", o.get("video_title"));
myIntent.putExtra("video_channel", o.get("video_channel"));
myIntent.putExtra("video_location", o.get("video_location"));
startActivity(myIntent); */
}{
if (mDialog != null && mDialog.isShowing()) {
mDialog.dismiss();
}
}
}
And this is my adapter: JSONfunctions.java
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url){
InputStream is = null;
String result = "";
JSONObject jArray = null;
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
try {
// Add your data
/*List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("key", "stianxxs"));
nameValuePairs.add(new BasicNameValuePair("secret", "mhfgpammv9f94ddayh8GSweji"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); */
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
//HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
is = httpEntity.getContent();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
try{
jArray = new JSONObject(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
Why im i getting this error? When using the right username and password in the url you would get: {"error":"","session":"RANDOM NUMBER"}
And as you can see i try to fetch this number. Any help is much appreciated!
You are getting this error because in line
JSONArray shows = object.getJSONArray("error");
you are trying to get value for key error and treat is as an array, whereas it's not - it's an empty string. Therefore you need to get it as a string:
String error = object.getString("error");
Similarly, if you need to get your "session", you can get it with
String session = object.getString("session");
P.S. Note that this is assuming that your JSONObject object actually contains the object represented by the string in your question.

Categories

Resources