Android登录使用JSON登录php / mysql asynctask错误[重复]

时间:2022-09-22 17:43:03

Possible Duplicate:
Force close when trying to parse JSON with AsyncTask in the background

可能重复:尝试在后台使用AsyncTask解析JSON时强制关闭

I am trying to write a simple login application on android using MySQL database and storing user info in SQLite but am getting an explosion of errors. Can anyone point me in the right direction? The the code never reaches "Successfully logged in!" in doInBackground, I think.

我试图在Android上使用MySQL数据库编写一个简单的登录应用程序,并在SQLite中存储用户信息,但是我遇到了大量错误。谁能指出我正确的方向?代码永远不会达到“成功登录!”在doInBackground中,我想。

This is the main activity

这是主要活动

public class MainActivity extends Activity {

JSONParser jsonParser = new JSONParser();
private ProgressDialog pDialog;
private static final String TAG_SUCCESS = "success";

// JSON Response node names

private static String KEY_UID = "uid";
private static String KEY_FIRSTNAME = "firstname";
private static String KEY_LASTNAME = "lastname";
private static String KEY_UNAME = "uname";
private static String KEY_EMAIL = "email";
Button bLogin;
EditText etUsername, etPassword;
TextView tvLError;

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

    // Login button
    etUsername = (EditText) findViewById(R.id.etUsername);
    etPassword = (EditText) findViewById(R.id.etPassword);
    bLogin = (Button) findViewById(R.id.bLogin);

    bLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            new LoginTask().execute();

        }
    });
class LoginTask extends AsyncTask<String, String, String> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Logging in...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... args) {
        // TODO Auto-generated method stub
        String uname = etUsername.getText().toString();
        String password = etPassword.getText().toString();

        UserFunctions userFunction = new UserFunctions();
        JSONObject json = userFunction.loginUser(uname, password);

        Log.d("Create Response", json.toString());

        try {
            int success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                // DATABASE HANDLER
                // 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_FIRSTNAME),
                        json_user.getString(KEY_LASTNAME),
                        json_user.getString(KEY_UNAME),
                        json_user.getString(KEY_EMAIL),
                        json_user.getString(KEY_UID));

                tvLError.setText("Successfully logged in!");

            } else {
                tvLError.setText("Incorrect username/password");
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(String file_url) {
        // dismiss the dialog once done
        pDialog.dismiss();
    }

}

The JSONParser class works properly, Log.d is showing the following JSON object

JSONParser类正常工作,Log.d显示以下JSON对象

{"uid":"7","error":0,"user":

  {"email":"abc@123.com","lastname":"test","uname":"test","firstname":"test"},
"success":1,"tag":"login"}

DatabaseHandler class for SQLite

SQLite的DatabaseHandler类

public class DatabaseHandler extends SQLiteOpenHelper{

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "android_api";
private static final String TABLE_LOGIN = "login";
private static final String KEY_ID = "id";
private static final String KEY_UNAME = "uname";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_FIRSTNAME = "firstname";
private static final String KEY_LASTNAME = "lastname";

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase db) {
    // TODO Auto-generated method stub
    String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
            + KEY_ID + " INTEGER PRIMARY KEY,"
            + KEY_FIRSTNAME + " TEXT,"
            + KEY_LASTNAME + " TEXT,"
            + KEY_UNAME + " TEXT,"
            + KEY_EMAIL + " TEXT UNIQUE,"
            + KEY_UID + " TEXT" + ")";
    db.execSQL(CREATE_LOGIN_TABLE);
}


public void addUser(String firstname, String lastname, String uname, String email, String uid) {
    SQLiteDatabase db = this.getWritableDatabase();

    ContentValues values = new ContentValues();
    values.put(KEY_FIRSTNAME, firstname); // First name
    values.put(KEY_LASTNAME, lastname); // Last name
    values.put(KEY_UNAME, uname); // username
    values.put(KEY_EMAIL, email); // Email
    values.put(KEY_UID, uid); // User ID

    // Inserting Row
    db.insert(TABLE_LOGIN, null, values);
    db.close(); // Closing database connection
}

