我正在開發一個安卓應用,希望能夠註冊和登錄。我跟着一個在線教程,但有問題,我不知道如何解決它。這也是我的第一個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;
}
}
這裏是我已經越來越
10月12日至1日錯誤日誌:47:45.995: E/AndroidRuntime(21570):FATAL EXCEPTION:main 12-01 10:47:45.995:E/AndroidRuntime(21570):android.os.NetworkOnMainThreadException 12-01 10:47:45.995:E/AndroidRuntime(21570)在android.os.StrictMode $ Androi dBlockGuardPolicy.onNetwork(StrictMode.java:1118) 12-01 10:47:45.995:E/AndroidRuntime(21570):at java.net.InetAddress.lookupHostByName(InetAddress.java:385) 12-01 10:47: 45.995:E/AndroidRuntime(21570):at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236) 12-01 10:47:45.995:E/AndroidRuntime(21570):at java.net.InetAddress.getAllByName( InetAddress.java:214) 12-01 10:47:45.995:E/AndroidRuntime(21570):at 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):at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360) 12-01 10:47:45.995:E/AndroidRuntime(21570):at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670) 12-01 10:47:45.995:E/AndroidRuntime(21570):at 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):at com.example.cs309.gotoclass.library.JSONParser.getJSONFromUrl(JSONParser.java:42) 12-01 10:47:45.995: E/AndroidRuntime(21570):at com.example.cs309.gotoclass.library.UserFunctions.registerUser(UserFunctions.java:62) 12-01 10:47:45.995:E/AndroidRuntime(21570):at com.example.cs309.gotoclass.RegisterActivity $ 1.onClick(RegisterActivity.java:55) 12-01 10:47:45.995:E/AndroidRuntime (21570):at android.view.View.performClick(View.java:4223) 12-01 10:47:45.995:E/AndroidRuntime(21570):at android.view.View $ PerformClick.run(View.java :17275) 12-01 10:47:45.995:E/AndroidRuntime(21570):at android.os.Handler.handleCallback(Handler.java:615) 12-01 10:47:45.995:E/AndroidRuntime(21570) ):at android.os.Handler.dispatchMessage(Handler.java:92) 12-01 10:47:45.995:E/AndroidRuntime(21570):at 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) :at java.lang.reflect.Method.invokeNative(Native Method) 12-01 10:47:45.995:E/AndroidRuntime(21570):at java.lang.reflect.Method.invoke(Method.java:511) 12-01 10:47:45.995:E/AndroidRuntime(21570):at 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):at dalvik.system.NativeStart。主(本地方法)
謝謝你們提供的任何幫助!
更新:
我認爲我是正確的軌道上的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):線程ID = 13:螺紋與離開未知的異常(組= 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):at android.os.AsyncTask $ 3.done(AsyncTask.java:299) 12-02 20:45:23.140:E/AndroidRuntime(28208)在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:電子/ AndroidRuntime(28208):在java.util.concurrent.FutureTask.run(FutureTask.java:137) 12-02 20:45:23.140:E/AndroidRuntime(28208):at android.os.AsyncTask $ SerialExecutor $ 1。運行(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):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):在com.example.cs309.gotoclass.RegisterActivity $ RegisterTask.doInBackground(RegisterActivity.java:89) 12-02 20:45:23.140:E/AndroidRuntime(28208):在玉米.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.inner運行(FutureTask.java:305)