I have been trying to follow this tutorial:http://www.androidhive.info/2012/01/android-login-and-registration-with-php-mysql-and-sqlite/. It is to create an android login app. I've read through the comments and it does not explicitly answer the reason why this error 500 server error is occurring and how to resolve it.
I researched and one site suggested to put the getJsonFromURL method
in an AsyncTask because it seems to be running on the main thread. However, this did not make a difference with the server error.
When the code below runs the Logcat reads out an internal server error 500. Which means the sever could not understand what was sent to it. I commented out this line in JSONParser.java:
httpPost.setEntity(new UrlEncodedFormEntity(params));
And the url works with the server and gets a 200 ok server response.
I can only assume that the way the name value pairs are being handled is wrong.
However, every example I found that uses List<NameValuePair>
to collect the values for the login
has the same implementation as the code below.
Can you look at the code below or suggest to me another way of getting the name value pairs to be sent by POST method to the server?
// JSONParser.java
package 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.HttpPost;
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(String url, List<NameValuePair> params) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
Log.v("name value pairs ",params.toString());
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
Log.v("Http Response",httpResponse.getStatusLine().toString());
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;
}
}
RegisterActivity.java:
package com.example.androidhive;
import org.json.JSONException;
import org.json.JSONObject;
import library.DatabaseHandler;
import library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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();
}
});
}
}
UserFunctions.java:
package 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.util.Log;
import android.content.Context;
public class UserFunctions {
private JSONParser jsonParser;
// Testing in Leobee.com
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "http://www.leobee.com/android/push/login/";
private static String registerURL = "http://www.leobee.com/android/push/login/index.php?";
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.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){
Log.v("register user", name+ " "+email +" " + password);
// Building Parameters
ArrayList<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
Log.v("url placed in json object", registerURL);
// Log.v("url placed in json object", params);
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
Log.v("JSON parser string", json.toString());
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;
}
}
Log cat 500 error with name value pairs:
05-27 05:47:07.342: V/register user(409): Name [email protected] pass
05-27 05:47:07.353: V/url placed in json object(409): http://www.leobee.com/android/push/login/index.php?
05-27 05:47:07.362: V/name value pairs(409): [tag=register, name=Name, [email protected], password=pass]
05-27 05:47:08.493: V/Http Response(409): HTTP/1.1 500 Internal Server Error
05-27 05:47:08.803: E/JSON Parser(409): Error parsing data org.json.JSONException: End of input at character 0 of
05-27 05:47:08.803: D/AndroidRuntime(409): Shutting down VM
05-27 05:47:08.803: W/dalvikvm(409): threadid=1: thread exiting with uncaught exception (group=0x40015560)
05-27 05:47:08.824: E/AndroidRuntime(409): FATAL EXCEPTION: main
05-27 05:47:08.824: E/AndroidRuntime(409): java.lang.NullPointerException
05-27 05:47:08.824: E/AndroidRuntime(409): at library.UserFunctions.registerUser(UserFunctions.java:68)
05-27 05:47:08.824: E/AndroidRuntime(409): at com.example.androidhive.RegisterActivity$1.onClick(RegisterActivity.java:55)
05-27 05:47:08.824: E/AndroidRuntime(409): at android.view.View.performClick(View.java:2485)
05-27 05:47:08.824: E/AndroidRuntime(409): at android.view.View$PerformClick.run(View.java:9080)
05-27 05:47:08.824: E/AndroidRuntime(409): at android.os.Handler.handleCallback(Handler.java:587)
05-27 05:47:08.824: E/AndroidRuntime(409): at android.os.Handler.dispatchMessage(Handler.java:92)
05-27 05:47:08.824: E/AndroidRuntime(409): at android.os.Looper.loop(Looper.java:130)
05-27 05:47:08.824: E/AndroidRuntime(409): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-27 05:47:08.824: E/AndroidRuntime(409): at java.lang.reflect.Method.invokeNative(Native Method)
05-27 05:47:08.824: E/AndroidRuntime(409): at java.lang.reflect.Method.invoke(Method.java:507)
05-27 05:47:08.824: E/AndroidRuntime(409): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-27 05:47:08.824: E/AndroidRuntime(409): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-27 05:47:08.824: E/AndroidRuntime(409): at dalvik.system.NativeStart.main(Native Method)
Logcat 200 ok with NO name value pairs:
05-27 05:51:39.863: D/dalvikvm(444): GC_EXTERNAL_ALLOC freed 70K, 49% free 2778K/5379K, external 2032K/2137K, paused 40ms
05-27 05:51:46.415: W/KeyCharacterMap(444): No keyboard for id 0
05-27 05:51:46.415: W/KeyCharacterMap(444): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
05-27 05:52:06.862: V/register user(444): no [email protected] url
05-27 05:52:06.862: V/url placed in json object(444): http://www.leobee.com/android/push/login/index.php?
05-27 05:52:06.883: V/name value pairs(444): [tag=register, name=no, [email protected], password=url]
05-27 05:52:07.893: V/Http Response(444): HTTP/1.1 200 OK
05-27 05:52:07.902: E/JSON(444): Access Deniedn
05-27 05:52:07.912: E/JSON Parser(444): Error parsing data org.json.JSONException: Value Access of type java.lang.String cannot be converted to JSONObject
05-27 05:52:07.912: D/AndroidRuntime(444): Shutting down VM
05-27 05:52:07.912: W/dalvikvm(444): threadid=1: thread exiting with uncaught exception (group=0x40015560)
05-27 05:52:07.923: E/AndroidRuntime(444): FATAL EXCEPTION: main
05-27 05:52:07.923: E/AndroidRuntime(444): java.lang.NullPointerException
05-27 05:52:07.923: E/AndroidRuntime(444): at library.UserFunctions.registerUser(UserFunctions.java:68)
05-27 05:52:07.923: E/AndroidRuntime(444): at com.example.androidhive.RegisterActivity$1.onClick(RegisterActivity.java:55)
05-27 05:52:07.923: E/AndroidRuntime(444): at android.view.View.performClick(View.java:2485)
05-27 05:52:07.923: E/AndroidRuntime(444): at android.view.View$PerformClick.run(View.java:9080)
05-27 05:52:07.923: E/AndroidRuntime(444): at android.os.Handler.handleCallback(Handler.java:587)
05-27 05:52:07.923: E/AndroidRuntime(444): at android.os.Handler.dispatchMessage(Handler.java:92)
05-27 05:52:07.923: E/AndroidRuntime(444): at android.os.Looper.loop(Looper.java:130)
05-27 05:52:07.923: E/AndroidRuntime(444): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-27 05:52:07.923: E/AndroidRuntime(444): at java.lang.reflect.Method.invokeNative(Native Method)
05-27 05:52:07.923: E/AndroidRuntime(444): at java.lang.reflect.Method.invoke(Method.java:507)
05-27 05:52:07.923: E/AndroidRuntime(444): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-27 05:52:07.923: E/AndroidRuntime(444): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-27 05:52:07.923: E/AndroidRuntime(444): at dalvik.system.NativeStart.main(Native Method)
It looks like you get an access denied error that makes your app crash when registering a user.
Try the folowing :