Wednesday, April 24, 2019

android - Error converting result java.lang.NullPointerException: lock == null



I am new to develop an android application. I have read a lot of related post regarding the question I was asking but the tips or solution from the post did not solve my problem. (Looking for the solution for a week already, really need help in order to proceed with my project) Thanks a lot...






import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;

import org.json.JSONException;
import org.json.JSONObject;

import com.example.aroma.slidingmenu.listener.JSONParser;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import android.widget.Toast;

public class ResultListFragment extends ListFragment {

TextView resultView;


public ResultListFragment(){}

//progress dialog

private ProgressDialog pDialog;

//creating JSON Parser object
JSONParser jParser = new JSONParser();

ArrayList> customerList;

//url to get the customer list
private static String url_search="http://192.168.1.3:80/test/getAllCustomers.php";


//JSON Node names
private static final String TAG_SUCCESS="success";
private static final String TAG_CUSTOMER="customers";
private static final String TAG_FNAME="FirstName";
private static final String TAG_LNAME="LastName";
private static final String TAG_AGE="Age";
private static final String TAG_MOBILE="Mobile";

//product JSONArray
JSONArray customers=null;

//search key value
public String searchKey;


@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.activity_searchresult_list, container, false);


Toast.makeText(getActivity(),"Search result in listview",Toast.LENGTH_LONG).show();

Intent intent = getActivity().getIntent();
searchKey = intent.getStringExtra("message");
//Toast.makeText(getActivity(), searchKey, Toast.LENGTH_LONG).show();

//hshmap for listview
customerList= new ArrayList>();



//Loading customer in background thread
new LoadCustomer().execute();

return rootView;
}

@Override
public void onViewCreated (View view, Bundle savedInstanceState) {

ListView lv =getListView();


lv.setOnItemSelectedListener(new OnItemSelectedListener(){

@Override
public void onItemSelected(AdapterView parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String iid=((TextView)view.findViewById(R.id.FirstName)).getText().toString();
}


@Override
public void onNothingSelected(AdapterView parent) {
// TODO Auto-generated method stub

}
});
}

/**
* Background Async Task to load customers by making HTTP request

* */
class LoadCustomer extends AsyncTask{
/**
* Before starting background thread show progress dialog
* */
@Override
protected void onPreExecute(){
super.onPreExecute();
pDialog=new ProgressDialog(getActivity()); //pDialog=new ProgressDialog(ResultListFragment.this);
pDialog.setMessage("Loading customers. Please wait...");

pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}

/**
* getting customers url
* **/
protected String doInBackground(String... args){
//Building Parameters

List params= new ArrayList();
//value captured from previous intent
params.add(new BasicNameValuePair("FirstName", searchKey));
//getting JSON string from url
JSONObject json = jParser.makeHttpRequest(url_search, "GET", params);
//check your log cat for JSON response
Log.d("Search customer", json.toString());

try{
//checking for SUCCESS TAG

int success=json.getInt(TAG_SUCCESS);

if(success==1){
//product found
//Getting array of products
customers=json.getJSONArray(TAG_CUSTOMER);

//looping through all products
for(int i=0;i map=new HashMap();


//adding each child node to HashMap key =>value
map.put(TAG_FNAME, fname);
map.put(TAG_LNAME, lname);
map.put(TAG_AGE, age);
map.put(TAG_MOBILE, mobile);

//adding HashList to ArrayList
customerList.add(map);
}
}else{

//no customer found
//do sth
Handler handler = new Handler(getActivity().getMainLooper());
handler.post( new Runnable(){
public void run(){
Toast.makeText(getActivity(),"no customer found" ,Toast.LENGTH_LONG).show();
}
});
}
}catch (JSONException e){

e.printStackTrace();
}

//return "success";
return null;
}

/**
* After completing background task dismiss the progress dialog
* **/

protected void onPostExecute(String file_url){
//dimiss the dialog after getting the related customer
pDialog.dismiss();
getActivity().runOnUiThread(new Runnable(){
public void run(){
/**
* updating parsed JSON data into ListView
* **/
ListAdapter adapter =new SimpleAdapter(
getActivity(), customerList,

R.layout.list_item, new String[]{ TAG_FNAME, TAG_LNAME, TAG_AGE, TAG_MOBILE},
new int[]{R.id.FirstName,R.id.LastName,R.id.Age,R.id.Mobile});
//updating listview
setListAdapter(adapter);
}
});

}

}



}



