Reputation: 4559
Actually i want to call a function of one activity from another activity..i write a simple code for that but its not working..and show runtime error..please check the code...if there any mistake..
code for activity1:
public class Activity1 extends Activity2
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
call();
}
public void call()
{
showToast("Helloo");
}
}
code for activity2:
public class Activity2 extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void showToast(String s)
{
EditText t=(EditText)findViewById(R.id.editText1);
t.setText(s);
}
}
Upvotes: 2
Views: 12607
Reputation: 445
if you put it in as static you should declare it on your main activity
Upvotes: 1
Reputation: 36045
Your problem is that you're calling findViewById
on a view that doesn't exist.
Activity1
is extending Activity2
.
You call the super.onCreate
in Activity1
which calls the onCreate
in Activity2
which calls setContentView()
for R.layout.main
.
I'm guessing your text R.id.editText1
is in the main layout.
When Activity1
returns from the call to super.onCreate
it immediately resets the content layout to main2
.
The edit text box that you are trying to edit no longer exists. findViewById
can not find it because the layout is not active. Thus it crashes.
To fix it try this:
public class Activity1 extends Activity2
{
private EditText et;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
et = (EditText) findViewById(R.id.editText2);
call();
}
public void call()
{
showToast("Helloo", et);
}
}
Where R.id.editText2
is an edit text box in the layout main2
.
In Activity2:
public class Activity2 extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void showToast(String s, EditText t)
{
t.setText(s);
}
}
Upvotes: 3
Reputation: 40218
The simplest way is to declare your showToast()
method as public static
, this way you can call it without having an instance of Activity2
.
Upvotes: 1
Reputation: 53516
First, this is a bad design principle since only one Activity is active at a time. You can make a method static and then you can cross call them but at that point it should be in some sort of common util class.
Upvotes: 2