2

编辑在下面标记为 ////编辑////

新编辑在下方标有 ///newedit///

我将在下面发布的代码是从几个地方借来的,与我在互联网上找到的任何教程或示例都完全不同,我看不出有什么问题。

我正在尝试为我的应用程序创建一个登录页面。目前,它没有检索我在用户名和密码中输入的文本(从这里称为 u 和 p)。如果我进入我的 strings.xml 文件并将 u 和 p 硬编码到应用程序中,它会检索它们并将它们传递给 JSONParser.java。

我在解决这个问题时遇到的问题就是这个。Googledev 和其他人建议使用

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

但我没有将意图或 u 和 p 发送到“nextActivity”以检查登录。它发生在同一个活动“LoginActivity”中。

我试过放置 inputUser = (EditText) findViewById(R.id.loginUser); 在其他领域,例如... public void onClick ...和 ​​....Mytask ....没有运气。

有人可以帮我让代码检索输入的新文本,无论我是否在文本中硬编码?可能是一个简单的问题,但我很难过。

这是整个代码

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;
       }
    }
}

////编辑//// 这里是 login.xml。示例代码有一个我还没有利用的注册部分。因此,请忽略它,除非它是由于某种奇怪的原因导致问题。我将留下几个空格,然后按照@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>

现在更新代码

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;
       }
    }
}

除了“private Void doInBackground”之外,我能够实现 TJ 建议的所有内容。

更改导致错误不允许我运行应用程序。所以我把它公开了。

有了这些新的变化,我的应用程序立即崩溃了。错误包括 Fatal Exception: main...unable to start activity for LoginActivity because of nullpointerexception...。

///新编辑///

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

好的,有logcat。希望这会有所帮助。你能帮忙的话,我会很高兴。我感谢大家的帮助。

4

3 回答 3

1

将您的 AsyncTask 类定义更改为:

class MyTask extends AsyncTask<String,Void,Void>

然后将 doInBackground 的参数设置为:

private Void doInBackground(String... params)

在 doInBackground 中获取用户名和密码,如下所示:

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

最后将您的按钮侦听器更改为:

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) ;

        }

现在解释一下。正如 GameDroids 和 eltabo 所指出的那样,当您创建 MyTask 对象时,MyTask 的字段用户和密码将为空,因为此时这些 EditTexts 中可能没有任何文本。

于 2013-04-17T04:42:24.770 回答
0

当您实例化它时,您将用户和密码值存储在您的任务中。目前,您的文本字段中没有任何价值。您应该在执行任务时将这些值作为参数传递,而不是在实例化它时,或者让任务从您的活动中获取它们(如果它们是可见的)。

于 2013-04-17T01:52:15.717 回答
0

在您的onCreate方法中,您定义输入字段,然后再往下几行即可创建MyTask实例。但在您的MyTask实例中,输入字段将在创建时立即读取:

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

因此,用户名和密码字段实际上将在创建后直接读取,而用户无法输入任何内容。因此,当用户在字段中写入内容并单击按钮时,字符串userpassword已经创建并且为空(因为那里没有什么可读取的)。

尝试在您的方法中读取用户名和密码doInBackground(Void... params)- 这应该可以解决问题(我希望)

于 2013-04-17T01:54:45.320 回答