NullPointerException android app - java

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?

Related

Android app just Crashes- Json is Null

I have checked the forum of how to correct NullPointer errors, however I am struggling, therefore could someone please offer me a helping hand. I have checked the post. What is a NullPointerException, and how do I fix it?. Still cannot find my solution please advise and help.
error message what the problem is: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference.
json is null when I execute line 214. This also means I have a call to onPostExecute passing a null object as argument. I have debugged my app and still cannot find the error message could you please help or advise me how I can fix this from happening.
CatLog - Error Messages
E/JSON Parser﹕ Error parsing data org.json.JSONException: Value
2015-12-09 of type java.lang.String cannot be converted to JSONObject
E/AndroidRuntime﹕ FATAL EXCEPTION: mainPID: 2386
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on
a null object reference
at com.app.tourist.Register$ProcessRegister.onPostExecute(Register.java:214
at com.app.tourist.Register$ProcessRegister.onPostExecute(Register.java:171)
private class ProcessRegister extends AsyncTask<String, String, JSONObject> { - Line 171: Gving Error Here.
if (json.getString(KEY_SUCCESS) != null) { - Line 214: Giving Error.
Register.Java File
public class Register extends Activity {
/**
* JSON Response node names.
**/
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_USERNAME = "uname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static String KEY_ERROR = "error";
/**
* Defining layout items.
**/
EditText inputFirstName;
EditText inputLastName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
ImageButton btnRegister;
TextView registerErrorMsg;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
/**
* Defining all layout items
**/
inputFirstName = (EditText) findViewById(R.id.fname);
inputLastName = (EditText) findViewById(R.id.lname);
inputUsername = (EditText) findViewById(R.id.uname);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.pword);
btnRegister = (ImageButton) findViewById(R.id.Registerbtn);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
/**
* Register Button click event.
* A Toast is set to alert when the fields are empty.
* Another toast is set to alert Username must be 5 characters.
**/
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
{
if ( inputUsername.getText().toString().length() > 4 ){
NetAsync(view);
}
else
{
Toast.makeText(getApplicationContext(),
"Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),
"One or more fields are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(Register.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args){
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessRegister().execute();
}
else{
nDialog.dismiss();
registerErrorMsg.setText("Error in Network Connection");
}
}
}
private class ProcessRegister extends AsyncTask<String, String, JSONObject> {
/**
* Defining Process dialog
**/
private ProgressDialog pDialog;
String email,password,fname,lname,uname;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputUsername = (EditText) findViewById(R.id.uname);
inputPassword = (EditText) findViewById(R.id.pword);
fname = inputFirstName.getText().toString();
lname = inputLastName.getText().toString();
email = inputEmail.getText().toString();
uname= inputUsername.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(Register.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Registering ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
/**
* Checks for success message.
**/
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
pDialog.setTitle("Getting Data");
pDialog.setMessage("Loading Info");
registerErrorMsg.setText("Successfully Registered");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Removes all the previous data in the SQlite database
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
* Stores registered data in SQlite Database
* Launch Registered screen
**/
Intent registered = new Intent(getApplicationContext(), Registered.class);
/**
* Close all views before launching Registered screen
**/
registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(registered);
finish();
}
else if (Integer.parseInt(red) ==2){
pDialog.dismiss();
registerErrorMsg.setText("User already exists");
}
else if (Integer.parseInt(red) ==3){
pDialog.dismiss();
registerErrorMsg.setText("Invalid Email id");
}
}
else{
pDialog.dismiss();
registerErrorMsg.setText("Error occured in registration");
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
public void NetAsync(View view){
new NetCheck().execute();
}}
UserFuction.java File
/**
* Function to Register
**/
public JSONObject registerUser(String fname, String lname, String email, String uname, String password){
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("fname", fname));
params.add(new BasicNameValuePair("lname", lname));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("uname", uname));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(registerURL,params);
return json;
}
As the line suggests, you also need to check if the object
json
is null or not, if it is null then there is no point to check if it contains any object or not.
To avoid it, you must make sure that json object is not null and even if it is null you should modify the condition as below:
if (json != null && json.getString(KEY_SUCCESS) != null)
Hope it helps..

NullPointerException on Json.getString() - Android app crashes [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I am trying to make a Register system for android. It registers users into the database and they receive an email confirmation, however the application crashes and closes.
I have checked the forum of how to correct NullPointer errors, however I am struggling, therefore could someone please offer me a helping hand. I have checked the post .What is a Null Pointer Exception, and how do I fix it?. Still cannot find my solution please advise and help.
CatLog - Error Messages
E/JSON Parser﹕ Error parsing data org.json.JSONException: Value
2015-12-09 of type java.lang.String cannot be converted to JSONObject
E/AndroidRuntime﹕ FATAL EXCEPTION: mainPID: 2386
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on
a null object reference
at com.app.tourist.Register$ProcessRegister.onPostExecute(Register.java:214
at com.app.tourist.Register$ProcessRegister.onPostExecute(Register.java:171)
private class ProcessRegister extends AsyncTask<String, String, JSONObject> { - Line 171: Gving Error Here.
if (json.getString(KEY_SUCCESS) != null) { - Line 214: Giving Error.
Register.Java File
public class Register extends Activity {
/**
* JSON Response node names.
**/
private static String KEY_SUCCESS = "success";
private static String KEY_UID = "uid";
private static String KEY_FIRSTNAME = "fname";
private static String KEY_LASTNAME = "lname";
private static String KEY_USERNAME = "uname";
private static String KEY_EMAIL = "email";
private static String KEY_CREATED_AT = "created_at";
private static String KEY_ERROR = "error";
/**
* Defining layout items.
**/
EditText inputFirstName;
EditText inputLastName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
ImageButton btnRegister;
TextView registerErrorMsg;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.register);
/**
* Defining all layout items
**/
inputFirstName = (EditText) findViewById(R.id.fname);
inputLastName = (EditText) findViewById(R.id.lname);
inputUsername = (EditText) findViewById(R.id.uname);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.pword);
btnRegister = (ImageButton) findViewById(R.id.Registerbtn);
registerErrorMsg = (TextView) findViewById(R.id.register_error);
/**
* Register Button click event.
* A Toast is set to alert when the fields are empty.
* Another toast is set to alert Username must be 5 characters.
**/
btnRegister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if ( ( !inputUsername.getText().toString().equals("")) && ( !inputPassword.getText().toString().equals("")) && ( !inputFirstName.getText().toString().equals("")) && ( !inputLastName.getText().toString().equals("")) && ( !inputEmail.getText().toString().equals("")) )
{
if ( inputUsername.getText().toString().length() > 4 ){
NetAsync(view);
}
else
{
Toast.makeText(getApplicationContext(),
"Username should be minimum 5 characters", Toast.LENGTH_SHORT).show();
}
}
else
{
Toast.makeText(getApplicationContext(),
"One or more fields are empty", Toast.LENGTH_SHORT).show();
}
}
});
}
/**
* Async Task to check whether internet connection is working
**/
private class NetCheck extends AsyncTask<String,String,Boolean>
{
private ProgressDialog nDialog;
#Override
protected void onPreExecute(){
super.onPreExecute();
nDialog = new ProgressDialog(Register.this);
nDialog.setMessage("Loading..");
nDialog.setTitle("Checking Network");
nDialog.setIndeterminate(false);
nDialog.setCancelable(true);
nDialog.show();
}
#Override
protected Boolean doInBackground(String... args){
/**
* Gets current device state and checks for working internet connection by trying Google.
**/
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected()) {
try {
URL url = new URL("http://www.google.com");
HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
urlc.setConnectTimeout(3000);
urlc.connect();
if (urlc.getResponseCode() == 200) {
return true;
}
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return false;
}
#Override
protected void onPostExecute(Boolean th){
if(th == true){
nDialog.dismiss();
new ProcessRegister().execute();
}
else{
nDialog.dismiss();
registerErrorMsg.setText("Error in Network Connection");
}
}
}
private class ProcessRegister extends AsyncTask<String, String, JSONObject> {
/**
* Defining Process dialog
**/
private ProgressDialog pDialog;
String email,password,fname,lname,uname;
#Override
protected void onPreExecute() {
super.onPreExecute();
inputUsername = (EditText) findViewById(R.id.uname);
inputPassword = (EditText) findViewById(R.id.pword);
fname = inputFirstName.getText().toString();
lname = inputLastName.getText().toString();
email = inputEmail.getText().toString();
uname= inputUsername.getText().toString();
password = inputPassword.getText().toString();
pDialog = new ProgressDialog(Register.this);
pDialog.setTitle("Contacting Servers");
pDialog.setMessage("Registering ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... args) {
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
/**
* Checks for success message.
**/
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
String red = json.getString(KEY_ERROR);
if(Integer.parseInt(res) == 1){
pDialog.setTitle("Getting Data");
pDialog.setMessage("Loading Info");
registerErrorMsg.setText("Successfully Registered");
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
JSONObject json_user = json.getJSONObject("user");
/**
* Removes all the previous data in the SQlite database
**/
UserFunctions logout = new UserFunctions();
logout.logoutUser(getApplicationContext());
db.addUser(json_user.getString(KEY_FIRSTNAME),json_user.getString(KEY_LASTNAME),json_user.getString(KEY_EMAIL),json_user.getString(KEY_USERNAME),json_user.getString(KEY_UID),json_user.getString(KEY_CREATED_AT));
/**
* Stores registered data in SQlite Database
* Launch Registered screen
**/
Intent registered = new Intent(getApplicationContext(), Registered.class);
/**
* Close all views before launching Registered screen
**/
registered.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pDialog.dismiss();
startActivity(registered);
finish();
}
else if (Integer.parseInt(red) ==2){
pDialog.dismiss();
registerErrorMsg.setText("User already exists");
}
else if (Integer.parseInt(red) ==3){
pDialog.dismiss();
registerErrorMsg.setText("Invalid Email id");
}
}
else{
pDialog.dismiss();
registerErrorMsg.setText("Error occured in registration");
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
public void NetAsync(View view){
new NetCheck().execute();
}}
UserFuction.java File
/**
* Function to Register
**/
public JSONObject registerUser(String fname, String lname, String email, String uname, String password){
// Building Parameters
List params = new ArrayList();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("fname", fname));
params.add(new BasicNameValuePair("lname", lname));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("uname", uname));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(registerURL,params);
return json;
}
Apperantly following line retuns null. Please check it.
JSONObject json = userFunction.registerUser(fname, lname, email, uname, password);

Android error converting result java.lang.nullpointerexception

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!

Database cannot be connected

I m trying to create an application using eclipse. in the user-register page , after I entered all the required data, and click the submit button, the message " Unfortunately, your eclipse has been stopped". what does this message means and how to solve it?
public class UserRegister extends Activity {
JSONParser jsonParser = new JSONParser();
EditText inputName;
EditText inputUsername;
EditText inputEmail;
EditText inputPassword;
RadioButton button1;
RadioButton button2;
Button button3;
int success = 0;
// url to create new product
private static String url_register_user = "http://192.168.1.100/MEMS/add_user.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_register);
// Edit Text
inputName = (EditText) findViewById(R.id.nameTextBox);
inputUsername = (EditText) findViewById(R.id.usernameTextBox);
inputEmail = (EditText) findViewById(R.id.emailTextBox);
inputPassword = (EditText) findViewById(R.id.pwTextBox);
// Create button
//RadioButton button1 = (RadioButton) findViewById(R.id.studButton);
// RadioButton button2 = (RadioButton) findViewById(R.id.shopownerButton);
Button button3 = (Button) findViewById(R.id.regSubmitButton);
// button click event
button3.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String name = inputName.getText().toString();
String username = inputUsername.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
if(name.contentEquals("")||username.contentEquals("")||email.contentEquals("")||password.contentEquals(""))
{
AlertDialog.Builder builder = new AlertDialog.Builder(UserRegister.this);
// 2. Chain together various setter methods to set the dialog characteristics
builder.setMessage(R.string.nullAlert)
.setTitle(R.string.alertTitle);
builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
}
});
// 3. Get the AlertDialog from create()
AlertDialog dialog = builder.show();
}
else
{
new RegisterNewUser().execute();
}
}
});
}
class RegisterNewUser extends AsyncTask<String, String, String>{
protected String doInBackground(String... args) {
String name = inputName.getText().toString();
String username = inputUsername.getText().toString();
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_register_user,
"GET", params);
// check log cat for response
Log.d("Send Notification", json.toString());
try
{
int success = json.getInt(TAG_SUCCESS);
if (success == 1)
{
// successfully created product
Intent i = new Intent(getApplicationContext(), StudentLogin.class);
startActivity(i);
finish();
}
else
{
// failed to register
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
}
}
My php file:
<?php
/*
* Following code will create a new product row
* All product details are read from HTTP Post Request
*/
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for required fields
if (isset($_GET['name']) && isset($_GET['username']) && isset($_GET['email']) && isset($_GET['password'])) {
$name = $_GET['name'];
$username = $_GET['username'];
$email = $_GET['email'];
$password = $_GET['password'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO register(name, username, email, password) VALUES('$name', '$username', '$email', '$password')");
// check if row inserted or not
if ($result) {
// successfully inserted into database
$response["success"] = 1;
$response["message"] = "You are successfully registered to MEMS.";
// 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);
}
?>
Change the comparision method to equals() instead of contentEquals() in your code
as The String#equals() not only compares the String's contents, but also checks if the other object is also an instance of a String. The String#contentEquals() methods only compares the contents (the character sequence) and does not check if the other object is also an instance of String. It can be anything as long as it is an implementation of CharSequence or an instance of StringBuffer.
So change your code as like this
if(name.equals("")||username.equals("")||email.equals("")||password.equals(""))
{
....
}

Can't store data to the database

I'm working on an application that stores user inputs into the database table via PHP API but i get an error message from the PHP code to the LogCat. Any advice would be greatly appreciated.
D/Create Response(284): {"message":"Required field(s) is missing","success":0}
PHP API
<?php
// array for JSON response
$response = array();
// check for the fields
if (isset($_POST['title']) && isset($_POST['request_date']) && isset($_POST['reqEndDate']) && isset($_POST['reason']) && isset($_POST['requestor']) && isset($_POST['status']) && isset($_POST['submitDate']) && isset($_POST['explanation']) && isset($_POST['hours']) && isset($_POST['id'])) {
$title = $_POST["request_title"];
$date = $_POST["request_date"];
$eDate = $_POST["reqEndDate"];
$reason = $_POST["reason"];
$requestor = $_POST["requestor"];
$status = $_POST["status"];
$dateSubmitted = $_POST["submitDate"];
$explanation = $_POST["explanation"];
$numhours = $_POST["hours"];
$id = $_POST['id'];
// mysql inserting a new row
$result = mysql_query("INSERT INTO requests(request_title, request_date, reqEndDate, reason, requestor, status, submitDate, explanation, hours, empid)
VALUES('$title', '$date', '$eDate', '$reason', '$requestor', '$status', '$dateSubmitted', '$explanation', '$numhours', '$id')");
?>
JAVA CLASS
// url to the PHP API to create new request
private static String url_create_request = "http://mywebsite.com/create_request.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_request);
// Edit Text
inputTitle = (EditText) findViewById(R.id.inputTitle);
inputSdate = (EditText) findViewById(R.id.inputSdate);
inputEdate = (EditText) findViewById(R.id.inputEdate);
inputHours = (EditText) findViewById(R.id.inputHours);
inputReason = (EditText) findViewById(R.id.inputReason);
inputExp = (EditText) findViewById(R.id.inputExp);
// Create button
Button btnCreateRequest = (Button) findViewById(R.id.btnCreateRequest);
// button click event
btnCreateRequest.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
// creating new product in background thread
new CreateNewRequest().execute();
}
});
}
class CreateNewRequest extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(NewRequestActivity.this);
pDialog.setMessage("Creating Request..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating Request Required Fields
* */
protected String doInBackground(String... args) {
String title = inputTitle.getText().toString();
String date = inputSdate.getText().toString();
String eDate = inputEdate.getText().toString();
String hours = inputHours.getText().toString();
String reason = inputReason.getText().toString();
String explanation = inputExp.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("request_title", title));
params.add(new BasicNameValuePair("request_date", date));
params.add(new BasicNameValuePair("reqEndDate", eDate));
params.add(new BasicNameValuePair("hours", hours));
params.add(new BasicNameValuePair("reason", reason));
params.add(new BasicNameValuePair("explanation", explanation));
// getting JSON Object
// Note that create request url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_request,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created request
Intent i = new Intent(getApplicationContext(), AllRequestsActivity.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create request
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
Just counting your DB columns: there appears to be 12 of them. You're only inserting into 11, and after process of elimination, it looks like you're leaving out "active," which, unless it has a default value or can be null, would throw a "Required field(s) is missing" error that you're getting when trying to insert into the DB.

Categories

Resources