如何从我的android应用程序中使用全局变量从mysql中检索用户的登录ID?
我在android中很新。在我的应用程序中,我想当一个用户登录该用户的id被携带所有activity.Like一个会话管理。该用户id来自mysql数据库。我想要登录用户id到所有选项卡显示在主activity.I试图全局变量,但它并没有work.please给我一些解决方案....如何从我的android应用程序中使用全局变量从mysql中检索用户的登录ID?
LoginActivity
@Override
public void onClick(View view) {
// Get text from email and passord field
String email = UsernameEt.getText().toString();
String password = PasswordEt.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, email, password);
//finish();
Intent intent = new Intent(UserLogin.this, MainActivity.class);
startActivity(intent);
finish();
}
BackgroundWorker的类
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx){
context = ctx;
}
@Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://www.mybusket.com/pmsapp/webs/get_all_emp.php";
if (type.equals("login")){
try {
String email_id = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("email_id", "UTF-8")+"="+URLEncoder.encode(email_id, "UTF-8")+"&"
+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result="";
String line="";
while ((line = bufferedReader.readLine())!= null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
从这个类中验证电子邮件地址..我可以如何将保存在mysql数据库中的登录用户标识携带到所有活动中。
Android应用程序不是网络应用程序,所以你不需要“携带”任何东西。
如果您需要存储要与不同活动共享的userId,可以将其放置在SharedPreferences中。
我想运行会话以获取其他活动中的用户数据登录.. –
使用SharedPreferences – Juan
为什么不从数据库本身检索id在所有活动中? –
尝试使用共享首选项。 –
您可以使用SharedPreferences,或者创建一个用户类,它是singeton并且在扩展Application的类中,或者您可以使用SQLite数据库。这两种方法都能正常工作,但最简单的方法是SharedPrefernces,但要实现注销逻辑,您应该设置用户参数并保存SharedPreferences。 – Thracian