App crash when no internet connection - java

so i was trying to create a simple login app connected to my wampserver by following tutorial on internet and it works fine, but the problem occurs when my device is not connected to internet and i can't figure it out why, but i'm pretty sure the problem is in my asynctask.
so i need help anyone, thanks.
here's my login.java
package id.wanda.smkkkristenimmanuelii;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener {
private EditText user, pass;
private Button mSubmit;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.1.110:80/smkkimmanuel2/login.php";
// JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_LEVEL_AKSES = "level_akses";
private static final String TAG_JABATAN = "jabatan";
public static String level_akses = "5", jabatan = "", namaUser = "";
public static String login_status = "false";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
// setup buttons
mSubmit = (Button) findViewById(R.id.btnLogin);
// register listeners
mSubmit.setOnClickListener(this);
}
#Override
public void onBackPressed() {
Login.this.finish();
startActivity(new Intent(this, MenuUtama.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnLogin:
new AttemptLogin().execute();
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
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 levelaks, jabat;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
levelaks = json.getString(TAG_LEVEL_AKSES);
jabat = json.getString(TAG_JABATAN);
level_akses = levelaks;
jabatan = jabat;
namaUser = username;
login_status = "true";
Intent i = new Intent(Login.this, MenuUtama.class);
finish();
startActivity(i);
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(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
and here's my JSONParser.java :
package id.wanda.smkkkristenimmanuelii;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
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.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() {
}
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;
}
}
here's my crash report:
05-19 09:56:44.040: E/AndroidRuntime(24861): FATAL EXCEPTION: AsyncTask #1
05-19 09:56:44.040: E/AndroidRuntime(24861): Process: id.wanda.smkkkristenimmanuelii, PID: 24861
05-19 09:56:44.040: E/AndroidRuntime(24861): java.lang.RuntimeException: An error occured while executing doInBackground()
05-19 09:56:44.040: E/AndroidRuntime(24861): at android.os.AsyncTask$3.done(AsyncTask.java:300)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
05-19 09:56:44.040: E/AndroidRuntime(24861): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.lang.Thread.run(Thread.java:841)
05-19 09:56:44.040: E/AndroidRuntime(24861): Caused by: java.lang.NullPointerException
05-19 09:56:44.040: E/AndroidRuntime(24861): at id.wanda.smkkkristenimmanuelii.Login$AttemptLogin.doInBackground(Login.java:138)
05-19 09:56:44.040: E/AndroidRuntime(24861): at id.wanda.smkkkristenimmanuelii.Login$AttemptLogin.doInBackground(Login.java:1)
05-19 09:56:44.040: E/AndroidRuntime(24861): at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-19 09:56:44.040: E/AndroidRuntime(24861): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-19 09:56:44.040: E/AndroidRuntime(24861): ... 4 more
05-19 09:56:44.040: W/ActivityManager(571): Force finishing activity id.wanda.smkkkristenimmanuelii/.Login
05-19 09:56:44.050: E/IMGSRV(192): :0: PVRDRMOpen: TP3, ret = 107

The best way to approach this is to use a ConnectivityManager to ascertain whether or not your device is online/has connectivity to the internet before attempting to do anything that requires a connection.
This way you can display a screen advising as such when offline, or attempt to run your code when online. From a user point of view this is favourable to your app just crashing when there is no connection available.

the problem is makeHttpRequest is returning null
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST", params);
you can simply add an extra catch to your try/catch
catch (NullPointerException e) {
e.printStackTrace();
}
Probably better practice is to check your connection with ConnectivityManager before you make the request

Change
private static final String LOGIN_URL = "http://192.168.1.110:80/smkkimmanuel2/login.php";
to
private static final String LOGIN_URL = "http://127.0.0.1:80/smkkimmanuel2/login.php";
The reason for this issue is that your IP is bound to that connection and when you are not connected then it's not your IP anymore.

The Best way to to avoid crash is just check the device if it is connected to the internet.
*ifConnected * : Do your process
*ifNotConnected *: Then display a dialog box to user that he/she is not connected to the internet.
This is what I do in the development.
This might help you :-
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
You need to add
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

The problem is solved now, thanks to #Karl and #Modge,
first, thanks to #Modge, to prevent the app from crashing, just add an catch exception in AttempLogin class, the doInBackground method which is inside Login.java, and it will keep showing the process dialog "Attempting to Login" :
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String levelaks, jabat;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
levelaks = json.getString(TAG_LEVEL_AKSES);
jabat = json.getString(TAG_JABATAN);
level_akses = levelaks;
jabatan = jabat;
namaUser = username;
login_status = "true";
Intent i = new Intent(Login.this, MenuUtama.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}catch (NullPointerException e) {
e.printStackTrace();
//THIS IS IT.
}
return null;
}
and to complete the app, i add ConnectivityManager as suggested by #Karl, by following the tutorial here http://www.androidhive.info/2012/07/android-detect-internet-connection-status/. after creating the ConnectionDetector class, i tweak my Login class and it will be like this :
package id.wanda.smkkkristenimmanuelii;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener {
private EditText user, pass;
private Button mSubmit;
//ADDED
// flag for Internet connection status
Boolean isInternetPresent = false;
// Connection detector class
ConnectionDetector cd;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// php login script location:
private static final String LOGIN_URL = "http://192.168.1.110:80/smkkimmanuel2/login.php";
// JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
private static final String TAG_LEVEL_AKSES = "level_akses";
private static final String TAG_JABATAN = "jabatan";
public static String level_akses = "5", jabatan = "", namaUser = "";
public static String login_status = "false";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// setup input fields
user = (EditText) findViewById(R.id.username);
pass = (EditText) findViewById(R.id.password);
//ADDED
cd = new ConnectionDetector(getApplicationContext());
// setup buttons
mSubmit = (Button) findViewById(R.id.btnLogin);
// register listeners
mSubmit.setOnClickListener(this);
}
#Override
public void onBackPressed() {
Login.this.finish();
startActivity(new Intent(this, MenuUtama.class));
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnLogin:
//ADDED
// get Internet status
isInternetPresent = cd.isConnectingToInternet();
// check for Internet status
if (isInternetPresent) {
// Internet Connection is Present
// make HTTP requests
showAlertDialog(Login.this, "Internet Connection",
"You have internet connection", true);
/*new AttemptLogin().execute();*/
} else {
// Internet connection is not present
// Ask user to connect to Internet
showAlertDialog(Login.this, "No Internet Connection",
"You don't have internet connection.", false);
}
break;
default:
break;
}
}
//ADDED
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message, Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
// Setting alert dialog icon
alertDialog.setIcon((status) ? R.drawable.success : R.drawable.failed);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
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 levelaks, jabat;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(LOGIN_URL, "POST",
params);
// check your log for json response
Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
levelaks = json.getString(TAG_LEVEL_AKSES);
jabat = json.getString(TAG_JABATAN);
level_akses = levelaks;
jabatan = jabat;
namaUser = username;
login_status = "true";
Intent i = new Intent(Login.this, MenuUtama.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
} else {
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}catch (NullPointerException 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(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
and it works like a charm, thanks for the help guys. I really appreciate it.

Related

Login functionality for andrioid app using mysql

I am coding the login functionality for my android app where it check against my online sql and present the user to the page if login is successful.
But I keep having this error:
E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #5 at these lines: Log.d("Login attempt", json.toString()) and class AttemptLogin extends AsyncTask
How do I solve it? Attached below is the code. Thanks in advance!
JSONParser.java
package com.test.qingyong.test;
/**
* Created by QingYong on 09/08/2015.
*/
import org.apache.http.HttpEntity;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import org.apache.http.HttpResponse;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
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.json.JSONException;
import org.json.JSONObject;
import android.util.Log;
public class JSONParser {
static InputStream is = null;
static JSONObject jsonObj ;
static String json = "";
// default no argument constructor for jsonpaser class
public JSONParser() {
}
public JSONObject getJSONFromUrl(final String url) {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
// Executing POST request & storing the response from server locally.
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 {
// Create a BufferedReader
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
// Declaring string builder
StringBuilder str = new StringBuilder();
// string to store the JSON object.
String strLine = null;
// Building while we have string !equal null.
while ((strLine = reader.readLine()) != null) {
str.append(strLine + "\n");
}
// Close inputstream.
is.close();
// string builder data conversion to string.
json = str.toString();
} catch (Exception e) {
Log.e("Error", " something wrong with converting result " + e.toString());
}
// Try block used for pasrseing String to a json object
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("json Parsering", "" + e.toString());
}
// Returning json Object.
return jsonObj;
}
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Make HTTP request
try {
// checking request method
if(method == "POST"){
// now defaultHttpClient object
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 str = new StringBuilder();
String strLine = null;
while ((strLine = reader.readLine()) != null) {
str.append(strLine + "\n");
}
is.close();
json = str.toString();
} catch (Exception e) {
}
// now will try to parse the string into JSON object
try {
jsonObj = new JSONObject(json);
} catch (JSONException e) {
}
return jsonObj;
}
}
Login.java
package com.test.qingyong.test;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Login extends Activity implements OnClickListener{
private EditText user, pass;
private Button bLogin;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://powerbankk.16mb.com/test.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
bLogin = (Button)findViewById(R.id.login);
bLogin.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
// here we have used, switch case, because on Login activity you may //also want to show registration button, so if the user is new ! we can go the //registration activity , menu than this we could also do this without switch //case.
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting for Login...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
int success;
String username = user.getText().toString();
String password = pass.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// checking log for json response
Log.d("Login attempt", json.toString());
// success tag for json
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Successfully Login!", json.toString());
Intent ii = new Intent(Login.this,OtherActivity.class);
finish();
// this finish() method is used to tell android os that we are done with current //activity now! Moving to menu activity
startActivity(ii);
return json.getString(TAG_MESSAGE);
}else{
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* Once the background process is done we need to Dismiss the progress dialog asap
* **/
protected void onPostExecute(String message) {
pDialog.dismiss();
if (message != null){
Toast.makeText(Login.this, message, Toast.LENGTH_LONG).show();
}
}
}
}
Login.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="#+id/login"
android:layout_width="118dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/password"
android:layout_alignRight="#+id/password"
android:layout_below="#+id/password"
android:text="login" />
<EditText
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/password"
android:ems="10"
android:focusable="true"
android:hint="Enter username"
android:imeOptions="actionNext"
/>
<EditText
android:id="#+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/username"
android:layout_centerHorizontal="true"
android:ems="10"
android:hint="Enter Password"
android:imeOptions="actionDone"
/>
</RelativeLayout>
test.php
<?php
mysql_connect("mysql.hostinger.in","username","password");
$db= mysql_select_db("db");
$password=$_POST["password"];
$username=$_POST["username"];
if (!empty($_POST)) {
if (empty($_POST['username']) || empty($_POST['password'])) {
// Create some data that will be the JSON response
$response["success"] = 0;
$response["message"] = "One or both of the fields are empty .";
//die is used to kill the page, will not let the code below to be executed. It will also
//display the parameter, that is the json data which our android application will parse to be //shown to the users
die(json_encode($response));
}
$query = " SELECT * FROM test WHERE username = '$username'and password='$password'";
$sql1=mysql_query($query);
$row = mysql_fetch_array($sql1);
if (!empty($row)) {
$response["success"] = 1;
$response["message"] = "You have been sucessfully login";
die(json_encode($response));
}
else{
$response["success"] = 0;
$response["message"] = "invalid username or password ";
die(json_encode($response));
}
}
else{
$response["success"] = 0;
$response["message"] = " One or both of the fields are empty ";
die(json_encode($response));
}
mysql_close();
?>
Try using Volley or Retrofit .They are faster and error handling is a lot easier than async task.

