我正在使用Android应用,希望能够进行注册和登录。我按照在线教程,但遇到问题,我无法弄清楚如何修复它。这是我的第一个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):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):在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):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.main(Native Method)
感谢您提供的任何帮助!
更新
我认为我在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):at java.util.concurrent.FutureTask.setException(FutureTask.java:124) 12-02 20:45:23.140:E / AndroidRuntime(28208):at java.util.concurrent.FutureTask $ Sync.innerRun(FutureTask.java:307) 12-02 20:45:23.140:E / AndroidRuntime(28208):at 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):at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076) 12-02 20:45:23.140:E / AndroidRuntime(28208):at 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):at 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):at java.util.concurrent.FutureTask $ Sync.innerRun(FutureTask.java:305)
答案 0 :(得分:1)
请不要在主线程上发出网络请求。
JSONObject json = userFunction.loginUser(email, password);
使用Threads,Handlers / AsyncTask代替。
参考this