and logoutUser in UserFunctions class just in case is

以及万一用户函数类中的logoutUser和

/**
 * Function to logout user
 * Reset Database
 * */
public boolean logoutUser(Context context){
    DatabaseHandler db = new DatabaseHandler(context);
    db.resetTables();
    return true;
}
}

The errors I am getting are

我得到的错误是

09-18 23:15:57.457: I/Process(807): Sending signal. PID: 807 SIG: 9
09-18 23:26:53.307: E/Trace(851): error opening trace file: No such file or directory (2)
09-18 23:26:53.717: I/Choreographer(851): Skipped 32 frames!  The application may be doing too much work on its main thread.
09-18 23:26:53.787: D/gralloc_goldfish(851): Emulator without GPU emulation detected.
09-18 23:26:56.149: I/Choreographer(851): Skipped 32 frames!  The application may be doing too much work on its main thread.
09-18 23:27:04.397: I/Choreographer(851): Skipped 60 frames!  The application may be doing too much work on its main thread.
09-18 23:27:05.138: D/Create Response(851): {"uid":"7","error":0,"user":{"email":"abc@123.com","lastname":"test","uname":"test","firstname":"test"},"success":1,"tag":"login"}
09-18 23:27:05.437: I/Choreographer(851): Skipped 65 frames!  The application may be doing too much work on its main thread.
09-18 23:27:05.477: D/dalvikvm(851): GC_CONCURRENT freed 175K, 3% free 8227K/8455K, paused 72ms+95ms, total 246ms
09-18 23:27:05.888: W/dalvikvm(851): threadid=11: thread exiting with uncaught exception (group=0x40a13300)
09-18 23:27:05.987: E/AndroidRuntime(851): FATAL EXCEPTION: AsyncTask #1
09-18 23:27:05.987: E/AndroidRuntime(851): java.lang.RuntimeException: An error occured while executing doInBackground()
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.os.AsyncTask$3.done(AsyncTask.java:299)
09-18 23:27:05.987: E/AndroidRuntime(851):  at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
09-18 23:27:05.987: E/AndroidRuntime(851):  at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
09-18 23:27:05.987: E/AndroidRuntime(851):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
09-18 23:27:05.987: E/AndroidRuntime(851):  at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
09-18 23:27:05.987: E/AndroidRuntime(851):  at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
09-18 23:27:05.987: E/AndroidRuntime(851):  at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
09-18 23:27:05.987: E/AndroidRuntime(851):  at java.lang.Thread.run(Thread.java:856)
09-18 23:27:05.987: E/AndroidRuntime(851): Caused by: android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4607)
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:835)
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.view.View.requestLayout(View.java:15129)
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.view.View.requestLayout(View.java:15129)
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.view.View.requestLayout(View.java:15129)
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.view.View.requestLayout(View.java:15129)
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.view.View.requestLayout(View.java:15129)
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.widget.TextView.checkForRelayout(TextView.java:6309)
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.widget.TextView.setText(TextView.java:3547)
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.widget.TextView.setText(TextView.java:3405)
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.widget.TextView.setText(TextView.java:3380)
09-18 23:27:05.987: E/AndroidRuntime(851):  at com.example.testapp1.MainActivity$LoginTask.doInBackground(MainActivity.java:148)
09-18 23:27:05.987: E/AndroidRuntime(851):  at com.example.testapp1.MainActivity$LoginTask.doInBackground(MainActivity.java:1)
09-18 23:27:05.987: E/AndroidRuntime(851):  at android.os.AsyncTask$2.call(AsyncTask.java:287)
09-18 23:27:05.987: E/AndroidRuntime(851):  at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-18 23:27:05.987: E/AndroidRuntime(851):  ... 5 more
09-18 23:27:06.308: I/Choreographer(851): Skipped 44 frames!  The application may be doing too much work on its main thread.
09-18 23:27:07.747: E/WindowManager(851): Activity com.example.testapp1.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41219ee8 that was originally added here
09-18 23:27:07.747: E/WindowManager(851): android.view.WindowLeaked: Activity com.example.testapp1.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@41219ee8 that was originally added here
09-18 23:27:07.747: E/WindowManager(851):   at android.view.ViewRootImpl.<init>(ViewRootImpl.java:374)
09-18 23:27:07.747: E/WindowManager(851):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:292)
09-18 23:27:07.747: E/WindowManager(851):   at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:224)
09-18 23:27:07.747: E/WindowManager(851):   at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:149)
09-18 23:27:07.747: E/WindowManager(851):   at android.view.Window$LocalWindowManager.addView(Window.java:547)
09-18 23:27:07.747: E/WindowManager(851):   at android.app.Dialog.show(Dialog.java:277)
09-18 23:27:07.747: E/WindowManager(851):   at com.example.testapp1.MainActivity$LoginTask.onPreExecute(MainActivity.java:115)
09-18 23:27:07.747: E/WindowManager(851):   at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
09-18 23:27:07.747: E/WindowManager(851):   at android.os.AsyncTask.execute(AsyncTask.java:534)
09-18 23:27:07.747: E/WindowManager(851):   at com.example.testapp1.MainActivity$1.onClick(MainActivity.java:59)
09-18 23:27:07.747: E/WindowManager(851):   at android.view.View.performClick(View.java:4084)
09-18 23:27:07.747: E/WindowManager(851):   at android.view.View$PerformClick.run(View.java:16966)
09-18 23:27:07.747: E/WindowManager(851):   at android.os.Handler.handleCallback(Handler.java:615)
09-18 23:27:07.747: E/WindowManager(851):   at android.os.Handler.dispatchMessage(Handler.java:92)
09-18 23:27:07.747: E/WindowManager(851):   at android.os.Looper.loop(Looper.java:137)
09-18 23:27:07.747: E/WindowManager(851):   at android.app.ActivityThread.main(ActivityThread.java:4745)
09-18 23:27:07.747: E/WindowManager(851):   at java.lang.reflect.Method.invokeNative(Native Method)
09-18 23:27:07.747: E/WindowManager(851):   at java.lang.reflect.Method.invoke(Method.java:511)
09-18 23:27:07.747: E/WindowManager(851):   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
09-18 23:27:07.747: E/WindowManager(851):   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
09-18 23:27:07.747: E/WindowManager(851):   at dalvik.system.NativeStart.main(Native Method)

