Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在android中使用SharedReferences自动登录_Java_Android_Login_Sharedpreferences - Fatal编程技术网

Java 如何在android中使用SharedReferences自动登录

Java 如何在android中使用SharedReferences自动登录,java,android,login,sharedpreferences,Java,Android,Login,Sharedpreferences,我有一个splash活动,它将被定向到login活动,如果login为true,那么用户将被定向到home,但是当用户在home中按back时,应用程序将自动关闭。 但问题是,当用户打开应用程序时,他们必须再次登录,即使之前没有注销。那么,如何将飞溅引入家庭活动呢?我读过,为了处理它,我必须使用SharedReferences,所以我必须使用它,但我不知道如何使用它来处理自动登录。 这是我的spash: public class SplashEpolicy extends Activity {

我有一个splash活动,它将被定向到login活动,如果login为true,那么用户将被定向到home,但是当用户在home中按back时,应用程序将自动关闭。 但问题是,当用户打开应用程序时,他们必须再次登录,即使之前没有注销。那么,如何将飞溅引入家庭活动呢?我读过,为了处理它,我必须使用SharedReferences,所以我必须使用它,但我不知道如何使用它来处理自动登录。 这是我的spash:

public class SplashEpolicy extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    //hide title bar
    BasicDisplaySettings.toggleTaskBar(SplashEpolicy.this, false);
    //show status bar
    BasicDisplaySettings.toggleStatusBar(SplashEpolicy.this, true);

    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splash_epolicy);

    Thread timer = new Thread() {
        public void run() {
            try {
                //this is configuration for how long the splash will be shown.
                //
                int time = Integer.parseInt(getResources().getString(R.string.splashTransTime));
                sleep(time);
            } catch (InterruptedException e) {
                // TODO: handle exception
                e.printStackTrace();
            } finally {
                //line below is for direct new activity that will be run after 
                //current activity finished.
                Intent intent = new Intent(SplashEpolicy.this,EpolicyMainActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);      
                finish();
            }
        }
    };
    timer.start();      
}
这是包含SharedReference的我的登录活动:

                String KEY = jo.getString("key");
                SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
                SharedPreferences.Editor editor = settings.edit();
                editor.putString("etUser", strUser);
                editor.putString("key",KEY);
                editor.commit();
                System.out.println(KEY+""+"key"+""+"etUser");

                Dialog.dismiss();
                Intent i = new Intent(LoginActivity.this,EpolicyMainTab.class);
                startActivity(i);

        }
        }catch (JSONException e) {
            e.printStackTrace();
        }
这就是我的家(EpolicySpolisactivity):

