Tuesday, July 10, 2012

Calling One Activity from non activity class



Click here to download source code

Package name  : selva.activity

Project name    : callactivity

verssion            : 1.5 (supports 1.5 and above)


main.xml

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

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click to move next Activity" />

</LinearLayout>




CallactivityActivity.java

package selva.activity;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.content.Intent;

public class CallactivityActivity extends Activity
{

String str="";

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

     setContentView(R.layout.main);
    
     Bundle extras = getIntent().getExtras();
     if (extras!=null)
     {
        str = extras.getString("val");

        // get the string stored in val which is passed from Nonactivityclass.java
        Toast.makeText(getApplicationContext(),str,Toast.LENGTH_LONG).show();
         
     }
    
      Button btn=(Button) findViewById(R.id.button1);
     
      btn.setOnClickListener(new View.OnClickListener()
      {
       
        @Override
        public void onClick(View v)
        {
            // TODO Auto-generated method stub
            Intent i=new Intent(CallactivityActivity.this,Nonactivityclass.class);
            startActivity(i);
           
        }
    });
     
}
      
     

}





Nonactivityclass.java



package selva.activity;

import android.content.Intent;
import android.os.Bundle;

public class Nonactivityclass extends CallactivityActivity{
   
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
       
       
       
        Intent i = new Intent();
       
        i.setClass(Nonactivityclass.this, CallactivityActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
       
        Bundle extras = new Bundle();
        extras.putString("val", "This is from non-activity class");

      // pass the string   "This is from non-activity class" to "val" key
        i.putExtras(extras);
        startActivityForResult(i, 1);
       
    }

 }




OUTPUT:


 






































































Click here to download source code


No comments:

Post a Comment