Thank you for your time!

感谢您的时间!

1 个解决方案

#1


0  

The onPostExecute() method synchronize itself again with the user interface thread and allows to update it. This method is called by the framework once the doInBackground() method finishes.

onPostExecute()方法再次与用户界面线程同步,并允许更新它。一旦doInBackground()方法完成,框架就会调用此方法。

your textview value set in onPostExecute method.

你的textview值在onPostExecute方法中设置。

 protected void onPostExecute(String file_url) {
    // dismiss the dialog once done
    pDialog.dismiss();
 if (success == 1) {
          tvLError.setText("Successfully logged in!");

 }else{
       tvLError.setText("Incorrect username/password");

     }

}

#1


0  

The onPostExecute() method synchronize itself again with the user interface thread and allows to update it. This method is called by the framework once the doInBackground() method finishes.

onPostExecute()方法再次与用户界面线程同步,并允许更新它。一旦doInBackground()方法完成,框架就会调用此方法。

your textview value set in onPostExecute method.

你的textview值在onPostExecute方法中设置。

 protected void onPostExecute(String file_url) {
    // dismiss the dialog once done
    pDialog.dismiss();
 if (success == 1) {
          tvLError.setText("Successfully logged in!");

 }else{
       tvLError.setText("Incorrect username/password");

     }

}