公共类EpolicyListPolis扩展了ListActivity{
静态字符串PEMEGANG=“PEMEGANG”;
静态字符串POLIS=“POLIS”;
静态字符串STATUS=“STATUS”;
静态字符串TERTANGGUNG=“TERTANGGUNG”;
串键;
List NasabahList=new ArrayList();
私人对话;
私有字符串strStorage Path=“”,
strNameFileDiv=“”;
图像视图注销按钮;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setTitle(R.string.Nomor_Polis);
setContentView(R.layout.epolicy\u list\u polis);
SharedReferences设置=GetSharedReferences(“首选项名称”,0);
strUser=settings.getString(“etUser”,null);
KEY=settings.getString(“KEY”,null);
LogoutButton=(ImageView)findViewById(R.id.LogoutButton);
新建NasabahAsyncTask().execute();
LogoutButton.setOnClickListener(新的OnClickListener(){
公共void onClick(视图v){
dialogSignOut();
}
});
}
公共类NasabahAsyncTask扩展异步任务{
字符串url=(“http://www.example.com?i=“+strUser+”&k=“+键);
NasabahAsyncTask公共图书馆(){
this.url=url;
//TODO自动生成的构造函数存根
}
受保护的void onPreExecute(){
super.onPreExecute();
Dialog=ProgressDialog.show(EpolicyListPolis.this,“,”Melakukan Pengambilan Data”);
}
@凌驾
受保护字符串doInBackground(无效…参数){
字符串结果=”;
试一试{
结果=Connection.get(url);
}捕获(例外e){
结果=”;
Log.d(“测试查看器”,e.getMessage());
}
返回结果;
}
@凌驾
受保护的void onPostExecute(字符串结果){
super.onPostExecute(结果);
fetchResponse(result.replace(“\n”和“).trim());
ListAdapter=新的SimpleAdapter(
EpolicyListPolis.this,NasabahList,R.layout.epolicy_polis_listitem,
新字符串[]{POLIS,PEMEGANG,TERTANGGUNG,STATUS},新int[]{R.id.POLIS,R.id.PEMEGANG,R.id.TERTANGGUNG,R.id.STATUS});
setListAdapter(适配器);
Dialog.dismise();
ListView lv=getListView();
lv.setOnItemClickListener(新的OnItemClickListener(){
@凌驾
public void onItemClick(AdapterView父级、视图、,
内部位置,长id){
字符串POLIS=((TextView)view.findviewbyd(R.id.POLIS)).getText().toString();
SharedReferences设置=GetSharedReferences(“首选项名称”,0);
SharedReferences.Editor=settings.edit();
编辑:putString(“POLIS”,POLIS);
commit();
}
}
私有void fetchResponse(字符串结果){
//TODO自动生成的方法存根
如果(!result.equals(“”){
试一试{
JSONArray JSONArray=新JSONArray(结果);
for(int i=0;i    public class EpolicyListPolis extends ListActivity {
    static String PEMEGANG="PEMEGANG";
    static String POLIS="POLIS";
    static String STATUS="STATUS";
    static String TERTANGGUNG="TERTANGGUNG";
    String KEY, strUser;
    List NasabahList= new ArrayList();
    private ProgressDialog Dialog;
    private String strStoragePath = "",
            strNameFileDiv = "";
    ImageView LogoutButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle(R.string.Nomor_Polis);


        setContentView(R.layout.epolicy_list_polis);
        SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
        strUser= settings.getString("etUser", null);
        KEY = settings.getString("key", null);
        LogoutButton=(ImageView)findViewById(R.id.LogoutButton);

        new NasabahAsyncTask().execute();

        LogoutButton.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                dialogSignOut();
            }
        });
            }
public class NasabahAsyncTask extends AsyncTask<Void, Void, String>{
    String url = ("http://www.example.com?i="+strUser+"&k="+KEY);
    public NasabahAsyncTask() {
        this.url=url;
        // TODO Auto-generated constructor stub
    }

    protected void onPreExecute() {
        super.onPreExecute();   
        Dialog = ProgressDialog.show(EpolicyListPolis.this, "", "Melakukan Pengambilan Data");
    }

@Override
protected String doInBackground(Void... params) {
    String result="";
    try {
        result=Connection.get(url);
    }catch (Exception e){
        result=" ";
        Log.d("test viewer",e.getMessage());
    }
    return result;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    fetchResponse(result.replace("\n", "").trim());

    ListAdapter adapter = new SimpleAdapter(
            EpolicyListPolis.this, NasabahList, R.layout.epolicy_polis_listitem,
            new String[] {POLIS, PEMEGANG, TERTANGGUNG, STATUS}, new int [] {R.id.polis, R.id.pemegang, R.id.tertanggung, R.id.status});

        setListAdapter(adapter);
    Dialog.dismiss();
    ListView lv = getListView();

    lv.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                int position, long id) {

            String POLIS = ((TextView)view.findViewById(R.id.polis)).getText().toString();

            SharedPreferences settings = getSharedPreferences("PREFS_NAME", 0);
            SharedPreferences.Editor editor = settings.edit();
            editor.putString("POLIS", POLIS);
            editor.commit();
            }
}

private void fetchResponse(String result) {
    // TODO Auto-generated method stub
    if (!result.equals("")) {
        try {
            JSONArray jsonArray = new JSONArray(result);
            for (int i = 0; i < jsonArray.length(); i++) {

                JSONObject jsonObject = jsonArray.getJSONObject(i);
                HashMap<String, String> map = new HashMap<String, String>();
                if (jsonObject.has("PEMEGANG")) 
                    map.put("PEMEGANG", jsonObject.get("PEMEGANG").toString());
                if (jsonObject.has("POLIS")) 
                    map.put("POLIS", jsonObject.get("POLIS").toString());
                if (jsonObject.has("STATUS")) 
                    map.put("STATUS", jsonObject.get("STATUS").toString());
                if (jsonObject.has("TERTANGGUNG")) 
                    map.put("TERTANGGUNG", jsonObject.get("TERTANGGUNG").toString());
                NasabahList.add(map);
                System.out.println("json oke");
}
        }catch (JSONException e) {

            e.printStackTrace();
        }

        }
    }
@Override
public void onBackPressed() {
    dialogExit();
}
public void dialogExit()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("do you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Ya", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                   Intent itSplashEnd = new Intent(EpolicyListPolis.this, SplashEnd.class);
                   //setIntent.addCategory(Intent.CATEGORY_HOME);
                   itSplashEnd.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
                   itSplashEnd.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                   startActivity(itSplashEnd);
                   finish();
                   System.exit(0);
               }
           })
           .setNegativeButton("no", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();
    alert.show();
}

public void dialogSignOut()
{
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage("Sign out?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
               // what will i do here?

                   Intent itSignOut = new Intent(EpolicyListPolis.this, EpolicyMainActivity.class);
                   itSignOut.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                   startActivity(itSignOut);
                   finish();
               }
           })
           .setNegativeButton("no", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    dialog.cancel();
               }
           });
    AlertDialog alert = builder.create();
    alert.show();
}

    }
