在我的上一篇文章中,我被告知我的结构全部搞砸了所以我已经改变了它所以我不是试图从一个活动做所有事情。
我的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));
但没有推出。
答案 0 :(得分:1)
首先,您确实应该在逻辑上为您的类名添加后缀,例如“LoginAsyncTask”和“SearchActivity”。
其次,是的,启动活动的正确(和唯一)方式是调用startActivity(Intent)
:)
尝试在startActivity
之前和之后添加日志,以验证onPostExecute
是否真正运行。