jj.amoniit
jj.amoniit

Reputation: 33

Why won't Android retrieve my entered text?

Edited below Marked with ////EDIT////

New Edit is below marked with ///newedit///

My code, which I will post below is borrowed from a few places and is just enough different than any of the tutorials or examples that I found on the internet that I am unable to see what is wrong.

I am trying to do a login page for my app. currently, it is not retrieving the text I am entering in the username and password (from here on refered to as u and p). If i going into my strings.xml file and hard code the u and p into the app, it does retrieve them and pass them on to the JSONParser.java.

Where I am having the problem solving this problem is this. Googledev and others suggest using the

Intent intent = new Intent(this, nextActivity.class);

But I am not sending the intent or the u and p to "nextActivity" to check the login. It is happening in the same activity "LoginActivity".

I have tried placing the inputUser = (EditText) findViewById(R.id.loginUser); in other areas like... public void onClick...and ....Mytask....with no luck.

Can somebody help me make the code retrieve the new text entered, whether I hard code in text or not? Probably a simple problem, but I am stumped.

Here's the whole code

package com.exmple.myapp;


import gdmeter.myapp_Calc;
import library.DatabaseHandler;
import library.UserFunctions;
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;

public class LoginActivity extends Activity {
    Button btnLogin;
    Button btnLinkToRegister;
    EditText inputUser;
    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";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    inputUser = (EditText) findViewById(R.id.loginUser);
    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);


    final MyTask myTask = new MyTask();
    // Login button Click Event
    btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            // Importing all assets like buttons, text fields
           myTask.execute() ;

        } 


            // Link to Register Screen
            /**       btnLinkToRegister.setOnClickListener(new View.OnClickListener() {

                public void onClick(View view) {
                    Intent i = new Intent(getApplicationContext(),
                            RegisterActivity.class);
                    startActivity(i);
                    finish();
                }
            });
        **/
    }); 
 }       

//*** Move out MyTask
class MyTask extends AsyncTask<Void,Void,Void>{
    String user = inputUser.getText().toString();
    String password = inputPassword.getText().toString();
    @Override
    protected Void doInBackground(Void... params) {

        UserFunctions userFunction = new UserFunctions();
        JSONObject json = userFunction.loginUser(user, password);
        // check for login response
        try {
            if (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 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(), myapp_Calc.class);

                    // Close all views before launching Dashboard
                    dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(dashboard);

                    // Close Login Screen
                    finish();
                }else{
                    // Error in login
                    loginErrorMsg.setText("Incorrect username/password");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
          }

        return null;
       }
    }
}

////EDIT//// Here is the login.xml. The example code had a registration section that I am not taking advantage of yet. So, disregard it unless it is by some freak reason causing the problem. I will leave a few spaces and then show the new code as suggested by @TJ Thind.

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#3b3b3b" >

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:padding="10dip" >
    <!--  View Title Label -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="10dip"
        android:text="LOGIN"
        android:textSize="25dip"
        android:textStyle="bold" />
    <!--  Email Label -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Username" />
    <!--  Email TextField -->
    <EditText
        android:id="@+id/loginUser"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="jj" />

    <!--  Password Label -->
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="15dip"
        android:text="Password" />
    <!--  Password TextField -->
    <EditText
        android:id="@+id/loginPassword"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="jj"
        android:password="true" />

    <!--  Error message -->
    <TextView android:id="@+id/login_error"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:textColor="#e30000"
                android:padding="10dip"
                android:textStyle="bold"/>

    <!--  Login Button -->
    <Button
        android:id="@+id/btnLogin"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dip"
        android:text="Login" />

    <!--  Link to Registration Screen -->
    <Button
        android:id="@+id/btnLinkToRegisterScreen"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="40dip"
        android:background="@null"
        android:text="I don&apos;t have account. Register Me!"
        android:textColor="#21dbd4"
        android:textStyle="bold" />
</LinearLayout>

now for the updated code

package com.exmple.myapp;


import gdmeter.myapp_Calc;
import library.DatabaseHandler;
import library.UserFunctions;

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.exmple.gdmeter.R;

public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputUser;
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";

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);


    final MyTask myTask = new MyTask();
    // Login button Click Event
    btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            // Importing all assets like buttons, text fields
            String user = inputUser.getText().toString();
            String password = inputPassword.getText().toString();
            myTask.execute(user,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();
                }
            });
        **/
    }); 
 }       

