Thursday, May 31, 2012

Return result back to main Activity using SharedPreference android Example

These is second method (first is already discuss in previous post) to get result from call activity.

In this example I am use SharedPreferences to retrieve result from called activity.

This method is also used to get result from anywhere in application.
You can set result from any activity and get it from any activity.

Here is complete example of SharedPreferences and how to return result from called activity to main activity.

1.  Create main activity and call new activity using startActivityForResult
     
   
public class SharedPreferenceActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button btnGetResult=(Button) findViewById(R.id.btnResult);
       
        final Intent intent=new Intent(this,SecondActivity.class);
       
       
       
        btnGetResult.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                startActivityForResult(intent, 1);    // call new activity
               
            }
        });
       
    }
   
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
           
            SharedPreferences myPreferences=getSharedPreferences("MYPREF",    Activity.MODE_PRIVATE);    // get preference created in called activity.
           
            String str=myPreferences.getString("STR", "empty");    //here STR is variable name same as secondActivity
           
            TextView tv=(TextView) findViewById(R.id.tvShow);
           
            tv.setText(str);
       
    }
}


2.   SecondActivity set result in SharedPreferences

     public class SecondActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondlayout);
       
        final SharedPreferences myPreference=getSharedPreferences("MYPREF", Activity.MODE_PRIVATE);
       
        Button btnOk=(Button) findViewById(R.id.btnOk);
        btnOk.setOnClickListener(new OnClickListener() {
          
            @Override
            public void onClick(View v) {
                EditText etText=(EditText) findViewById(R.id.etText);
                String str=etText.getText().toString();
      
                              
                SharedPreferences.Editor editor=myPreference.edit();
          
                editor.putString("STR", str);  // put value in preference
                editor.commit();   // it is must if not commit preference then it not save.
              
                finish();    // finishes current activity
            }
        });
    }
}


3.  Register second activity in AndroidManifest.xml

       <activity android:name="SecondActivity"></activity>

Return Result back to main Activity Android example

To receive result back from called activity you can use startActivityForResult() instead of startActivity() it override onActivityResult() to receive result.

Here is complete example of how to retrieve result from calling activity.

1.  Create class from which you want to start new activity.
     
    public class SetResultActivity extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        Button btnGetResult=(Button) findViewById(R.id.btnResult);
       
        final Intent intent=new Intent(this,SecondActivity.class);
       
        btnGetResult.setOnClickListener(new OnClickListener() {
          
            @Override
            public void onClick(View v) {
                startActivityForResult(intent, 1);    // call new activity
              
            }
        });
       
       
    }
   
    // these method call when called activity finished.


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        super.onActivityResult(requestCode, resultCode, data);
      
   
        if(resultCode==1)           // check result code set in secondActivity that is 1
        {
          
            String str=data.getStringExtra("STR");
          
            TextView tv=(TextView) findViewById(R.id.tvShow);
          
            tv.setText(str);
        }
        else
            Log.i("Result", "not Receive");
    }

}



2.    Create second Activity from which you want to receive result.

        public class SecondActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.secondlayout);
       
        final Intent intent=new Intent();
       
        Button btnOk=(Button) findViewById(R.id.btnOk);
        btnOk.setOnClickListener(new OnClickListener() {
           
            @Override
            public void onClick(View v) {
                EditText etText=(EditText) findViewById(R.id.etText);
                String str=etText.getText().toString();
       
                               
                intent.putExtra("STR", str);    // set value in intent
               
                setResult(1,intent);    // set result here 1 is result code used in when    //we  return multiple result back to main activity
 
                finish();    // finishes current activity
            }
        });
    }
}


3. Register secondActivity in AndroidManifest.xml

       <activity android:name="SecondActivity"></activity>

Starting New Activity from another activity

If you want to start new activity from existing activity then follow following steps:

1.   right-click on package in which you want to create new activity then after select new -> class -> enter class name -> finish

It create new class on your package as show below.

          public class SecondActivity {

          }

2.  Extend Activity class

public class SecondActivity extends Activity {


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

      }
}

3. Register newly created activity in your AndroidManifest.xml

           <activity  android:label="Test"
            android:name=".SecondActivity" >
        </activity>

4.  in main activity from you want to start new activity write following code

        - Create intent
                Intent intent=new Intent(this,SecondActivity.class);
       - start Activity
                 startActivity(intent);