I've read many other topics on SO from people who received the same exception, but none of the proposed solutions worked. So here's my problem:
I'm trying to download a userlist from my database through a function in my app. The JSONParser keeps returning a NullPointException on this particular table from the database. I've successfully used the JSONParser class on other queries, but it doesn't work on this one. I've tested the PHP file which handles the query, and it returns the exact values I want as a JSON OBject. If the table is empty, it returns:
{
"success":0,
"message":"No users found"
}
If the table contains user information, it returns:
{
"success":1,
"users":[
{
"ID":someID1,
"NAME":someName1
"PHONE":somePhoneNumber1
},
{
"ID":someID2,
"NAME":someName2
"PHONE":somePhoneNumber2
}]
}
I'm starting the request by calling
LoadAllUsers load = new LoadAllUsers();
load.execute();
in a certain method. This is my LoadAllUsers class:
public class LoadAllUsers extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(allUsers.this);
pDialog.setMessage("Laden van alle gebruikers...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... args) {
updateJSONData();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
updateList();
}
}
I receive a NullPointerException on the first line of my updateJSONdata() method, which is:
public void updateJSONData() {
JSONObject json = jParser.getJSONFromUrl(my_url);
try {
int success = json.getInt("success");
if (success == 1) {
JSONArray users = json.getJSONArray("users");
for (int i = 0; i<users.length(); i++) {
JSONObject c = users.getJSONObject(i);
String id = c.getString("ID");
String name = c.getString("NAAM");
String phone =c.getString("TELEFOON");
HashMap<String,String> map = new HashMap<String, String>();
map.put("ID",id);
map.put("name",name);
map.put("phonenumber",phone);
if (phoneNumber == phone) {
ID = Integer.parseInt(id);
this.name = name;
}
userlist.add(map);
}
} else {
Log.d("Geen succes!", "Helaas!");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
So, the exception is thrown in the line with jParser.getJSONFromUrl(...).
My JSONParser class, of which jParser is an instance, is:
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
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();
} 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);
} 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");
Log.d("Gemaakte paramstring",paramString);
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
Log.d("httpResponse: ",httpResponse.toString());
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;
}
}
And the LogCat message is:
05-07 10:46:24.995 27615-27686/com.example.user.my_app E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: com.example.user.my_app, PID: 27615
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:841)
Caused by: java.lang.NullPointerException
at com.example.user.my_appcenter_tile.updateJSONData(center_tile.java:376)
at com.example.user.my_app.center_tile$Memberlist.doInBackground(center_tile.java:419)
at com.example.user.my_app.center_tile$Memberlist.doInBackground(center_tile.java:406)
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:841)
I would be very grateful if you could help me out with this problem.
Well, jParser is null in updateJSONdata().
Make sure to check if it's != null before using it.
And if it should not be null, then fix your code.
Your error is just a NullPointerException.
You can use 'has' keyword to check availability of json keys, then can parse Json to avoid exception,otherwise you can track via Null Pointer exception.
public void updateJSONData() {
JSONObject json = jParser.getJSONFromUrl(my_url);
try {
int success = json.getInt("success");
boolean isAvail=json.has("users");
if (success == 1) {
if(isAvail)
JSONArray users = json.getJSONArray("users");
for (int i = 0; i<users.length(); i++) {
}
}
}
catch(Exception e){
}
}
1. jParser is NULL so use
// make sure my_url has json string in it
// read json first and use in place of my_url
JSONObject jsonObjTokener = (JSONObject) new JSONTokener(my_url).nextValue();
// get success
String isSuccess = jsonObjTokener.getString("success");
// get users
JSONObject mUser = jsonObjTokener.getJSONObject("users");
at that line
2. You did spelling mistake at
String name = c.getString("NAAM");
correct to
String name = c.getString("NAME");
Related
I am using an AsyncTask for a network call. If successful, it should return a JSON Array, and so far it works well on the device I test(Google nexus 5).
But on a Motorola device, it does not work. In the sense, it is not even sending a request to the server.
Here is the code :
private class SimpleTask extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
#Override
protected void onPreExecute()
{
dialog = new ProgressDialog(MainActivity.this,ProgressDialog.STYLE_SPINNER);
dialog.setMessage("Loading Engine");
dialog.show();
}
protected String doInBackground(String... urls) {
String result = "";
try {
//HttpGet httpGet = new HttpGet(urls[0]);
HttpPost httpPost = new HttpPost(urls[0]);
HttpClient client = new DefaultHttpClient();
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("number",details));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(httpPost);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == 200) {
InputStream inputStream = response.getEntity().getContent();
BufferedReader reader = new BufferedReader
(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
result += line;
}
}
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
//Log.w("PREMIERE::::",result);
return result;
}
protected void onPostExecute(String jsonString) {
//dialog.dismiss();
try {
if ((this.dialog != null) && this.dialog.isShowing()) {
this.dialog.dismiss();
}
} catch (final IllegalArgumentException e) {
// Handle or log or ignore
} catch (final Exception e) {
// Handle or log or ignore
} finally {
this.dialog = null;
}
showData(jsonString);
}
}
private void showData(String jsonString)
{
// try
// {
Log.w("VALS:",""+jsonString);
Gson gson = new Gson();
JsonParser parser = new JsonParser();
JsonArray jArray = parser.parse(jsonString).getAsJsonArray();
SharedPreferences pref = getSharedPreferences("ActivitySession", Context.MODE_PRIVATE);
for(JsonElement obj : jArray )
{
MainPojo cse = gson.fromJson( obj , MainPojo.class);
uid.add(cse);
}
if(!uid.isEmpty())
{
new SimpleTask2().execute(URL2);
}
else
{
Snackbar.make(this.findViewById(android.R.id.content), "Invalid Credentials", Snackbar.LENGTH_LONG).show();
}
/*
}
catch (Exception e){
Snackbar.make(this.findViewById(android.R.id.content), "Check data connection", Snackbar.LENGTH_LONG).show();
e.printStackTrace();
}*/
}
And I purposefully, did not catch exception, and traced the bug via Crashlytics. The bug occurs on this line.
JsonArray jArray = parser.parse(jsonString).getAsJsonArray();
which says :
Fatal Exception: java.lang.IllegalStateException: This is not a JSON
Array.
Which I believes also occurs when the response is empty, and since I can't also trace a request in server, I believe this is because No request is being sent.(Correct me if wrong).
So, my question is : Am I missing something | or is there anything wrong in the way I defined AsyncTask?
EDIT 1
PS: I am using an HTTPS URL in this AsyncTask
In Crashalitics you can log debug messages and stack traces from exceptions that were caught. So the answer for you is to proper collect this information, and then the issue will be clear
// catch everythin n log everything
} catch (ClientProtocolException e) {
Crashlytics.logException(e);
} catch (IOException e) {
Crashlytics.logException(e);
}
also put log messages before the possible crash
Crashlytics.log("Here is the async task that keeps giving me headache");
I am trying to insert data from android to MySQL but it does not show any error in logcat but displays the json message in the app.
Here is my PHP script.
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
require("config.inc.php");
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['userName']) && isset($_POST['userContact']) && isset($_POST['userAddress']) && isset($_POST['userStore']) && isset($_POST['userRequest'])) {
$userName = $_POST['userName'];
$userContact = $_POST['userContact'];
$userAddress = $_POST['userAddress'];
$userStore = $_POST['userStore'];
$userRequest = $_POST['userRequest'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO userrequests(userName, contactNumber, userAddress, storeList, requestBody) VALUES('$userName', '$userContact', '$userAddress', '$userStore', '$userRequest')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Product successfully created.";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "IsitdispllayingthusOops! An error occurred.";
// echoing JSON response
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
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, "utf-8"), 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");
Log.i("log_tag","Line reads: " + line);
}
// Close the input stream.
is.close();
// Convert the string builder data to an actual string.
json = sb.toString();
} 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);
} 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, "utf-8"), 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;
}
}
Here is my MainActivity.java
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();
}
}
}
}
And the error I am getting inside the emulator is this json message in my php script
$response["message"] = "IsitdispllayingthusOops! An error occurred.";
I couldn't find the reason why new row cannot be inserted into MySQL.
POST can not be used by external applications. You have to use GET instead.
I am working on an Android application that executes an http POST request, and the tutorial I followed was resulting in an android.os.NetworkOnMainThreadException
The original code was something like this.
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// 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();
} 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();
Log.e("JSON", json);
} 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;
}
}
And this class was invoked with this line.
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
After changing this to an AsyncTask class, the code looks like this.
class JSONParser extends AsyncTask<String, Void, JSONObject>{
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// variables passed in:
String url;
List<NameValuePair> params;
// constructor
public JSONParser(String url, List<NameValuePair> params) {
this.url = url;
this.params = params;
}
#Override
protected JSONObject doInBackground(String... args) {
// Making HTTP request
try {
// 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();
} catch (UnsupportedEncodingException 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();
Log.e("JSON", json);
} 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;
}
#Override
protected void onPostExecute(JSONObject jObj) {
return;
}
}
My question is, how do I return a JSONObject from this new AsyncTask class?I can see that jObj is being returned in doInBackground(), but I am not sure where it is being returned to.
What do I need to modify or how do I need to call my new JSONParser class so that it is returning a JSONObject?
Have a look at this code, it may give you an insight as to how to deal with the parsing of JSON objects. I am just posting the onPostExecute function for now because you seemed to have all the rest figured correctly.
As for your doubt as to where the data object from the doInBackground is returned, it is automatically sent to the onPostExecute where you can further on parse it.
#Override
protected void onPostExecute(JSONObject result)
{
try
{
JSONObject data = result.getJSONObject("data");
// whatever your JSON tag may be, in this case its data.
if (data.isNull("data"))
{
// action to handle null JSON object.
}
else
{
JSONArray jarray = data.getJSONArray("data");
int len=jarray.length();
for (int i = 0; i < jarray.length(); i++)
{
JSONObject obj = (JSONObject) jarray.get(i);
String instanceName = obj.getString("instanceName");
//extract data by whatever tag names you require, in this case instanceName.
}
}
}
catch (JSONException je)
{
je.printStackTrace();
Log.d(TAG, "Error: " + je.getMessage());
}
}
}
from your doInBackground Method
#Override
protected JSONObject doInBackground(String... args) {
return jObj;
}
your return your JsonObject to
#Override
protected void onPostExecute(JSONObject jObj) {
// Here you get your return JsonObject
}
An Async Task has 3 attribures
Params, the type of the parameters sent to the task upon execution.
Progress, the type of the progress units published during the background computation.
Result, the type of the result of the background computation.
The point you need to understand is that you are creating a object of Async Task Class While calling new JSONParser(loginURL, params);
The solution is that create a public result variable in your Async class and the call execute() on the object of class and then access the public object from the object.
I can see that jObj is being returned in doInBackground() but I am not
sure where it is being returned to.
The result of doinBackground() is received as a parameter in onPostExecute(). You are returning a json object in doinBackground() which is a parameter to onPostExecute().
#Override
protected void onPostExecute(JSONObject jObj) {
return;
}
Usage
new JSONParser().execute("url);
class JSONParser extends AsyncTask<String, Void, JSONObject>{
//string parameter to doInBackground()
//JSONObject - result returned in doInBackground() received as a param in onPostExecute()
}
You can also pass paramters to the constructor of your asynctask
new JSONParser("url",params).execute();
In your asynctask;
String url;
List<NameValuePair> params;
// constructor
public JSONParser(String url, List<NameValuePair> params) {
this.url = url;
this.params = params;
}
In order to avoid executing the http relating things in the UI thread, i migrated my code inside asynctask, before that, it was working fine on versions before 3.0 -- however, after literally copy pasting the code inside asynctask, it started to giving the invalid index, size is 0 exception. Whenever I need to use the method I am applying the call --
new dataRetrievalViaAsyncTask().execute(url, null, null); --
Whats wrong down there ?
class dataRetrievalViaAsyncTask extends AsyncTask<String, Void, Void>
{
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(String... f_url)
{
Log.i("tag", "inside doInBackground");
String url2 = f_url[0];
Log.i("tag", url2);
HttpClient httpclient = new DefaultHttpClient();
Log.i("tag", "done : HttpClient httpclient = new DefaultHttpClient();");
HttpPost httppost = new HttpPost(url2);
Log.i("tag", "done : HttpPost httppost = new HttpPost(url);");
try
{
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
Log.i("tag", "done : httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));");
HttpResponse response = httpclient.execute(httppost);
Log.i("tag", "done : HttpResponse response = httpclient.execute(httppost);");
HttpEntity entity = response.getEntity();
Log.i("tag", "done : HttpEntity entity = response.getEntity();");
is = entity.getContent();
Log.i("tag", "after : is = entity.getContent();");
} catch (Exception e)
{
Log.e("log_tag", "Error in http connection", e);
}
// convert response to string
return null;
}
protected void onPostExecute()
{
try
{
Log.i("tag","before : BufferedReader reader = new BufferedReader(new Inp");
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e)
{
Log.e("log_tag", "Error in http connection", e);
}
try
{
Log.i("tag", "before : jsons ");
jArray = new JSONArray(result);
JSONObject json_data = null;
Log.i("tag", Integer.toString(jArray.length()));
for (int i = 0; i < jArray.length(); i++)
{
json_data = jArray.getJSONObject(i);
uid = json_data.getInt("uid");
item1= json_data.getString("item1");
item2 = json_data.getString("item2");
item3 = json_data.getString("item3");
item4 = json_data.getString("item4");
item5 = json_data.getString("item5");
item6 = json_data.getString("item6");
favorited = json_data.getString("favorited");
currentList.add(new itemClass(uid, item1 item2)); //there is a constructor for this in the itemClass
itemClass toSendToOffline = new itemsClass(uid, item1, item2, item3, item4, item5, item6, favorited);
myDBHelper.insertFromOnlineToDBtoSendToOffline();
}
} catch (JSONException e1)
{
Toast.makeText(getBaseContext(), "Not Found", Toast.LENGTH_LONG).show();
} catch (ParseException e1)
{
e1.printStackTrace();
}
super.onPostExecute(null);
}
}
(mainly the code is stopping at --
HttpResponse response = httpclient.execute(httppost);
I can not see nameValuePairs variable initialized anywhere, which is actually causing problem.
class dataRetrievalViaAsyncTask extends AsyncTask<Void, Void, String>
{
String URL = "";
public dataRetrievalViaAsyncTask( String url )
{
URL = url;
}
#Override
protected void onPreExecute()
{
}
#Override
protected String doInBackground(Void... f_url)
{
String result="";
try
{
result=fetchdataFromServer(URL);
}
catch (JSONException e)
{
e.printStackTrace();
}
return result;
}
protected void onPostExecute(String result)
{
// See your results as string //result
}
public JSONObject getJsonObjectToRequestToServer(String plid) throws JSONException
{
JSONObject parms = new JSONObject();
parms.put("user_id", "");
parms.put("app_key", "xyz");
parms.put("secret", "abc");
parms.put("token", "");
parms.put("playurl", "1");
parms.put("mode", "playlistdetail");
parms.put("playlist_id", plid);
return parms;
}
public String fetchdataFromServer(String url) throws JSONException
{
String stringresponce = null;
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(URL);
JSONObject parms = getJsonObjectToRequestToServer("1");
StringEntity se;
se = new StringEntity(parms.toString());
httpPost.setEntity(se);
httpPost.setHeader("Content-type", "application/json");
#SuppressWarnings("rawtypes")
ResponseHandler responseHandler = new BasicResponseHandler();
stringresponce = httpClient.execute(httpPost, responseHandler);
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return stringresponce;
}
}
put this code in your code and pass arguments ass you need this is the way how i request to server and get json response as string from result variable pass arguments to your url as i passed by making json object then convert them to string
then execute like this............
dataRetrievalViaAsyncTask asyncTask=new dataRetrievalViaAsyncTask(Yoururl);
asyncTask.execute();
hope this will help if you have some issues please post here thanks......
I am doing an HttpPost to get data from a php server using async task. Basically the php script will either return a JSON array or null. It works fine when the json array is returned, however if the script returns null my if statement is not being picked up on and I am being returned this error:
Error parsing data org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray
This is a snippet of my script:
#Override
protected Void doInBackground(String... params) {
String url_select = "http://localhost/test.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("id", id));
try {
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null){
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
if(result == "null"){
this.progressDialog.dismiss();
startActivity(new Intent(viewRandom.this, allDone.class));
}else{
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++){
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
String id = Jasonobject.getString("id");
}
this.progressDialog.dismiss();
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Change if(result == "null") to if(result == null).
If you want to check for the string "null" do it with .equals(): if ("null".equals(result))
I am not sure if you really send a "null" string back from your server but anyway. As you might end returning null (not the string!), you should check for that, too.
Edit: Why is "null".equals(result) better than result.equals("null")? The answer is: the first one is null-safe which means it will not throw a NullPointerException when result is null. The second one will result in an exception in that case.
Instead of returning null Your Should try to return an Integer value to onPostExecute something like this
#Override
public Integer doInBackground(String...params){
.......
.......
return 1;
}
protected void onPostExecute(Integer v) {
if(v==1) {
}
}