想要使用sharedpreference

时间:2016-05-18 13:23:23

标签: android

先生..我在 activity_main.xml 中有可点击的文本视图,点击该文本视图后,我将转到注册。 xml ,我将在EditText中提供电话号码,我想使用共享偏好保存该号码,我需要在我点击的textView上显示之前 activity_main.xml 上显示的号码当我点击退出按钮时,数字应该删除,之前的textview应该替换。请有人帮我清楚。

activity_main.xml中

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.tasknumberchange.MainActivity" >

<TextView
    android:id="@+id/welcome"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="80dp"
    android:text="@string/welcome"
    android:textSize="25sp"
    android:textStyle="bold" />

<TextView
    android:id="@+id/clickForRegistration"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@id/welcome"
    android:layout_below="@id/welcome"
    android:layout_marginLeft="30dp"
    android:layout_marginTop="80dp"
    android:onClick="RegisterHere"
    android:clickable="true"
    android:text="@string/click_text"
    android:textSize="15sp" />

<ImageView 
    android:id="@+id/line"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/clickForRegistration"
    android:layout_below="@+id/clickForRegistration"
    android:layout_alignRight="@+id/clickForRegistration"
    android:src="@drawable/line"/>

<Button
    android:id="@+id/logout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_marginBottom="10dp"
    android:onClick="LogOut"
    android:clickable="true"
    android:background="@drawable/save_styles"
    android:text="@string/logout"
    android:textColor="#FFFFFF"
    android:textSize="25sp" />

</RelativeLayout>

MainActivity.java

package com.example.tasknumberchange;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class MainActivity extends Activity {
    TextView txt1,txt2;

    public static SharedPreferences sh;
    public static Editor editor;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txt1=(TextView)findViewById(R.id.clickForRegistration);

        //txt2=(TextView)findViewById(R.id.replace);
        sh = getSharedPreferences("MyPrefs", 0);
        txt1.setText(sh.getString("PhoneNo",""));
        txt1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent =new Intent(MainActivity.this,RegistrationPage.class);
                startActivity(intent);
            }

        });

    }

    public void LogOut(View view)
    {
        sh=getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
        SharedPreferences.Editor sh_editor = sh.edit();
        sh_editor.clear();
        sh_editor.commit();
    }
}

registration.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <EditText
        android:id="@+id/phoneDetails"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:drawableLeft="@drawable/phone"
        android:drawableStart="@drawable/phone"
        android:ems="10"
        android:paddingLeft="5dp"
        android:gravity="center"
        android:hint="@string/phone_number"
        android:inputType="phone" />

    <Button
        android:id="@+id/savePhoneNumber"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_marginBottom="10dp"
        android:background="@drawable/save_styles"
        android:text="@string/save"
        android:textColor="#FFFFFF"
        android:textSize="25sp" />

</RelativeLayout>

RegistrationPage.java

package com.example.tasknumberchange;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class RegistrationPage extends Activity implements OnClickListener
{
    Button save;
    EditText phoneNumber;
    String st_phoneNumber;
    public static final String MyPREFERENCES = "MyPrefs";
    public static final String Phone="PhoneNo";
     SharedPreferences sharedpreferences;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registration);

        phoneNumber=(EditText)findViewById(R.id.phoneDetails);
        save=(Button)findViewById(R.id.savePhoneNumber);
        sharedpreferences=getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);


        save.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                st_phoneNumber=phoneNumber.getText().toString();
                SharedPreferences.Editor editor=sharedpreferences.edit();
                editor.putString(Phone, st_phoneNumber);
                editor.commit();
                Toast.makeText(RegistrationPage.this,"Thanks",Toast.LENGTH_LONG).show();
                Intent intent=new Intent(v.getContext(),MainActivity.class);
                intent.putExtra("MyNumber",st_phoneNumber);
                startActivity(intent);
            }
        });

    }
       @Override
       public boolean onCreateOptionsMenu(Menu menu) {
          // Inflate the menu; this adds items to the action bar if it is present.
          getMenuInflater().inflate(R.menu.main, menu);
          return true;
       }
       @Override
       public boolean onOptionsItemSelected(MenuItem item) {
          // Handle action bar item clicks here. The action bar will
          // automatically handle clicks on the Home/Up button, so long
          // as you specify a parent activity in AndroidManifest.xml.

          int id = item.getItemId();

          //noinspection SimplifiableIfStatement
          if (id == R.id.action_settings) {
             return true;
          }
          return super.onOptionsItemSelected(item);
       }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }

}

3 个答案:

答案 0 :(得分:0)

使用onResume()。当活动返回屏幕时调用此函数。您可以通过此功能获得意图并在文本视图中更改文本。

答案 1 :(得分:0)

  

编辑2:

像这样更改您的MainActivity:

public class MainActivity extends Activity {

TextView txt1,txt2;

public  SharedPreferences sh;
public  SharedPreferences.Editor editor;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txt1=(TextView)findViewById(R.id.clickForRegistration);

    //txt2=(TextView)findViewById(R.id.replace);
    sh = getSharedPreferences("MyPrefs", 0);
    if(!sh.getString("PhoneNo","").isEmpty())
        txt1.setText(sh.getString("PhoneNo",""));
    txt1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent =new Intent(MainActivity.this,RegistrationPage.class);
            startActivity(intent);
        }

    });

}

public void LogOut(View view)
{
    sh=getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
    SharedPreferences.Editor sh_editor = sh.edit();
    sh_editor.clear();
    sh_editor.commit();

    //Start all over again..!!

    Intent intent1 = new Intent(this, MainActivity.class);
    intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(intent1);
    finish();
}

}

我已经尝试过这个并且完美地为我工作。希望这也有助于你:)

答案 2 :(得分:0)

只需更改下面的主要活动,如果工作正常,请尝试了解代码并告知我是否有任何问题。

      package com.example.tasknumberchange;

      import android.app.Activity;
      import android.content.Context;
      import android.content.Intent;
      import android.content.SharedPreferences;
      import android.content.SharedPreferences.Editor;
      import android.os.Bundle;
      import android.view.View;
      import android.view.View.OnClickListener;
      import android.widget.TextView;

      public class MainActivity extends Activity {

            TextView txt1,txt2;

            public static SharedPreferences sh;
            public static Editor editor;

          @Override
          protected void onCreate(Bundle savedInstanceState) {
               super.onCreate(savedInstanceState);
               setContentView(R.layout.activity_main);
              txt1=(TextView)findViewById(R.id.clickForRegistration);

             sh = getSharedPreferences("MyPrefs", 0);
             txt1.setText(sh.getString("PhoneNo",""));
             txt1.setOnClickListener(new OnClickListener() {

           @Override
           public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent intent =new Intent(MainActivity.this,RegistrationPage.class);
                startActivity(intent);
           }

       });

   }

   public void LogOut(View view)
   {
       sh=getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
       SharedPreferences.Editor sh_editor = sh.edit();
       sh_editor.remove("PhoneNo");
       sh_editor.clear();
       sh_editor.commit();

       txt1.setText(getResources().getString(R.string.click_text));

    }

    @Override
    public void onResume(){
    super.onResume();

     setValues();
    }

    public void setValues()
    {
       sh = getSharedPreferences("MyPrefs", 0);
       txt1.setText(sh.getString("PhoneNo",""));
    }


}