我正在尝试创建一个简单的登录屏幕,正确加载用户尚未登录。 但是 - 按下“登录”按钮会使应用程序崩溃。
LoginActivity.java
package com.atsdata.flldk;
import java.util.HashMap;
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.atsdata.flldk.library.DatabaseHandler;
import com.atsdata.flldk.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.login);
// 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);
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(), MainActivity.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();
}
}
});
}
}
UserFunctions.java
package com.atsdata.flldk.library;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;
import android.content.Context;
public class UserFunctions {
private JSONParser jsonParser;
// Testing in localhost using wamp or xampp
// use http://10.0.2.2/ to connect to your localhost ie http://localhost/
private static String loginURL = "http://<url-removed>";
private static String registerURL = "http://<url-removed>";
private static String login_tag = "login";
private static String register_tag = "register";
// constructor
public UserFunctions(){
jsonParser = new JSONParser();
}
/**
* function make Login Request
* @param email
* @param password
* */
public JSONObject loginUser(String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
JSONObject json = jsonParser.getJSONFromUrl(loginURL, params);
// return json
// Log.e("JSON", json.toString());
return json;
}
/**
* function make Login Request
* @param name
* @param email
* @param password
* */
public JSONObject registerUser(String name, String email, String password){
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", register_tag));
params.add(new BasicNameValuePair("name", name));
params.add(new BasicNameValuePair("email", email));
params.add(new BasicNameValuePair("password", password));
// getting JSON Object
JSONObject json = jsonParser.getJSONFromUrl(registerURL, params);
// return json
return json;
}
/**
* Function get Login status
* */
public boolean isUserLoggedIn(Context context){
DatabaseHandler db = new DatabaseHandler(context);
int count = db.getRowCount();
if(count > 0){
// user logged in
return true;
}
return false;
}
/**
* Function to logout user
* Reset Database
* */
public boolean logoutUser(Context context){
DatabaseHandler db = new DatabaseHandler(context);
db.resetTables();
return true;
}
}
log cat
03-07 06:58:40.212: D/AndroidRuntime(1440): Shutting down VM
03-07 06:58:40.212: W/dalvikvm(1440): threadid=1: thread exiting with uncaught exception (group=0xb1aa3b90)
03-07 06:58:40.222: E/AndroidRuntime(1440): FATAL EXCEPTION: main
03-07 06:58:40.222: E/AndroidRuntime(1440): Process: com.atsdata.flldk, PID: 1440
03-07 06:58:40.222: E/AndroidRuntime(1440): android.os.NetworkOnMainThreadException
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
03-07 06:58:40.222: E/AndroidRuntime(1440): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
03-07 06:58:40.222: E/AndroidRuntime(1440): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
03-07 06:58:40.222: E/AndroidRuntime(1440): at java.net.InetAddress.getAllByName(InetAddress.java:214)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
03-07 06:58:40.222: E/AndroidRuntime(1440): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
03-07 06:58:40.222: E/AndroidRuntime(1440): at com.atsdata.flldk.library.JSONParser.getJSONFromUrl(JSONParser.java:43)
03-07 06:58:40.222: E/AndroidRuntime(1440): at com.atsdata.flldk.library.UserFunctions.loginUser(UserFunctions.java:40)
03-07 06:58:40.222: E/AndroidRuntime(1440): at com.atsdata.flldk.LoginActivity$1.onClick(LoginActivity.java:54)
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.view.View.performClick(View.java:4424)
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.view.View$PerformClick.run(View.java:18383)
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.os.Handler.handleCallback(Handler.java:733)
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.os.Handler.dispatchMessage(Handler.java:95)
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.os.Looper.loop(Looper.java:137)
03-07 06:58:40.222: E/AndroidRuntime(1440): at android.app.ActivityThread.main(ActivityThread.java:4998)
03-07 06:58:40.222: E/AndroidRuntime(1440): at java.lang.reflect.Method.invokeNative(Native Method)
03-07 06:58:40.222: E/AndroidRuntime(1440): at java.lang.reflect.Method.invoke(Method.java:515)
03-07 06:58:40.222: E/AndroidRuntime(1440): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-07 06:58:40.222: E/AndroidRuntime(1440): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-07 06:58:40.222: E/AndroidRuntime(1440): at dalvik.system.NativeStart.main(Native Method)
如果有人能指出我正确的方向,那就太好了。感谢。
答案 0 :(得分:2)
您不能在UI主线程上进行网络通信。这是为了阻止您的代码阻止UI并锁定它。您需要在另一个线程上进行网络工作。您应该阅读有关AsyncTasks的信息:
http://www.vogella.com/tutorials/AndroidBackgroundProcessing/article.html#concurrency_asynchtask
http://developer.android.com/reference/android/os/AsyncTask.html
答案 1 :(得分:1)
NetworkOnMainThreadException
这意味着您无法在主线程中执行网络操作(例如onClick或其他线程中未使用的其他方法)。
尝试将代码放入
public void onClick(View view) {...}
到AsyncTask