Android WebServices PHP MYSQL

I am trying to save student data from my android app to MYSQL Database via Webservices. But the problem is it is not saving data on the database .. The Php file is programmed in a manner that it will display JSON as output
$response["success"] = 1;
$response["message"] = "Student record has been saved successfully";
else
$response["success"] = 0;
$response["message"] = "Oops! An error occurred.";
PHP File returning "Oops! An error occurred " in the application..
My PHP File For Creating New Records Is:
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// check for required fields
if (isset($_POST['rollno']) && isset($_POST['sname']) && isset($_POST['regid']) &&isset($_POST['class'])&& isset($_POST['fname'])&& isset($_POST['fno'])&& isset($_POST['mname'])&& isset($_POST['mno'])&& isset($_POST['route'])&& isset($_POST['timings'])&& isset($_POST['latitude'])&& isset($_POST['longitude'])) {
$rollno = $_POST['rollno'];
$sname = $_POST['sname'];
$regid = $_POST['regid'];
$class = $_POST['class'];
$fname = $_POST['fname'];
$fno = $_POST['fno'];
$mname = $_POST['mname'];
$mno = $_POST['mno'];
$route = $_POST['route'];
$timings = $_POST['timings'];
$latitude = $_POST['latitude'];
$longitude = $_POST['longitude'];
// include db connect class
require_once('/home/a9447544/public_html/school/db_connect.php');
// connecting to db
$db = new DB_CONNECT();
// mysql inserting a new row
$result = mysql_query("INSERT INTO school(rollno, sname,regid, class, fname, fno, mname, mno, route, timings, latitude, longitude) VALUES('$rollno', '$sname','$regid', '$class', '$fname', '$fno', '$mname', '$mno', '$route', '$timings', '$latitude', '$longitude')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "Student record has been saved successfully";
// echoing JSON response
echo json_encode($response);
} else {
// failed to insert row
$response["success"] = 0;
$response["message"] = "Oops! 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);
}
?>
Android Java File For Creating New Record..
package com.example.akshay.productdata;
/**
* Created by Akshay on 8/9/2015.
*/
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class NewProductActivity extends Activity {
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
EditText RollNo, SName, Class, FatherName, FatherNo, MotherName, MotherNo, RouteNo, Timings;
String ROLLNO, SNAME, ROUTE, FATHERNAME, FATHERNO, MOTHERNAME, MOTHERNO, TIMINGS, CLASS, REGID;
// url to create new product
private static String url_create_product = "http://www.funvilla.in/school/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_product);
// Edit Text
RollNo = (EditText) findViewById(R.id.ET_ROLL);
SName = (EditText) findViewById(R.id.ET_SNAME);
Class = (EditText) findViewById(R.id.ET_CLASS);
FatherName = (EditText) findViewById(R.id.ET_FatherName);
FatherNo = (EditText) findViewById(R.id.ET_FATHERNO);
MotherName = (EditText) findViewById(R.id.ET_MotherName);
MotherNo = (EditText) findViewById(R.id.ET_MotherNo);
RouteNo = (EditText) findViewById(R.id.ET_Route);
Timings = (EditText) findViewById(R.id.ET_Timings);
// Create button
Button btnCreateProduct = (Button) findViewById(R.id.BT_SaveStudentRecord);
// button click event
btnCreateProduct.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.CUPCAKE)
#Override
public void onClick(View view) {
// creating new product in background thread
ROLLNO = RollNo.getText().toString();
SNAME = SName.getText().toString();
CLASS = Class.getText().toString();
FATHERNAME = FatherName.getText().toString();
FATHERNO = FatherNo.getText().toString();
MOTHERNAME = MotherName.getText().toString();
MOTHERNO = MotherNo.getText().toString();
ROUTE = RouteNo.getText().toString();
TIMINGS = Timings.getText().toString();
new CreateNewProduct().execute();
}
});
}
/**
* Background Async Task to Create new product
*/
#TargetApi(Build.VERSION_CODES.CUPCAKE)
class CreateNewProduct extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewProductActivity.this);
pDialog.setMessage("Creating Product..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating product
*/
protected String doInBackground(String... args) {
String LAT = "78.555454";
String LONG = "78.545545";
REGID = "jefk3je3eh";
Log.e("ROLLNO==========", ROLLNO);
Log.e("SNAME==========", SNAME);
Log.e("REGID==========", REGID);
Log.e("CLASS==========", CLASS);
Log.e("FATHERNAME==========", FATHERNAME);
Log.e("FATHERNO==========", FATHERNO);
Log.e("MOTHERNAME==========", MOTHERNAME);
Log.e("MOTHERNO==========", MOTHERNO);
Log.e("ROUTE==========", ROUTE);
Log.e("Timings==========", TIMINGS);
Log.e("LAT==========", LAT);
Log.e("LONG==========", LONG);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("rollno", ROLLNO));
params.add(new BasicNameValuePair("sname", SNAME));
params.add(new BasicNameValuePair("regid", REGID));
params.add(new BasicNameValuePair("class", CLASS));
params.add(new BasicNameValuePair("fname", FATHERNAME));
params.add(new BasicNameValuePair("fno", FATHERNO));
params.add(new BasicNameValuePair("mname", MOTHERNAME));
params.add(new BasicNameValuePair("mno", MOTHERNO));
params.add(new BasicNameValuePair("route", ROUTE));
params.add(new BasicNameValuePair("timings", TIMINGS));
params.add(new BasicNameValuePair("latitude", LAT));
params.add(new BasicNameValuePair("longitude", LONG));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_product,
"POST", params);
// check log cat fro response
Log.e("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), AllProductsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} 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 done
pDialog.dismiss();
}
}
}
JSONParser.java - For Establishing connection and Saving and retrieving Records
package com.example.akshay.productdata;
/**
* Created by Akshay on 8/9/2015.
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
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.json.JSONException;
import org.json.JSONObject;
import android.os.StrictMode;
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<NameValuePair> params) {
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// 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();
Log.e("=======" , 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;
}
}
Logcat:
08-22 00:39:39.640 7279-7452/com.example.akshay.productdata E/ROLLNO==========﹕ 77
08-22 00:39:39.640 7279-7452/com.example.akshay.productdata E/SNAME==========﹕ lkskl
08-22 00:39:39.640 7279-7452/com.example.akshay.productdata E/REGID==========﹕ jefk3je3eh
08-22 00:39:39.640 7279-7452/com.example.akshay.productdata E/CLASS==========﹕ mmm
08-22 00:39:39.640 7279-7452/com.example.akshay.productdata E/FATHERNAME==========﹕ sdf
08-22 00:39:39.640 7279-7452/com.example.akshay.productdata E/FATHERNO==========﹕ 54554
08-22 00:39:39.640 7279-7452/com.example.akshay.productdata E/MOTHERNAME==========﹕ dfd
08-22 00:39:39.640 7279-7452/com.example.akshay.productdata E/MOTHERNO==========﹕ 544
08-22 00:39:39.640 7279-7452/com.example.akshay.productdata E/ROUTE==========﹕ 54
08-22 00:39:39.640 7279-7452/com.example.akshay.productdata E/Timings==========﹕ 5445
08-22 00:39:39.640 7279-7452/com.example.akshay.productdata E/LAT==========﹕ 78.555454
08-22 00:39:39.640 7279-7452/com.example.akshay.productdata E/LONG==========﹕ 78.545545
08-22 00:39:40.300 7279-7452/com.example.akshay.productdata E/=======﹕ {"success":0,"message":"Oops! An error occurred."}
08-22 00:39:40.300 7279-7452/com.example.akshay.productdata E/Create Response﹕ {"success":0,"message":"Oops! An error occurred."}
UPDATE:
I've tried to run the query on MYSQL Database But the following error occurred
Error
SQL query:
INSERT INTO school( rollno, sname, regid, class, fname, fno, mname, mno, route, timings, latitude, longitude )
VALUES ( 12, Akshay, mk34, MCA, Ajay Sood, 686, Manju Sood, 5454, 401, 55, 78.545545, 79.5421081 )
MySQL said: Documentation
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Sood, 686, Manju Sood, 5454, 401, 55, 78.545545, 79.5421081)' at line 1
Please use single quote '' for varchar fields in SQL query.

JsonParser Android Error

I have two login applications with exactly the same code that calls the json parser class. the first one works fine (you can try it from the link, username admin and pass:123) however the second class gives a null pointer exception on the json.getInt(TAG_SUCCESS);
This is the JsonParser Class:
package com.example.mysqltest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
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.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<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 Working-fine Class:
package com.example.mysqltest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Login extends Activity implements OnClickListener{
private EditText user, pass;
private Button mSubmit, mRegister;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//php login script location:
//testing from a real server:
private static final String LOGIN_URL = "http://www.eshteghel.comlu.com/dbservice/login.php";
//JSON element ids from repsonse of php script:
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.login);
//setup input fields
user = (EditText)findViewById(R.id.username);
pass = (EditText)findViewById(R.id.password);
//setup buttons
mSubmit = (Button)findViewById(R.id.login);
mRegister = (Button)findViewById(R.id.register);
//register listeners
mSubmit.setOnClickListener(this);
mRegister.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.login:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
*/
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Attempting login...");
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 = user.getText().toString();
String password = pass.getText().toString();
try {
/* try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(password.getBytes(),0,password.length());
password = new BigInteger(1,md5.digest()).toString(16);
//System.out.println("Signature: "+signature);
} catch (final NoSuchAlgorithmException e) {
e.printStackTrace();
}*/
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
//Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
//Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
//Log.d("Login Successful!", json.toString());
Intent i = new Intent(Login.this, ReadComments.class);
finish();
startActivity(i);
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(Login.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
While the class that gives the null pointer exception:
package test.example.com.test;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Sign_in extends FragmentActivity implements View.OnClickListener{
Button btSignUp,btLogin;
EditText etUser,etPass;
// Progress Dialog
private ProgressDialog nDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
//testing from a real server:
private static final String LOGIN_URL = "http://www.eshteghel.comlu.com/dbservice/login.php";
//JSON element ids from repsonse of php script:
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sign_in);
etUser = (EditText) findViewById(R.id.etUser);
etPass = (EditText) findViewById(R.id.etPass);
btSignUp = (Button) findViewById(R.id.btSignUp);
btLogin = (Button) findViewById(R.id.btLogin);
btSignUp.setOnClickListener(this);
btLogin.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_sign_in, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void showDialog(){
ClientDialog cd = new ClientDialog();
cd.show(getSupportFragmentManager(), "DialogFragment");
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.btLogin:
new AttemptLogin().execute();
break;
case R.id.btSignUp:
showDialog();
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
nDialog = new ProgressDialog(Sign_in.this);
nDialog.setTitle("Checking Network");
nDialog.setMessage("Loading..");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
// Check for success tag
int success;
String username = etUser.getText().toString();
String password = etPass.getText().toString();
try {
/*try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(password.getBytes(),0,password.length());
password = new BigInteger(1,md5.digest()).toString(16);
//System.out.println("Signature: "+signature);
} catch (final NoSuchAlgorithmException e) {
e.printStackTrace();
}*/
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
//Log.d("request!", "starting");
// getting product details by making HTTP request
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
// check your log for json response
//Log.d("Login attempt", json.toString());
// json success tag
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
//Log.d("Login Successful!", json.toString());
Intent i = new Intent(Sign_in.this, Company.class);
finish();
startActivity(i);
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
nDialog.dismiss();
if (file_url != null){
Toast.makeText(Sign_in.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}

Error converting result java.lang.NullPointerException: lock == null and Error parsing data org.json.JSONException: End of input at character 0 of

Here is the relevant log-cat information:
11-09 16:45:47.354 5149-5149/com.example.apex.apex E/Buffer Error﹕ Error converting result java.lang.NullPointerException: lock == null
11-09 16:45:47.354 5149-5149/com.example.apex.apex E/JSON Parser﹕ Error parsing data org.json.JSONException: End of input at character 0 of
11-09 16:45:47.354 5149-5149/com.example.apex.apex D/AndroidRuntime﹕ Shutting down VM
11-09 16:45:47.354 5149-5149/com.example.apex.apex W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41bd9ce0)
Process: com.example.apex.apex, PID: 5149
java.lang.NullPointerException
at com.example.apex.apex.RegisterActivity$1.onClick(RegisterActivity.java:70)
at android.view.View.performClick(View.java:4445)
at android.view.View$PerformClick.run(View.java:18446)
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:5146)
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:732)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
at dalvik.system.NativeStart.main(Native Method)
11-09 16:46:36.686 5149-5149/com.example.apex.apex I/Process﹕ Sending signal. PID: 5149 SIG: 9
RegisterActivity.java:
I am new to Java and Android development, therefore I am initially hard-coding data to communicate with a remote server through PHP.
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class RegisterActivity extends Activity {
private static String KEY_SUCCESS = "success";
private static String KEY_ERROR = "error";
private static String KEY_ERROR_MSG = "error_msg";
Button btnRegister;
TextView registerErrorMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
if(Build.VERSION.SDK_INT > 8)
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
// import all assets
btnRegister = (Button) findViewById(R.id.btnRegister);
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// inputs
String fName = "John";
String lName = "Smith";
String email = "someone#example.com";
String password = "123345";
String location = "Sligo";
String dob = "07-10-1993";
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
java.util.Date date = null;
try {
date = sdf.parse(dob);
} catch (ParseException e) {
e.printStackTrace();
}
java.sql.Date sqlDob = new Date(date.getTime());
String gender = "Male";
int height = 128;
double weight = 78.5;
CyclistFunctions cyclistFunction = new CyclistFunctions();
JSONObject json = cyclistFunction.registerCyclist(fName, lName, email, password,
location, sqlDob, gender, height, weight);
// check for register response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1) {
// user successfully registered
// store user details in SQLite DB
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// clear all previous data in database
finish();
} else {
registerErrorMsg.setText("Error in registration occurred! :/");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.register, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
activity_register.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="com.example.apex.apex.RegisterActivity">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/btnRegister"
android:text="Click!"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/btnRegister"
android:layout_marginTop="50dp"/>
JSONParser.java
package com.example.apex.apex;
import android.util.Log;
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.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
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) {
// make HTTP request
try {
// creates a new HTTP client from parameters and a connection manager
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 {
// buffer input from is
BufferedReader reader = new BufferedReader(new InputStreamReader
(is, HTTP.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 to parse the string to JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
CyclistFunctions.java
package com.example.apex.apex;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
public class CyclistFunctions {
private JSONParser jsonParser;
private static final String registerURL = "http://127.0.0.1/apexdb/include/db_functions.php/";
private static String register_tag = "register";
// constructor
public CyclistFunctions() {
jsonParser = new JSONParser();
}
/**
* make register request
*/
public JSONObject registerCyclist(String first_name, String last_name, String email_address,
String password, String location, Date birth_date, String gender,
int height_cm, double weight_kg) {
// build parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("first_name", first_name));
params.add(new BasicNameValuePair("last_name", last_name));
params.add(new BasicNameValuePair("email_address", email_address));
params.add(new BasicNameValuePair("password", password));
params.add(new BasicNameValuePair("location", location));
params.add(new BasicNameValuePair("birth_date", String.valueOf(birth_date)));
params.add(new BasicNameValuePair("gender", gender));
params.add(new BasicNameValuePair("height_cm", String.valueOf(height_cm)));
params.add(new BasicNameValuePair("weight_kg", String.valueOf(weight_kg)));
// fetch JSON object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
}
db_functions.php
<?php
class DB_Functions {
private $db;
// constructor
function __construct() {
require_once 'db_connect.php';
// connecting to database
$this->db = new db_connect();
$this->db->connect();
}
// destructor
function __destruct() {
}
/**
Storing new cyclist
return user details
**/
public function storeCyclist($first_name, $last_name, $email_address,
$password, $birth_date, $gender, $height_cm, $weight_kg) {
$hash = $this->hashSSHA($password);
$encrypted_password = $hash["encrypted"]; // password
$salt = $hash["salt"]; // salt
$result = mysqli_query("INSERT INTO cyclist (first_name, last_name, email_address,
encrypted_password, salt, birth_date, gender, height_cm, weight_kg, date_created)
VALUES ('$first_name', '$last_name', '$email_address', '$encrypted_password', '$salt', '$birth_date',
'$gender', '$height_cm', '$weight_kg', NOW())");
if($result) {
// successfully inserted cyclist into database
$response["success"] = 1;
$response["message"] = "Cyclist succesfully created";
// echo JSON response
echo json_encode($response);
} else {
// insert fail
$response["success"] = 1;
$response["message"] = "Woops, something went wrong - failed to create new cyclist! :(";
}
}
public function userExists($email_address) {
$result = mysqli_query("SELECT email_address from cyclist WHERE email_address = '$email_address'");
$no_of_rows = mysqli_num_rows($result);
if($no_of_rows > 0) {
// user exists
return true;
} else {
// user exists
return false;
}
}
/**
encrypt password
#param password
returns salt
**/
public function hashSSHA($password) {
$salt = sha1(rand());
$salt = substr($salt, 0, 10);
$encrypted = base64_encode(sha1($password . $salt, true) . $salt);
$hash = array("salt" => $salt, "encrypted" => $encrypted);
return $hash;
}
/**
decrypting password
#params salt, password
returns hash string
**/
public function checkSSHA($salt, $password) {
$hash = base64_encode(sha1($password . $salt, true) . $salt);
return $hash;
}
}
?>
DB_Connect.php
<?php
class DB_Connect {
// constructor
function __construct() {
}
// destructor
function __destruct() {
// $this->close();
}
// connecting to database
public function connect() {
require_once 'config.php';
// connecting to mysqli
$con = new mysqli_connect($db_host, $db_user, $db_password, $db_name);
// check connection
if(mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " .mysqli_connect_errno();
}
// return db handler
return $con;
}
public function close() {
// close connection
mysqli_close();
}
}
?>
You have not given value to registerErrorMsg due to this you are getting null pointer.
registerErrorMsg = (TextView) findViewById(R.id.registerErrorMsg);
i think this will solve your problem.
You must post your json model and cyclistic functions in order to identify exact issues.
This line is creating errors
JSONObject json = cyclistFunction.registerCyclist(fName, lName, email, password,
location, sqlDob, gender, height, weight);
It has to be like this
String result_json = cyclistFunction.registerCyclist(fName, lName, email, password,location, sqlDob, gender, height, weight);
if (result_json != null) {
try {
JSONObject jsonObj = new JSONObject(result_json );
if (jsonObj != null) {
String res = json.getString(KEY_SUCCESS);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}

NullPointerException in Android JSONParser

I have an android application that crashes whenever I press the Login button; I keep getting a Null Pointer Exception in my JSONParser. I really hope you can help.
Here is my UserFunctions.java:
package com.example.sabre9.library;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.content.Context;
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://10.0.2.2/Sabre1/";
//private static String registerURL = "http://10.0.2.2/Sabre1/";
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));
JSONObject json = jsonParser.makeHttpRequest(loginURL, "POST", params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Register 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.makeHttpRequest(registerURL, "POST", 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;
}
}
JSONParser.java:
package com.example.sabre9.library;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;
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.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<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;
}
}
And here are my logcat errors:
02-13 03:15:01.921: E/Buffer Error(1263): Error converting result java.lang.NullPointerException: lock == null
02-13 03:15:01.931: E/JSON Parser(1263): Error parsing data org.json.JSONException: End of input at character 0 of
02-13 03:15:02.891: E/Buffer Error(1263): Error converting result java.lang.NullPointerException: lock == null
02-13 03:15:02.891: E/JSON Parser(1263): Error parsing data org.json.JSONException: End of input at character 0 of
Edit: My LoginActivity.java:
package com.example.sabre9;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.example.sabre9.library.DatabaseHandler;
import com.example.sabre9.library.UserFunctions;
public class LoginActivity extends Activity {
Button btnLogin;
//Button btnLinkToRegister;
EditText inputEmail;
EditText inputPassword;
TextView loginErrorMsg;
// 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 != 2)
return null;
JSONObject json = userFunction.loginUser(params[0], params[1]);
return json;
}
protected void onPostExecute(JSONObject json) {
try {
if (json != null && json.getString(KEY_SUCCESS) != null) {
loginErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully logged in
// Store user details in SQLite Database
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
// Clear all previous From 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 Main Screen
Intent main = new Intent(getApplicationContext(), MainActivity.class);
// Close all views before launching Dashboard
main.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(main);
// Close Login Screen
finish();
}else{
// Error in login
loginErrorMsg.setText("Incorrect username/password");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
// Importing all assets like buttons, text fields
inputEmail = (EditText) findViewById(R.id.loginEmail);
inputPassword = (EditText) findViewById(R.id.loginPassword);
btnLogin = (Button) findViewById(R.id.btnLogin);
//btnLinkToRegister = (Button) findViewById(R.id.btnLinkToRegisterScreen);
loginErrorMsg = (TextView) findViewById(R.id.login_error);
// Login button Click Event
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
new MyAsyncTask().execute(email, password);
}
});
//Link to Register Screen
/*btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
finish();
}
});*/
}
}
Your java.lang.NullPointerException: lock == null occurs >= Android 3.0 because networking is not allowed on the main(UI) thread, unless overridden via StrictMode policy. Try:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Note that as a result, httpClient.execute(httpPost); will lock up the system pretty bad as it waits for the response. (Instead, you might do that in an AsyncTask so it doesn't lock up the main thread.) Hope this helps.
I have fixed this error. Seems that through a very embarassing brain fart I have forgotten to include in my manifest file the internet permissions needed. Also, I have tweaked my php files a little. Thank you for the answers anyways :)

Categories

Resources