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);
}
}
Your problem is that you’re calling
findViewByIdon a view that doesn’t exist.Activity1is extendingActivity2.You call the
super.onCreateinActivity1which calls theonCreateinActivity2which callssetContentView()forR.layout.main.I’m guessing your text
R.id.editText1is in the main layout.When
Activity1returns from the call tosuper.onCreateit immediately resets the content layout tomain2.The edit text box that you are trying to edit no longer exists.
findViewByIdcan not find it because the layout is not active. Thus it crashes.To fix it try this:
Where
R.id.editText2is an edit text box in the layoutmain2.In Activity2: