0

我正在开发一个 android 应用程序,并希望能够进行注册和登录。我遵循了一个在线教程,但遇到了问题,我不知道如何解决它。这也是我的第一个安卓应用。谢谢你尽你所能的帮助!

import org.json.JSONException;
import org.json.JSONObject;
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;

import com.example.cs309.gotoclass.library.DatabaseHandler;
import com.example.cs309.gotoclass.library.UserFunctions;

public class LoginActivity extends Activity {
Button btnLogin;
Button btnLinkToRegister;
EditText inputEmail;
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.activity_login_screen);

    // Importing all assets like buttons, text fields
    inputEmail = (EditText) findViewById(R.id.loginEmail);
    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);

    // Login button Click Event
    btnLogin.setOnClickListener(new View.OnClickListener() {

        public void onClick(View view) {
            String email = inputEmail.getText().toString();
            String password = inputPassword.getText().toString();
            UserFunctions userFunction = new UserFunctions();
            JSONObject json = userFunction.loginUser(email, 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(), HomeScreenStudent.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();
            }
        }
    });

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

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

    public void LoginHome(View view){
        Intent intent = new Intent(this, HomeScreenStudent.class);
        startActivity(intent);
    }

public void LoginGuest(View view){
    Intent intent = new Intent(this, HomeScreenGuest.class);
    startActivity(intent);
}
}

但我认为问题出在我的 JSONParser 类中

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

        HttpResponse httpResponse = httpClient.execute(httpPost);
        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();
        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;

}
}

这是我得到的错误日志

12-01 10:47:45.995:E/AndroidRuntime(21570):致命异常:主要 12-01 10:47:45.995:E/AndroidRuntime(21570):android.os.NetworkOnMainThreadException 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 java.net.InetAddress.lookupHostByName(InetAddress .java:385) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 12-01 10:47:45.995: E/AndroidRuntime(21570 ): 在 java.net.InetAddress.getAllByName(InetAddress.java:214) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator. java:137) 12-01 10:47:45.995: E/AndroidRuntime(21570): at org.apache.http。impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164) 12-01 10:47:45.995: E/AndroidRuntime(21570): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119 ) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 12-01 10:47:45.995: E/AndroidRuntime (21570):在 org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670) 12-01 10:47:45.995:E/AndroidRuntime(21570):在 org.apache.http.impl。 client.AbstractHttpClient.execute(AbstractHttpClient.java:509) 12-01 10:47:45.995: E/AndroidRuntime(21570): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487) 12 -01 10:47:45.995:E/AndroidRuntime(21570):在 com.example.cs309.gotoclass.library。JSONParser.getJSONFromUrl(JSONParser.java:42) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 com.example.cs309.gotoclass.library.UserFunctions.registerUser(UserFunctions.java:62) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 com.example.cs309.gotoclass.RegisterActivity$1.onClick(RegisterActivity.java:55) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在android.view.View.performClick(View.java:4223) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 android.view.View$PerformClick.run(View.java:17275) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 android.os.Handler.handleCallback(Handler.java:615) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 android.os.Handler .dispatchMessage(Handler.java:92) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 android.os.Looper.loop(Looper.java:137) 12-01 10:47:45.995:E/AndroidRuntime(21570): 在 android.app.ActivityThread.main(ActivityThread.java:4898) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 java.lang.reflect.Method.invokeNative(Native方法) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 java.lang.reflect.Method.invoke(Method.java:511) 12-01 10:47:45.995: E/AndroidRuntime(21570) : 在 com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 com.android.internal.os.ZygoteInit.main (ZygoteInit.java:773)12-01 10:47:45.995:E/AndroidRuntime(21570):在 dalvik.system.NativeStart.main(本机方法)E/AndroidRuntime(21570): 在 java.lang.reflect.Method.invoke(Method.java:511) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 com.android.internal.os.ZygoteInit $MethodAndArgsCaller.run(ZygoteInit.java:1006) 12-01 10:47:45.995: E/AndroidRuntime(21570): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) 12-01 10 :47:45.995:E/AndroidRuntime(21570):在dalvik.system.NativeStart.main(本机方法)E/AndroidRuntime(21570): 在 java.lang.reflect.Method.invoke(Method.java:511) 12-01 10:47:45.995: E/AndroidRuntime(21570): 在 com.android.internal.os.ZygoteInit $MethodAndArgsCaller.run(ZygoteInit.java:1006) 12-01 10:47:45.995: E/AndroidRuntime(21570): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773) 12-01 10 :47:45.995:E/AndroidRuntime(21570):在dalvik.system.NativeStart.main(本机方法)