JSONParser.java






package com.example.aroma.slidingmenu.listener;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;http://stackoverflow.com/editing-help

import org.apache.http.HttpEntity;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;

import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";


// constructor
public JSONParser() {

}

// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List params) {


// Making HTTP request
try {

// check for request method
if(method.equals("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.equals("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();

String all=EntityUtils.toString(httpEntity);
Log.d("response",all);
}



} 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;

}
}



getAllCustomers.php







$response = array();
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("testdatabase", $con);


$FirstName=$_GET["FirstName"];
$result = mysql_query("SELECT * FROM customer where FirstName like '%$FirstName%' ");


if(mysql_num_rows($result)>0){
// looping through all results
// products node
$response["customers"] = array();


while ($row = mysql_fetch_array($result)) {
// temp user array
$customers = array();
$customers["FirstName"] = $row["FirstName"];
$customers["LastName"] = $row["LastName"];
$customers["Age"] = $row["Age"];
$customers["Mobile"] = $row["Mobile"];

// push single product into final response array
array_push($response["customers"], $customers);

}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no products found
$response["success"] = 0;
$response["message"] = "No products found";


// echo no users JSON
echo json_encode($response);
}




Error that I saved from Logcat:






02-12 17:17:50.599: E/Buffer Error(13636): Error converting result java.lang.NullPointerException: lock == null
02-12 17:17:50.599: E/JSON Parser(13636): Error parsing data org.json.JSONException: End of input at character 0 of
02-12 17:17:50.604: E/AndroidRuntime(13636): FATAL EXCEPTION: AsyncTask #4
02-12 17:17:50.604: E/AndroidRuntime(13636): java.lang.RuntimeException: An error occured while executing doInBackground()
02-12 17:17:50.604: E/AndroidRuntime(13636): at android.os.AsyncTask$3.done(AsyncTask.java:299)
02-12 17:17:50.604: E/AndroidRuntime(13636): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
02-12 17:17:50.604: E/AndroidRuntime(13636): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
02-12 17:17:50.604: E/AndroidRuntime(13636): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
02-12 17:17:50.604: E/AndroidRuntime(13636): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)

02-12 17:17:50.604: E/AndroidRuntime(13636): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
02-12 17:17:50.604: E/AndroidRuntime(13636): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
02-12 17:17:50.604: E/AndroidRuntime(13636): at java.lang.Thread.run(Thread.java:838)
02-12 17:17:50.604: E/AndroidRuntime(13636): Caused by: java.lang.NullPointerException
02-12 17:17:50.604: E/AndroidRuntime(13636): at com.example.aroma.slidingmenu.ResultListFragment$LoadCustomer.doInBackground(ResultListFragment.java:136)
02-12 17:17:50.604: E/AndroidRuntime(13636): at com.example.aroma.slidingmenu.ResultListFragment$LoadCustomer.doInBackground(ResultListFragment.java:1)
02-12 17:17:50.604: E/AndroidRuntime(13636): at android.os.AsyncTask$2.call(AsyncTask.java:287)
02-12 17:17:50.604: E/AndroidRuntime(13636): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
02-12 17:17:50.604: E/AndroidRuntime(13636): ... 4 more



Answer



Try call asynctask in onActivityCreated



 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {

View rootView = inflater.inflate(R.layout.activity_searchresult_list, container, false);


return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);

Toast.makeText(getActivity(),"Search result in listview",Toast.LENGTH_LONG).show();

Intent intent = getActivity().getIntent();

searchKey = intent.getStringExtra("message");
//Toast.makeText(getActivity(), searchKey, Toast.LENGTH_LONG).show();

//hshmap for listview
customerList= new ArrayList>();


//Loading customer in background thread
new LoadCustomer().execute();


}

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...