SharedPreferences prefs = this.getSharedPreferences("YOUR_PREF_NAME", Context.MODE_PRIVATE);

String loginID = prefs.getString("LOGIN_ID", "");
String loginPWD = prefs.getString("LOGIN_PWD", "");

if (loginID.length()>0 && loginPWD.length()>0) {
     //YOUR LOGIN CODE
} else {
     //SHOW PROMPT FOR LOGIN DETAILS
}
SharedPreferences prefs = this.getSharedPreferences("YOUR_PREF_NAME", Context.MODE_PRIVATE);
Editor editor = prefs.edit();
editor.putString("LOGIN_ID", "");     //RESET TO DEFAULT VALUE
editor.putString("LOGIN_PWD", "");     //RESET TO DEFAULT VALUE
editor.commit();
SharedPreferences sharedPrefs = getSharedPreferences("youPrefsFile", 0);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putBoolean("isLoggedIn", true);
editor.commit();
SharedPreferences settings = getSharedPreferences("youPrefsFile",0);
boolean isLoggedin = settings.getBoolean("isLoggedIn", false);
        boolean signedflag=false;
SharedPreferences prefs = this.getSharedPreferences("com.project.myProject", Context.MODE_PRIVATE);
String savedUser = "com.project.myProject.savedUser";
String user = prefs.getString(savedUser, "none"); // return "none" if user is not logged in
String savedPass = "com.project.myProject.savedPass";
String pass = prefs.getString(savedPass, "none");

if (user.equalsIgnoreCase("none") || pass.equalsIgnoreCase("none")) {
    // Show a log in dialog and/or other stuff to let user log in
} else {
    // Launch your main interface
}
YourActivity.this.getSharedPreferences("com.project.myProject", Context.MODE_PRIVATE).edit().clear().commit();
Intent intent = new Intent(SplashEpolicy.this,EpolicyMainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);      
finish();
<activity
    android:name="com.project.myProject.SplashEpolicy"
    android:label="@string/app_name"
    android:noHistory="true" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
SharedPreferences sharedPrefs = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putBoolean("isLoggedIn", true);
editor.commit();
SharedPreferences prefs = this.getSharedPreferences("MyPref", Context.MODE_PRIVATE);
boolean isLoggedIn = prefs.getString(isLoggedIn, false); // return "false" if user is not logged in

if (!isLoggedIn) {
    // Show a log in dialog and/or other stuff to let user log in
} else {
    // Launch your main interface
}