在我的上一篇文章中,有人告诉我我的结构一团糟,所以我已经改变了它,所以我不想从一个活动中做所有事情。
我的 loginactivity 获取登录详细信息,然后调用 asycn 任务来检查用户是否存在于我的外部数据库中:
public class LogIn extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
public void logIn(View view){
EditText textU;
EditText textP;
//get userName and password from edit text
textU = (EditText)findViewById(R.id.Username);
textP = (EditText)findViewById(R.id.Password);
String userName = textU.getText().toString();
String passW = textP.getText().toString();
Log.d("logIN", userName);
Log.d("logIN", passW);
//log in url
String url = "myURL";
String userURLComp = "u=" + userName;
String pURLComp = "&p=" + passW;
url = url + userURLComp + pURLComp;
Log.d("URL", url);
//async task for getting json
new ReadLogInJSON(this).execute(url);
}
}
我的问题是,在异步任务检查用户是否在数据库中之后,我不知道如何从异步任务启动新活动:
public class ReadLogInJSON extends AsyncTask
<String, Void, String> {
Context c;
public ReadLogInJSON(Context context)
{
c = context;
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPostExecute(String result){
//decode json here
try{
JSONObject json = new JSONObject(result);
String status = json.getString("status");
if(status.equals("no")){
//toast logIN failed
String message = "Log In Failed";
Toast.makeText(c, message, Toast.LENGTH_SHORT).show();
}
else{
//get userName
String userName = json.getString("userName");
//get user ID
String userID = json.getString("userID");
//set preferences
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(c);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("userName",userName);
editor.putString("userID",userID);
editor.commit();
//launch new activity
}
}
catch(Exception e){
}
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
更新:
我试着用这个启动它:
c.startActivity(new Intent(c, Search.class));
但没有启动。