Saturday, 11 April 2015

Storing Values in Android


Intent


How to use putExtra() and getExtra()


Use this to "put" the file...

Intent i = new Intent(FirstScreen.this, SecondScreen.class);
i.putExtra("name", "value");

Then, to retrieve the value try ...

Bundle b = getIntent().getExtras();
if(b!=null){
String j = b.getString("name");
}

Example :-

first Screen.java
text=(TextView)findViewById(R.id.tv1);
edit=(EditText)findViewById(R.id.edit);
button=(Button)findViewById(R.id.bt1);
button.setOnClickListener(new OnClickListener() {
    public void onClick(View arg0) {
        String s=edit.getText().toString();
        Intent i=new Intent(MainActivity.this, newclass.class);
        i.putExtra("name", s);
        startActivity(i);
    }
});

Second Screen.java
public class newclass extends Activity
{
    private TextView Textv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.intent);
        Textv = (TextView)findViewById(R.id.tv2);
        Bundle b = getIntent().getExtras();
        if(b!=null)
        {
            String j =(String) b.get("name");
        }
    }

}


Shared Preferences


Use this to "put" the file...

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getContext());
Editor editor = prefs.edit();
editor.putString(PREF_NAME, "");
editor.commit();

Then, to retrieve the value try ...

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(YouActivity.this);

String servername = settings.getString("sharedPreferencesKey", "defaultValue");
server.setText(servername);

No comments:

Post a Comment