我对Android应用开发相对较新,并想知道我做错了什么。我有一个使用用户名和密码连接到我的Web服务器的AsyncTask,并将用户数据集作为json对象返回。不幸的是我无法获取json字符串,因为我的AsyncHttpReading类中的onPostExecute()似乎没有被调用。为什么呢?
MainActivity.java 的
package com.alphavoice.sampleproject;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import com.alphavoice.sampleproject.community.user.User;
import com.alphavoice.sampleproject.util.HttpReader;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isLoggedIn = (appPrefs.getInt("userId", 0) != 0) ? true : false;
if (isLoggedIn) {
renderCommunityView();
}
else {
setContentView(R.layout.activity_main);
final Button btnLogin = (Button) findViewById(R.id.btn_login);
final EditText etUsername = (EditText) findViewById(R.id.et_username);
final EditText etPassword = (EditText) findViewById(R.id.et_password);
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String loginUrl = "http://example.com/websrv/get_user.php?username=" + username + "&password=" + password;
AsyncHttpReading httpReading = new AsyncHttpReading();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
int corePoolSize = 60;
int maximumPoolSize = 80;
int keepAliveTime = 10;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(maximumPoolSize);
Executor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue);
// httpReading.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, loginUrl);
httpReading.executeOnExecutor(threadPoolExecutor, loginUrl);
}
else {
httpReading.execute(loginUrl);
}
if (httpReading.getLoggedInUser() != null) {
// renderCommunityView();
btnLogin.setBackgroundColor(Color.GREEN);
}
else {
// wrong combination of username & password => try again
etUsername.setBackgroundColor(Color.rgb(255, 204, 204));
etPassword.setBackgroundColor(Color.rgb(255, 204, 204));
}
}
});
}
}
private void renderCommunityView() {
setContentView(R.layout.activity_community);
}
private class AsyncHttpReading extends AsyncTask<String, Void, String> {
private String response = "";
private User loggedInUser = null;
public AsyncHttpReading() { }
public String getResponse() {
return response;
}
public User getLoggedInUser() {
return loggedInUser;
}
@Override
protected String doInBackground(String... urls) {
HttpReader httpReader = new HttpReader(urls[0]);
response = httpReader.getResponse();
return response;
}
@Override
protected void onPostExecute(String response) {
try {
JSONObject userData = new JSONObject(this.getResponse()).getJSONObject("0");
if (userData != null) {
loggedInUser = new User(userData);
}
} catch (JSONException e) {
Log.e("SAMPLEPROJECT", "Could not parse json data!");
}
}
}
}
package com.alphavoice.sampleproject;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import com.alphavoice.sampleproject.community.user.User;
import com.alphavoice.sampleproject.util.HttpReader;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences appPrefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean isLoggedIn = (appPrefs.getInt("userId", 0) != 0) ? true : false;
if (isLoggedIn) {
renderCommunityView();
}
else {
setContentView(R.layout.activity_main);
final Button btnLogin = (Button) findViewById(R.id.btn_login);
final EditText etUsername = (EditText) findViewById(R.id.et_username);
final EditText etPassword = (EditText) findViewById(R.id.et_password);
btnLogin.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String loginUrl = "http://example.com/websrv/get_user.php?username=" + username + "&password=" + password;
AsyncHttpReading httpReading = new AsyncHttpReading();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
int corePoolSize = 60;
int maximumPoolSize = 80;
int keepAliveTime = 10;
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<Runnable>(maximumPoolSize);
Executor threadPoolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, keepAliveTime, TimeUnit.SECONDS, workQueue);
// httpReading.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, loginUrl);
httpReading.executeOnExecutor(threadPoolExecutor, loginUrl);
}
else {
httpReading.execute(loginUrl);
}
if (httpReading.getLoggedInUser() != null) {
// renderCommunityView();
btnLogin.setBackgroundColor(Color.GREEN);
}
else {
// wrong combination of username & password => try again
etUsername.setBackgroundColor(Color.rgb(255, 204, 204));
etPassword.setBackgroundColor(Color.rgb(255, 204, 204));
}
}
});
}
}
private void renderCommunityView() {
setContentView(R.layout.activity_community);
}
private class AsyncHttpReading extends AsyncTask<String, Void, String> {
private String response = "";
private User loggedInUser = null;
public AsyncHttpReading() { }
public String getResponse() {
return response;
}
public User getLoggedInUser() {
return loggedInUser;
}
@Override
protected String doInBackground(String... urls) {
HttpReader httpReader = new HttpReader(urls[0]);
response = httpReader.getResponse();
return response;
}
@Override
protected void onPostExecute(String response) {
try {
JSONObject userData = new JSONObject(this.getResponse()).getJSONObject("0");
if (userData != null) {
loggedInUser = new User(userData);
}
} catch (JSONException e) {
Log.e("SAMPLEPROJECT", "Could not parse json data!");
}
}
}
}
HttpReader.java 的
package com.alphavoice.sampleproject.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.util.Log;
public class HttpReader {
private String url = "";
public HttpReader(String url) {
this.url = url;
}
public String getURL() {
return url;
}
public String getResponse() {
URL urlObj = null;
HttpURLConnection connection = null;
// http request
try {
urlObj = new URL(url);
connection = (HttpURLConnection) urlObj.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
} catch (Exception e) {
Log.e("SAMPLEPROJECT", "Could not connect to web server!");
}
// read stream
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream()));
StringBuffer buffer = new StringBuffer();
char[] chars = new char[1024];
int read = 0;
while ((read = reader.read(chars)) != -1) {
buffer.append(chars, 0, read);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
Log.e("SAMPLEPROJECT", "Could not open stream!");
}
return null;
}
}
User.java 的
package com.alphavoice.sampleproject.util;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.util.Log;
public class HttpReader {
private String url = "";
public HttpReader(String url) {
this.url = url;
}
public String getURL() {
return url;
}
public String getResponse() {
URL urlObj = null;
HttpURLConnection connection = null;
// http request
try {
urlObj = new URL(url);
connection = (HttpURLConnection) urlObj.openConnection();
connection.setReadTimeout(10000);
connection.setConnectTimeout(15000);
connection.setRequestMethod("POST");
connection.setDoInput(true);
connection.setDoOutput(true);
} catch (Exception e) {
Log.e("SAMPLEPROJECT", "Could not connect to web server!");
}
// read stream
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(urlObj.openStream()));
StringBuffer buffer = new StringBuffer();
char[] chars = new char[1024];
int read = 0;
while ((read = reader.read(chars)) != -1) {
buffer.append(chars, 0, read);
}
reader.close();
return buffer.toString();
} catch (IOException e) {
Log.e("SAMPLEPROJECT", "Could not open stream!");
}
return null;
}
}