HttpResponse httpResponse = httpClient.execute(httpPost);
老实说,我不确定问题是什么,可以真正使用一些帮助。请记住,因为我是初学者,我可能还不了解一些高级功能/术语。下面是我的主程序包(brg.application.alarmmonitor)下的Login.java Register.java代码和作为库(brg.application.alarmmonitor.library)的DatabaseHandler.java JSONParser.java UserFunctions.java以及来自Eclipse中的LogCat。
Login.java
package brg.application.alarmmonitor;
import org.json.JSONException;
import org.json.JSONObject;
import brg.application.alarmmonitor.Dashboard;
import brg.application.alarmmonitor.Register;
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 brg.application.alarmmonitor.library.DatabaseHandler;
import brg.application.alarmmonitor.library.UserFunctions;
public class Login 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);
// 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.link_to_register);
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();
Log.d("Button", "Login");
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(), Dashboard.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(),
Register.class);
startActivity(i);
finish();
}
});
}
}
Register.java
package brg.application.alarmmonitor;
import org.json.JSONException;
import org.json.JSONObject;
import brg.application.alarmmonitor.Dashboard;
import brg.application.alarmmonitor.Login;
import brg.application.alarmmonitor.R;
import brg.application.alarmmonitor.library.DatabaseHandler;
import brg.application.alarmmonitor.library.UserFunctions;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class Register 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_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_register);
// Importing all assets like buttons, text fields
inputFullName = (EditText) findViewById(R.id.reg_name);
inputEmail = (EditText) findViewById(R.id.reg_email);
inputPassword = (EditText) findViewById(R.id.reg_password);
btnRegister = (Button) findViewById(R.id.btnRegister);
btnLinkToLogin = (Button) findViewById(R.id.link_to_login);
registerErrorMsg = (TextView) findViewById(R.id.reg_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();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.registerUser(name, email, password);
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
registerErrorMsg.setText("");
String res = json.getString(KEY_SUCCESS);
if(Integer.parseInt(res) == 1){
// user successfully registred
// 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(), Dashboard.class);
// Close all views before launching Dashboard
dashboard.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(dashboard);
// Close Registration Screen
finish();
}else{
// Error in registration
registerErrorMsg.setText("Error occured in registration");
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
// Link to Login Screen
btnLinkToLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Login.class);
startActivity(i);
// Close Registration View
finish();
}
});
}
}
DatabaseHandler.java
package brg.application.alarmmonitor.library;
import java.util.HashMap;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "a8855590_alarm";
// Login table name
private static final String TABLE_LOGIN = "login";
// Login Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_NAME = "name";
private static final String KEY_EMAIL = "email";
private static final String KEY_UID = "uid";
private static final String KEY_CREATED_AT = "created_at";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_LOGIN_TABLE = "CREATE TABLE " + TABLE_LOGIN + "("
+ KEY_ID + " INTEGER PRIMARY KEY,"
+ KEY_NAME + " TEXT,"
+ KEY_EMAIL + " TEXT UNIQUE,"
+ KEY_UID + " TEXT,"
+ KEY_CREATED_AT + " TEXT" + ")";
db.execSQL(CREATE_LOGIN_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOGIN);
// Create tables again
onCreate(db);
}
/**
* Storing user details in database
* */
public void addUser(String name, String email, String uid, String created_at) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, name); // Name
values.put(KEY_EMAIL, email); // Email
values.put(KEY_UID, uid); // Email
values.put(KEY_CREATED_AT, created_at); // Created At
// Inserting Row
db.insert(TABLE_LOGIN, null, values);
db.close(); // Closing database connection
}
/**
* Getting user data from database
* */
public HashMap<String, String> getUserDetails(){
HashMap<String,String> user = new HashMap<String,String>();
String selectQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// Move to first row
cursor.moveToFirst();
if(cursor.getCount() > 0){
user.put("name", cursor.getString(1));
user.put("email", cursor.getString(2));
user.put("uid", cursor.getString(3));
user.put("created_at", cursor.getString(4));
}
cursor.close();
db.close();
// return user
return user;
}
/**
* Getting user login status
* return true if rows are there in table
* */
public int getRowCount() {
String countQuery = "SELECT * FROM " + TABLE_LOGIN;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int rowCount = cursor.getCount();
db.close();
cursor.close();
// return row count
return rowCount;
}
/**
* Re crate database
* Delete all tables and create them again
* */
public void resetTables(){
SQLiteDatabase db = this.getWritableDatabase();
// Delete All Rows
db.delete(TABLE_LOGIN, null, null);
db.close();
}
}
JSONParser.java
package brg.application.alarmmonitor.library;
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;
}
}
UserFunctions.java
package brg.application.alarmmonitor.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;
private static String loginURL = "http://alarmmonitor.comyr.com/android_login_api/";
private static String registerURL = "http://alarmmonitor.comyr.com/android_login_api/";
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 Register 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;
}
}
LogCat错误
11-04 18:02:28.570: D/Button(1725): Login
11-04 18:02:28.579: D/dalvikvm(1725): GC_CONCURRENT freed 101K, 7% free 3017K/3228K, paused 2ms+0ms, total 3ms
11-04 18:02:28.579: D/AndroidRuntime(1725): Shutting down VM
11-04 18:02:28.579: W/dalvikvm(1725): threadid=1: thread exiting with uncaught exception (group=0xb2d5a908)
11-04 18:02:28.579: E/AndroidRuntime(1725): FATAL EXCEPTION: main
11-04 18:02:28.579: E/AndroidRuntime(1725): android.os.NetworkOnMainThreadException
11-04 18:02:28.579: E/AndroidRuntime(1725): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-04 18:02:28.579: E/AndroidRuntime(1725): at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
11-04 18:02:28.579: E/AndroidRuntime(1725): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
11-04 18:02:28.579: E/AndroidRuntime(1725): at java.net.InetAddress.getAllByName(InetAddress.java:214)
11-04 18:02:28.579: E/AndroidRuntime(1725): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
11-04 18:02:28.579: E/AndroidRuntime(1725): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
11-04 18:02:28.579: E/AndroidRuntime(1725): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
11-04 18:02:28.579: E/AndroidRuntime(1725): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
11-04 18:02:28.579: E/AndroidRuntime(1725): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
11-04 18:02:28.579: E/AndroidRuntime(1725): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
11-04 18:02:28.579: E/AndroidRuntime(1725): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
11-04 18:02:28.579: E/AndroidRuntime(1725): at brg.application.alarmmonitor.library.JSONParser.getJSONFromUrl(JSONParser.java:42)
11-04 18:02:28.579: E/AndroidRuntime(1725): at brg.application.alarmmonitor.library.UserFunctions.loginUser(UserFunctions.java:38)
11-04 18:02:28.579: E/AndroidRuntime(1725): at brg.application.alarmmonitor.Login$1.onClick(Login.java:57)
11-04 18:02:28.579: E/AndroidRuntime(1725): at android.view.View.performClick(View.java:4202)
11-04 18:02:28.579: E/AndroidRuntime(1725): at android.view.View$PerformClick.run(View.java:17340)
11-04 18:02:28.579: E/AndroidRuntime(1725): at android.os.Handler.handleCallback(Handler.java:725)
11-04 18:02:28.579: E/AndroidRuntime(1725): at android.os.Handler.dispatchMessage(Handler.java:92)
11-04 18:02:28.579: E/AndroidRuntime(1725): at android.os.Looper.loop(Looper.java:137)
11-04 18:02:28.579: E/AndroidRuntime(1725): at android.app.ActivityThread.main(ActivityThread.java:5039)
11-04 18:02:28.579: E/AndroidRuntime(1725): at java.lang.reflect.Method.invokeNative(Native Method)
11-04 18:02:28.579: E/AndroidRuntime(1725): at java.lang.reflect.Method.invoke(Method.java:511)
11-04 18:02:28.579: E/AndroidRuntime(1725): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
11-04 18:02:28.579: E/AndroidRuntime(1725): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
11-04 18:02:28.579: E/AndroidRuntime(1725): at dalvik.system.NativeStart.main(Native Method)
我知道这是很多代码,对不起,但我想确保你拥有所需的所有代码来帮助我解决问题。再次感谢!
乔纳森
编辑: 好的,所以我试图改变Login.java使用AsyncTask,我查看了一些事情,看到我需要使用publishProgress但是现在当我点击登录时它只是说“登录...”很长一段时间直到最后退出。这是新的代码和错误:
Login.java
package brg.application.alarmmonitor;
import org.json.JSONException;
import org.json.JSONObject;
import brg.application.alarmmonitor.Dashboard;
import brg.application.alarmmonitor.Register;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import brg.application.alarmmonitor.library.DatabaseHandler;
import brg.application.alarmmonitor.library.UserFunctions;
public class Login 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);
// 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.link_to_register);
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();
Log.d("Button", "Login");
JSONObject json = userFunction.loginUser(email, password);
**/
class LoginTask extends AsyncTask<String, String, String> {
ProgressDialog dialog = new ProgressDialog (Login.this);
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog.setMessage("Logging in...");
dialog.setIndeterminate(false);
dialog.setCancelable(true);
dialog.show();
}
protected void onProgressUpdate(String... message) {
loginErrorMsg.setText(message[0]);
}
@Override
protected String doInBackground(String... args) {
// TODO Auto-generated method stub
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
JSONObject json = userFunction.loginUser(email, password);
Log.d("Button", "Login");
// check for login response
try {
if (json.getString(KEY_SUCCESS) != null) {
//loginErrorMsg.setText("");
publishProgress(json.getString("loginErrorMsg"));
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(), Dashboard.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");
publishProgress(json.getString("Incorrect email/password"));
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
@SuppressWarnings("unused")
protected void onPostExecute() {
dialog.dismiss();
}
}
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
new LoginTask().execute();
}
});
// Link to Register Screen
btnLinkToRegister.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),
Register.class);
startActivity(i);
finish();
}
});
}
}
LogCat错误:
11-05 17:40:30.610: E/Buffer Error(2046): Error converting result java.lang.NullPointerException: lock == null
11-05 17:40:30.610: E/JSON Parser(2046): Error parsing data org.json.JSONException: End of input at character 0 of
11-05 17:40:30.610: D/Button(2046): Login
11-05 17:40:30.610: W/dalvikvm(2046): threadid=10: thread exiting with uncaught exception (group=0xb2d2c908)
11-05 17:40:30.610: E/AndroidRuntime(2046): FATAL EXCEPTION: AsyncTask #1
11-05 17:40:30.610: E/AndroidRuntime(2046): java.lang.RuntimeException: An error occured while executing doInBackground()
11-05 17:40:30.610: E/AndroidRuntime(2046): at android.os.AsyncTask$3.done(AsyncTask.java:299)
11-05 17:40:30.610: E/AndroidRuntime(2046): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
11-05 17:40:30.610: E/AndroidRuntime(2046): at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
11-05 17:40:30.610: E/AndroidRuntime(2046): at java.util.concurrent.FutureTask.run(FutureTask.java:239)
11-05 17:40:30.610: E/AndroidRuntime(2046): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
11-05 17:40:30.610: E/AndroidRuntime(2046): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
11-05 17:40:30.610: E/AndroidRuntime(2046): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
11-05 17:40:30.610: E/AndroidRuntime(2046): at java.lang.Thread.run(Thread.java:856)
11-05 17:40:30.610: E/AndroidRuntime(2046): Caused by: java.lang.NullPointerException
11-05 17:40:30.610: E/AndroidRuntime(2046): at brg.application.alarmmonitor.Login$1LoginTask.doInBackground(Login.java:93)
11-05 17:40:30.610: E/AndroidRuntime(2046): at brg.application.alarmmonitor.Login$1LoginTask.doInBackground(Login.java:1)
11-05 17:40:30.610: E/AndroidRuntime(2046): at android.os.AsyncTask$2.call(AsyncTask.java:287)
11-05 17:40:30.610: E/AndroidRuntime(2046): at java.util.concurrent.FutureTask.run(FutureTask.java:234)
11-05 17:40:30.610: E/AndroidRuntime(2046): ... 4 more
答案 0 :(得分:0)
android.os.NetworkOnMainThreadException
您正在主线程内调用网络进程,这不是(通常)允许的。 你应该在一个单独的线程中调用getJSONFromUrl(...)。
您可以使用原始线程调用它:
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
getJSONFromUrl(...);
}
}
thread.start()
或使用AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
考虑到您需要将代码更改为“等待”,直到getJSONFromUrl(...)被强制执行,然后您可以继续执行程序流程。
编辑:我将添加一些关于如何继续流程的内容。在你的情况下,你可以做类似的事情:
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String email = inputEmail.getText().toString();
String password = inputPassword.getText().toString();
UserFunctions userFunction = new UserFunctions();
Log.d("Button", "Login");
// Here you should show a loading dialog or somthing, as this can take a couple o seconds
Thread thread = new Thread(new Runnable()
{
@Override
public void run()
{
JSONObject json = userFunction.loginUser(email, password);
runOnUiThread(new Runnable()
{
@Override
public void run()
{
ContinueFlow();
}
}
}
}
}
}
其中“ContinueFlow()”将是一种方法,现在所有这些都在
之下JSONObject json = userFunction.loginUser(email, password);
如您所见,您必须在UI线程中调用所有其他内容(这就是runOnUiThread的动机)
使用AsyncTask(我认为更干净)你不必乱用ui线程(你只需要在doInBackground中执行所有网络内容,并继续使用onComplete(...)中的流)
答案 1 :(得分:0)