//*** Move out MyTask
class MyTask extends AsyncTask<String,Void,Void>{
    @Override
    public Void doInBackground(String... params) {
        String user = params[0];
        String password = params[1];

        UserFunctions userFunction = new UserFunctions();
        JSONObject json = userFunction.loginUser(user, password);
        // check for login response
        try {
            if (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 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(), myapp_Calc.class);

                    // Close all views before launching Dashboard
                    dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(dashboard);

                    // Close Login Screen
                    finish();
                }else{
                    // Error in login
                    loginErrorMsg.setText("Incorrect username/password");
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
          }

        return null;
       }
    }
}

I was able to implement everything TJ suggested except the "private Void doInBackground".

Changing that caused errors not allowing me to run the app. So I left it public.

With these new changes, I get immediate crashing of the app. The errors include Fatal Exception: main...unable to start activity for LoginActivity because of nullpointerexception....

///newedit///

04-28 19:20:06.517: D/ActivityThread(10674): setTargetHeapUtilization:0.25
04-28 19:20:06.517: D/ActivityThread(10674): setTargetHeapIdealFree:8388608
04-28 19:20:06.517: D/ActivityThread(10674): setTargetHeapConcurrentStart:2097152
04-28 19:20:06.667: W/dalvikvm(10674): threadid=1: thread exiting with uncaught exception (group=0x40eca438)
04-28 19:20:06.667: E/AndroidRuntime(10674): FATAL EXCEPTION: main
04-28 19:20:06.667: E/AndroidRuntime(10674): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.exmple.gdmeter/com.exmple.gdmeter.LoginActivity}: java.lang.NullPointerException
04-28 19:20:06.667: E/AndroidRuntime(10674):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2088)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2113)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at android.app.ActivityThread.access$700(ActivityThread.java:139)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1224)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at android.os.Looper.loop(Looper.java:137)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at android.app.ActivityThread.main(ActivityThread.java:4918)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at java.lang.reflect.Method.invokeNative(Native Method)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at java.lang.reflect.Method.invoke(Method.java:511)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at dalvik.system.NativeStart.main(Native Method)
04-28 19:20:06.667: E/AndroidRuntime(10674): Caused by: java.lang.NullPointerException
04-28 19:20:06.667: E/AndroidRuntime(10674):    at com.exmple.gdmeter.LoginActivity.onCreate(LoginActivity.java:46)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at android.app.Activity.performCreate(Activity.java:5048)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
04-28 19:20:06.667: E/AndroidRuntime(10674):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2052)
04-28 19:20:06.667: E/AndroidRuntime(10674):    ... 11 more

Okay, there is the logcat. Hopefully this helps out. Any help would be nice. I thank everyone for their help.

Upvotes: 2

Views: 180

Answers (3)

TJ Thind
TJ Thind

Reputation: 784

Change your AsyncTask class definition to this:

class MyTask extends AsyncTask<String,Void,Void>

Then the parameters for doInBackground to this:

private Void doInBackground(String... params)

In doInBackground get the user name and password like so:

String user = params[0]
String password = params[1];

Finally change your button listener to this:

btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            // Importing all assets like buttons, text fields
           String user = inputUser.getText().toString();
           String password = inputPassword.getText().toString();
           myTask.execute(user,password) ;

        }

Now for the explanation. Exactly as GameDroids and eltabo have pointed out when you create a MyTask object the MyTask's fields user and password will be blank, because at that point there's probably not any text in those EditTexts.

Upvotes: 1

GameDroids
GameDroids

Reputation: 5662

In your onCreate method you define your input fields and only a few lines further down you create the MyTask instance. But in your MyTask instance the input fields will be read instantaneously on creation:

class MyTask extends AsyncTask<Void,Void,Void>{
     String user = inputUser.getText().toString();  // this will be read when you instantiate your MyTask
     String password = inputPassword.getText().toString();


     @Override
     protected Void doInBackground(Void... params) {   // this will be executed when the click listener gets triggered

So the username and the password field will actually be read directly after their creation, without the user being able to input anything. So when the user writes something in the fields and click the button, the Strings user and password are already created and empty (because there was nothing there to read).

Try reading the username and password in your doInBackground(Void... params) method – that should do the trick (I hope)

Upvotes: 0

eltabo
eltabo

Reputation: 3807

Your are storing the user and password values in your task when you instance it. At this moment there is no value in your text fields. You should pass these values as parameters when you execute the task, not when you instance it, or let the task take them from your activity if they are visible.

Upvotes: 0

Related Questions