感谢你们提供的任何帮助!

更新:

我认为我在 AsyncTask 的正确轨道上,但仍然没有,所以任何帮助将不胜感激!

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_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.activity_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 RegisterTask().execute();
        }
    });

    // 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();
        }
    });
}

class RegisterTask extends AsyncTask<String, String, String> {
int success;

@Override
protected void onPreExecute() {
    super.onPreExecute();
}

@Override
protected String doInBackground(String... args) {
    // TODO Auto-generated method stub
    String email = inputEmail.getText().toString();
    String password = inputPassword.getText().toString();
    String name = inputFullName.getText().toString();

    UserFunctions userFunction = new UserFunctions();
    JSONObject json = userFunction.registerUser(name, email, password);

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

    try {
        int success = json.getInt(KEY_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_NAME),
                    json_user.getString(KEY_EMAIL),
                    json_user.getString(KEY_UID),
                    json_user.getString(KEY_CREATED_AT));

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

protected void onPostExecute(String file_url) {
if (success == 1) {
        Intent dashboard = new Intent(getApplicationContext(), LoginActivity.class);
        dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        startActivity(dashboard);
        finish();
}else{
    //Some Error

 }
}
}
} 

还有错误日志...

块引用

12-02 20:45:23.140: W/dalvikvm(28208): threadid=13: 线程以未捕获的异常退出 (group=0x415e62a0) 12-02 20:45:23.140: E/AndroidRuntime(28208): 致命异常: AsyncTask #1 12-02 20:45:23.140:E / AndroidRuntime(28208):java.lang.RuntimeException:执行doInBackground()时发生错误12-02 20:45:23.140:E / AndroidRuntime(28208):在android .os.AsyncTask$3.done(AsyncTask.java:299) 12-02 20:45:23.140: E/AndroidRuntime(28208): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273) 12 -02 20:45:23.140: E/AndroidRuntime(28208): 在 java.util.concurrent.FutureTask.setException(FutureTask.java:124) 12-02 20:45:23.140: E/AndroidRuntime(28208): 在 java .util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307) 12-02 20:45:23.140: E/AndroidRuntime(28208): 在 java.util.concurrent。FutureTask.run(FutureTask.java:137) 12-02 20:45:23.140: E/AndroidRuntime(28208): 在 android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230) 12-02 20:45 :23.140: E/AndroidRuntime(28208): 在 java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 12-02 20:45:23.140: E/AndroidRuntime(28208): 在 java.util.concurrent。 ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569) 12-02 20:45:23.140: E/AndroidRuntime(28208): at java.lang.Thread.run(Thread.java:856) 12-02 20:45: 23.140: E/AndroidRuntime(28208): 由: java.lang.NullPointerException 12-02 20:45:23.140: E/AndroidRuntime(28208): at com.example.cs309.gotoclass.RegisterActivity$RegisterTask.doInBackground(RegisterActivity. java:89) 12-02 20:45:23.140: E/AndroidRuntime(28208): 在 com.example.cs309.gotoclass.RegisterActivity$RegisterTask。doInBackground(RegisterActivity.java:1) 12-02 20:45:23.140: E/AndroidRuntime(28208): 在 android.os.AsyncTask$2.call(AsyncTask.java:287) 12-02 20:45:23.140: E /AndroidRuntime(28208):在 java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)

4

1 回答 1

1

请不要在主线程上发出网络请求。

 JSONObject json = userFunction.loginUser(email, password);

请改用线程、处理程序/异步任务。

参考这个

于 2012-12-01T18:58:40.930 回答