I am trying to create a simple login and registration activity in Android.
I am getting the errors
Error converting result java.lang.nullpointerexception,error parsing
data org.json.JSONException.
Below is my code :
JSONPARSER
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 method
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;
}
}
USERFUNCTIONS:
public class UserFunctions {
private JSONParser jsonParser;
// Testing in localhost using wamp or xampp
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "http://49.249.85.221/android_api/";
private static String registerURL = "http://49.249.85.221/android_api/";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* #param email
* #param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
String method=new String();
JSONObject json = jsonParser.makeHttpRequest(loginURL,method, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* #param name
* #param email
* #param password
* */
public JSONObject registerUser(String name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
String method=new String();
// getting JSON Object
JSONObject json = jsonParser.makeHttpRequest(registerURL,method, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
REGISTERACTIVITY:
public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private class MyAsyncTask extends AsyncTask<String, Void, JSONObject> {
protected JSONObject doInBackground(String... params) {
UserFunctions userFunction = new UserFunctions();
if (params.length != 3)
return null;
JSONObject json = userFunction.registerUser(params[0], params[1], params[2]);
return json;
}
protected void onPostExecute(JSONObject json) {
// check for login response
try {
if (json != null && json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
UserFunctions userFunction = new UserFunctions();
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
new MyAsyncTask().execute(name, email, password);
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
When I ran debugger it pointed to the line if (json.getString(KEY_SUCCESS) != null)
in RegisterActivity. I am clueless as to where I might be wrong. Please guide me on this.
LOGCAT:
10-28 22:40:27.422: D/dalvikvm(373): GC_EXTERNAL_ALLOC freed 78K, 52% free 2599K/5379K, external 897K/1038K, paused 190ms
10-28 22:40:32.000: W/KeyCharacterMap(373): No keyboard for id 0
10-28 22:40:32.000: W/KeyCharacterMap(373): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
10-28 22:40:45.879: E/Buffer Error(373): Error converting result java.lang.NullPointerException
10-28 22:40:45.899: E/Buffer Error(373): Error converting result java.lang.NullPointerException
10-28 22:40:45.983: E/JSON Parser(373): Error parsing data org.json.JSONException: End of input at character 0 of
10-28 22:40:45.989: D/AndroidRuntime(373): Shutting down VM
10-28 22:40:45.989: W/dalvikvm(373): threadid=1: thread exiting with uncaught exception (group=0x40015560)
10-28 22:40:46.049: E/AndroidRuntime(373): FATAL EXCEPTION: main
10-28 22:40:46.049: E/AndroidRuntime(373): java.lang.NullPointerException
10-28 22:40:46.049: E/AndroidRuntime(373): at com.example.androidhive.RegisterActivity$1.onClick (RegisterActivity.java:112)
10-28 22:40:46.049: E/AndroidRuntime(373): at android.view.View.performClick(View.java:2485)
10-28 22:40:46.049: E/AndroidRuntime(373): at android.view.View$PerformClick.run(View.java:9080)
10-28 22:40:46.049: E/AndroidRuntime(373): at android.os.Handler.handleCallback(Handler.java:587)
10-28 22:40:46.049: E/AndroidRuntime(373): at android.os.Handler.dispatchMessage(Handler.java:92)
10-28 22:40:46.049: E/AndroidRuntime(373): at android.os.Looper.loop(Looper.java:123)
10-28 22:40:46.049: E/AndroidRuntime(373): at android.app.ActivityThread.main(ActivityThread.java:3683)
10-28 22:40:46.049: E/AndroidRuntime(373): at java.lang.reflect.Method.invokeNative(Native Method)
10-28 22:40:46.049: E/AndroidRuntime(373): at java.lang.reflect.Method.invoke(Method.java:507)
10-28 22:40:46.049: E/AndroidRuntime(373): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:839)
10-28 22:40:46.049: E/AndroidRuntime(373): at c om.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
10-28 22:40:46.049: E/AndroidRuntime(373): at dalvik.system.NativeStart.main(Native Method)
10-28 22:40:46.309: E/JSON Parser(373): Error parsing data org.json.JSONException: End of input at character 0 of
10-28 22:40:50.289: I/Process(373): Sending signal. PID: 373 SIG: 9
The main issue is resolved after implementing the solution suggested by Martin.
I am facing some other errors now. LOGCAT is attached below.
10-28 23:17:19.183: D/dalvikvm(449): GC_EXTERNAL_ALLOC freed 78K, 52% free 2599K/5379K, external 897K/1038K, paused 232ms
10-28 23:17:23.259: W/KeyCharacterMap(449): No keyboard for id 0
10-28 23:17:23.269: W/KeyCharacterMap(449): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
10-28 23:17:46.379: E/Buffer Error(449): Error converting result java.lang.NullPointerException
10-28 23:17:46.389: E/Buffer Error(449): Error converting result java.lang.NullPointerException
10-28 23:17:46.389: E/JSON Parser(449): Error parsing data org.json.JSONException: End of input at character 0 of
10-28 23:17:46.409: E/JSON Parser(449): Error parsing data org.json.JSONException: End of input at character 0 of
That might be because the key not even exist, do this before calling json.getString("key"); method:
JSONObject json = yourJSON;
if(json != null && !json.isNull(KEY_SUCCESS)){
//Wahetever you need
String value = json.getString(KEY_SUCCESS);
if(value != null && value.length > 0){
//You will fall here only if there's a value...
}
}
Notice that you first need to make sure that the key actually exist, otherway it could throw a JSONException...
Hope this helps...
Regards!
Related
I know that there are many posts about this particular error, but none of them are solving my issue and I am new to Android development. As a result of this error, I am unable to see the data in a listView for an app.
The following is my code:
public class JSONBuilderActivity extends ListActivity {
private ProgressDialog pDialog;
//URL to get JSON
private static String url = "http://"";
//JSON Node names
private static final String TAG_CARS = "cars"; //root
private static final String TAG_CARID = "car_id";
JSONArray carid = null; //Initializes JSON array
static String response = null;
//Hashmap for ListView
ArrayList<HashMap<String, String>>caridList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView lv = getListView();
//Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Gets values from selected ListItem
String cars = ((TextView) view.findViewById(R.id.cars)).getText().toString();
String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
Intent in = new Intent(JSONBuilderActivity.this, MainActivity.class);
//getApplicationContext()
//sending data to new activity
in.putExtra("TAG_CARS", cars);
in.putExtra("TAG_CARID", car_id);
startActivity(in);
}
});
//Calls async task to get json
new GetCars().execute();
}
public class ServiceHandler {
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Makes service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Makes service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,ArrayList<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
//Checks http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
//Adds post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
//Appends params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
/*
* Async task class to get json by making HTTP call
*/
private class GetCars extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caridList = new ArrayList<HashMap<String, String>>();
//Shows progress dialog
pDialog = new ProgressDialog(JSONBuilderActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
//Creates service handler class instance
ServiceHandler sh = new ServiceHandler();
//Makes a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
//Prints the json response in the log
Log.d("GetCars response: ", "> " + jsonStr);
//Prints array in app
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
//Hashmap for single match
HashMap<String, String> matchGetCars = new HashMap<String, String>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Dismisses the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updates parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item,
new String[]{TAG_CARID}, new int[]{R.id.car_id});
setListAdapter(adapter);
Log.v("List parsed", caridList.toString());
}
}
}
I realize that an error is occurring near the following:
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
//Hashmap for single match
HashMap<String, String> matchGetCars = new HashMap<String, String>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
Here is the logcat data:
org.json.JSONException: No value for car_id
07-20 15:31:30.424 7567-7677/com.example.justin.myapplication W/System.err﹕ at org.json.JSONObject.get(JSONObject.java:354)
07-20 15:31:30.424 7567-7677/com.example.justin.myapplication W/System.err﹕ at org.json.JSONObject.getString(JSONObject.java:510)
07-20 15:31:30.424 7567-7677/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONBuilderActivity$GetCars.doInBackground(JSONBuilderActivity.java:202)
07-20 15:31:30.424 7567-7677/com.example.justin.myapplication W/System.err﹕ at com.example.justin.myapplication.JSONBuilderActivity$GetCars.doInBackground(JSONBuilderActivity.java:155)
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at android.os.AsyncTask$2.call(AsyncTask.java:287)
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.FutureTask.run(FutureTask.java:234)
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
07-20 15:31:30.431 7567-7677/com.example.justin.myapplication W/System.err﹕ at java.lang.Thread.run(Thread.java:856)
07-20 15:31:30.455 7567-7567/com.example.justin.myapplication V/List parsed﹕ []
A brief view of what the JSON looks like:
{"cars":[{"id":1,"CarID":"20946"....so on...
I appreciate if any suggestions could be thoroughly explained and demonstrated as to why this error is occurring. Thank you greatly.
Replace
private static final String TAG_CARID = "car_id";
with
private static final String TAG_CARID = "CarID";
You JSONArray has key "CarID", whereas you are searching for "car_id".
Hope this helps :)
"cars" is jsonArray in the jsonObject. You must get the array first and then extract values from it. I cant give you code example right now, because I am currently on my phone.
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)
I need help in my application. In that application I want to do login and registration but whenever I press the login and register buttons, it crash the whole application. I'm using xampp as server.
RegisterActivity.java
protected EditText mUsername;
protected EditText mUserEmail;
protected EditText mUserPassword;
protected Button mRegisterButton;
// 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://127.0.0.1/webservice/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_register);
//initialize
mUsername = (EditText)findViewById(R.id.usernameRegisterEditText);
mUserEmail = (EditText)findViewById(R.id.emailRegisterEditText);
mUserPassword = (EditText)findViewById(R.id.passwordRegisterEditText);
mRegisterButton = (Button)findViewById(R.id.registerButton);
//listen to register button click
mRegisterButton.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(RegisterActivity.this);
pDialog.setMessage("Creating User...");
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 = mUsername.getText().toString();
String email = mUserEmail.getText().toString();
String password = mUserPassword.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
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(RegisterActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
JSONParser
------------
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();
} 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, "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;
}
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="sergio.applicationone"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".LoginActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".HomepageActivity"
android:label="HomepageActivity" >
</activity>
<activity
android:name=".RegisterActivity"
android:label="RegisterActivity" >
</activity>
</application>
</manifest>
------logcat
12-30 13:33:34.341 6574-6574/sergio.applicationone E/﹕ Device driver API match
Device driver API version: 23
User space API version: 23
12-30 13:33:34.341 6574-6574/sergio.applicationone E/﹕ mali: REVISION=Linux-r3p2-01rel3 BUILD_DATE=Fri Mar 21 13:52:50 KST 2014
12-30 13:34:35.676 6574-6804/sergio.applicationone E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
12-30 13:34:40.731 6574-6804/sergio.applicationone E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
12-30 13:34:56.866 6574-6574/sergio.applicationone I/Choreographer﹕ Skipped 1267 frames! The application may be doing too much work on its main thread.
12-30 13:35:24.221 6574-6804/sergio.applicationone W/dalvikvm﹕ threadid=11: thread exiting with uncaught exception (group=0x41de5c08)
12-30 13:35:24.361 6574-6574/sergio.applicationone I/Choreographer﹕ Skipped 1593 frames! The application may be doing too much work on its main thread.
12-30 13:35:24.451 6574-6804/sergio.applicationone E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
Process: sergio.applicationone, PID: 6574
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 sergio.applicationone.RegisterActivity$CreateUser.doInBackground(RegisterActivity.java:118)
at sergio.applicationone.RegisterActivity$CreateUser.doInBackground(RegisterActivity.java:77)
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)
12-30 13:35:25.971 6574-6574/sergio.applicationone E/WindowManager﹕ android.view.WindowLeaked: Activity sergio.applicationone.RegisterActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView{425e22d8 V.E..... R......D 0,0-639,128} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:468)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:267)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:69)
at android.app.Dialog.show(Dialog.java:289)
at sergio.applicationone.RegisterActivity$CreateUser.onPreExecute(RegisterActivity.java:91)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:587)
at android.os.AsyncTask.execute(AsyncTask.java:535)
at sergio.applicationone.RegisterActivity.onClick(RegisterActivity.java:73)
at android.view.View.performClick(View.java:4640)
at android.view.View$PerformClick.run(View.java:19425)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
put all this code outside doinbackground
String username = mUsername.getText().toString();
String email = mUserEmail.getText().toString();
String password = mUserPassword.getText().toString();
I already know what a nullpointerexception is, but Im not able to find it in my own code. I hope you guys can see it
here is the log:
12-04 06:21:36.866 1687-1687/com.example.thelegendaryturk.theneckoptimizer E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.thelegendaryturk.theneckoptimizer, PID: 1687
java.lang.NullPointerException
at com.example.thelegendaryturk.theneckoptimizer.RegisterActivity$1.onClick(RegisterActivity.java:63)
at android.view.View.performClick(View.java:4438)
at android.view.View$PerformClick.run(View.java:18422)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Here is the RegisterActivity.java(line 63 is highlighted with ***)
public class RegisterActivity extends Activity {
Button btnRegister;
Button btnLinkToLogin;
EditText inputFullName;
EditText inputEmail;
EditText inputPassword;
TextView registerErrorMsg;
// JSON Response node names
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
private static String KEY_UID = "uid";
private static String KEY_NAME = "name";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.registerName);
inputEmail = (EditText) findViewById(R.id.registerEmail);
inputPassword = (EditText) findViewById(R.id.registerPassword);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.btnLinkToLoginScreen);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
// Register Button Click event
btnRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputFullName.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
*** if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous data in database
userFunction.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_NAME), json_user.getString(KEY_EMAIL), json.getString(KEY_UID), json_user.getString(KEY_CREATED_AT));
// Launch Dashboard Screen
Intent dashboard = new Intent(getApplicationContext(), DashboardActivity.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
Here is the UserFunction.java:
public class UserFunctions {
public JSONParser jsonParser;
private static String loginURL = "http://10.0.2.2/android_login_api/";
private static String registerURL = "http://10.0.2.2/android_login_api/";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* #param email
* #param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
JSONObject json;
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* #param name
* #param email
* #param password
* */
public JSONObject registerUser(String name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
I think there is a simple solution but I am wasting my time for more than two hours now. Any help is welcome
First check json then check KEY_SUCCESS :
if (json!=null && json.getString(KEY_SUCCESS) != null) {
your problem is in either :
JSONObject json = userFunction.registerUser(name, email, password);
OR:
json.getString(KEY_SUCCESS)
even if you don't get the corresponding JSONObject from the userFunction or the String called KEY_SUCCESS is referenced to a null value.
I guess your problem is in Userfunction.registerUser()
json = jsonParser.getJSONFromUrl(loginURL, params);
step in here at debugging or check by code if json == null
if(json == null)
system.out.println("Error json object == null");
i think you really should find out why the jsonParser returns null at this point. Perhaps der url is not available?
I'm developing an android app which sends username and password to MySQL database and receives response ("success" or "error") in the login activity. But the returning JSONObject is null. Below are the codes
userauth.php
<?php
//Connecting to mysql db
include("db.php");
//Check for POST request
//if(isset($_POST['tag']) && $_POST['tag'] !=''){
//Get tag
// $tag = $_POST['tag'];
//}
//Getting username and password from android via JSON
$username = $_POST['username'];
$password = $_POST['password'];
//Creating respose array
$respose = array("tag" => $tag, "success" => 1, "error" =>0);
//Getting data from json
//$username='asanka102';
//$password='asanka102';
//Querying mysql database against userauth table for user auth
$sql = "SELECT * FROM userauth WHERE username='$username' AND password='$password'";
$qry = mysql_query($sql);
$fin_result = mysql_num_rows($qry);
//Returning true when user exists & return false when user doen's exist
//if$fin_result > 0(){
// return true;
//}else{
// return false;
//}
if($fin_result > 0){
//User found, login should be granted
$response["success"] = 1;
echo json_encode($response);
}else{
//User not found, login shold be prohibited
$response["error"] = 0;
$response["error_msg"] = 'Invalid login';
echo json_encode($response);
}
?>
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etUsername = (EditText) findViewById(R.id.et_username);
etPass = (EditText) findViewById(R.id.et_password);
errorTxt = (TextView) findViewById(R.id.text_invalid_input);
loginButton = (Button) findViewById(R.id.button_login);
loginButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
new GetPassword().execute();
}
});
}
private class GetPassword extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
String username = etUsername.getText().toString();
String password = etPass.getText().toString();
UserFunctions userFunctions = new UserFunctions();
JSONObject json = userFunctions.loginUser(username, password);
//Do other things
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
if (pDialog.isShowing())
pDialog.dismiss();
}
}
UserFunctions.java
public class UserFunctions {
private JSONParser jsonParser;
private static String login_url = "http://192.168.100.172/android/userauth.php";
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* #param username
* #param password
* */
public JSONObject loginUser(String username, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(login_url, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
}
JSONParser.java
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
// Empty constructor
}
// function get json from url
// by making HTTP POST or GET mehtod
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;
}
}
The logcat gives this
02-11 12:29:10.457: E/Buffer Error(13927): Error converting result java.lang.NullPointerException: lock == null
02-11 12:29:10.457: E/JSON Parser(13927): Error parsing data org.json.JSONException: End of input at character 0 of
02-11 12:29:10.457: W/dalvikvm(13927): threadid=11: thread exiting with uncaught exception (group=0x41ba5ba8)
02-11 12:29:10.467: D/dalvikvm(13927): GC_FOR_ALLOC freed 280K, 2% free 17142K/17456K, paused 10ms, total 11ms
02-11 12:29:10.477: E/AndroidRuntime(13927): FATAL EXCEPTION: AsyncTask #1
02-11 12:29:10.477: E/AndroidRuntime(13927): Process: collector.lbfinance, PID: 13927
02-11 12:29:10.477: E/AndroidRuntime(13927): java.lang.RuntimeException: An error occured while executing doInBackground()
02-11 12:29:10.477: E/AndroidRuntime(13927): at android.os.AsyncTask$3.done(AsyncTask.java:300)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
02-11 12:29:10.477: E/AndroidRuntime(13927): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.lang.Thread.run(Thread.java:841)
02-11 12:29:10.477: E/AndroidRuntime(13927): Caused by: java.lang.NullPointerException
02-11 12:29:10.477: E/AndroidRuntime(13927): at collector.lbfinance.MainActivity$GetPassword.doInBackground(MainActivity.java:102)
02-11 12:29:10.477: E/AndroidRuntime(13927): at collector.lbfinance.MainActivity$GetPassword.doInBackground(MainActivity.java:1)
02-11 12:29:10.477: E/AndroidRuntime(13927): at android.os.AsyncTask$2.call(AsyncTask.java:288)
02-11 12:29:10.477: E/AndroidRuntime(13927): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
02-11 12:29:10.477: E/AndroidRuntime(13927): ... 4 more
Is $fin_result returning rows?
Try the following
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();
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;
What does the logcat say by your is.close(); json = sb.toString(); Log.e("JSON", json); which is in JSONParser.java.