Subscribe For Free Updates!

We'll not spam mate! We promise.

Wednesday, June 10, 2015

Android working with Shared Preference

Here is my MAIN CLass ie.., LAUNCHER. I am using a textviewand keeping in Sharedpreference as sp object and calling that textview in other class using sp.getSharedpreferenc Method:
package com.babu.sharedpreferencee;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

public class MainActivity extends Activity {

 EditText edt;
 SharedPreferences sp;


 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.share);

  edt=(EditText)findViewById(R.id.edt1);

  Button b=(Button)findViewById(R.id.btn1);
  b.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View arg0) {
    // TODO Auto-generated method stub
    String s=edt.getText().toString();

    SharedPreferences sp = getSharedPreferences("prefs", 0);

    SharedPreferences.Editor editor = sp.edit();

    editor.putString("enteredname", s);

    editor.commit();
    
    



    Intent i=new Intent(MainActivity.this,Second.class);
    startActivity(i);



   }
  });




 }



}
First XML
1:  First.xml  
2:  <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
3:    xmlns:tools="http://schemas.android.com/tools"  
4:    android:layout_width="match_parent"  
5:    android:layout_height="match_parent"  
6:    android:paddingBottom="@dimen/activity_vertical_margin"  
7:    android:paddingLeft="@dimen/activity_horizontal_margin"  
8:    android:paddingRight="@dimen/activity_horizontal_margin"  
9:    android:paddingTop="@dimen/activity_vertical_margin"  
10:    tools:context=".MainActivity" >  
11:    <TextView  
12:      android:id="@+id/txt"  
13:      android:layout_width="wrap_content"  
14:      android:layout_height="wrap_content"  
15:      android:text="@string/hello_world" />  
16:  </RelativeLayout>  
Share XML:
1:  <?xml version="1.0" encoding="utf-8"?>  
2:  <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
3:    android:layout_width="match_parent"  
4:    android:layout_height="match_parent"  
5:    android:orientation="vertical" >  
6:    <EditText  
7:      android:id="@+id/edt1"  
8:      android:layout_width="fill_parent"  
9:      android:layout_height="wrap_content" />  
10:    <Button  
11:      android:id="@+id/btn1"  
12:      android:layout_width="wrap_content"  
13:      android:layout_height="wrap_content"  
14:      android:text="Submit" />  
15:  </LinearLayout>  

Socializer Widget By Blogger Yard
SOCIALIZE IT →
FOLLOW US →
SHARE IT →

0 comments:

Post a Comment