我的主要活动启动一个视图与另一个视图,具体取决于用户是否登录。它根据是否输入了一些共享首选项来检查用户是否登录。
在我的主要内容中,我确定使用此代码显示哪个视图:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//check if user is logged in
SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_PRIVATE);
String prefName = myPrefs.getString("userName", null);
String userID = myPrefs.getString("userID", null);
if(prefName == null && userID == null ){
setContentView(R.layout.activity_login);
}
else{
setContentView(R.layout.activity_main);
}
如果我进入登录视图,用户输入他们的详细信息,如果他们的登录成功,我想返回将活动更改为正常的 R.layout.activity_main ,我无法在我的末尾弄清楚如何做异步任务:
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 normal activity
Intent i = new Intent(c, MainActivity.class);
i.setClass(c, MainActivity.class);
startActivity(i);
}
}
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();
}
}