I have a simple application that I'm trying to test. It has two activities and two buttons (each button goes to the other activity - MainActivity and MainActivity2), and I'm trying to make some simple Robotium tests of it. I am getting the following error:
java.lang.RuntimeException: Exception during suite construction at
android.test.suitebuilder.TestSuiteBuilder$FailedToCreateTests.testSuiteConstructionFailed(TestSuiteBuilder.java:238)
at java.lang.reflect.Method.invokeNative(Native Method) at
android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191) at
android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176) at
android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554)
at
android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1840)
Caused by: java.lang.reflect.InvocationTargetException at
java.lang.reflect.Constructor.constructNative(Native Method) at
java.lang.reflect.Constructor.newInstance(Constructor.java:423) at
android.test.suitebuilder.TestMethod.instantiateTest(TestMethod.java:87)
at android.test.suitebuilder.TestMethod.createTest(TestMethod.java:73)
at
android.test.suitebuilder.TestSuiteBuilder.addTest(TestSuiteBuilder.java:262)
at
android.test.suitebuilder.TestSuiteBuilder.build(TestSuiteBuilder.java:184)
at
android.test.InstrumentationTestRunner.onCreate(InstrumentationTestRunner.java:379)
at
android.app.ActivityThread.handleBindApplication(ActivityThread.java:5142)
at android.app.ActivityThread.access$1500(ActivityThread.java:156) at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1418)
at android.os.Handler.dispatchMessage(Handler.java:102) at
android.os.Looper.loop(Looper.java:157) at
android.app.ActivityThread.main(ActivityThread.java:5872) at
java.lang.reflect.Method.invokeNative(Native Method) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:674) at
dalvik.system.NativeStart.main(Native Method) Caused by:
java.lang.NullPointerException at
android.view.ViewConfiguration.get(ViewConfiguration.java:338) at
android.view.View.(View.java:3490) at
android.view.View.(View.java:3547) at
android.widget.TextView.(TextView.java:674) at
android.widget.Button.(Button.java:107) at
android.widget.CompoundButton.(CompoundButton.java:68) at
android.widget.CheckBox.(CheckBox.java:68) at
android.widget.CheckBox.(CheckBox.java:64) at
android.widget.CheckBox.(CheckBox.java:60) at
com.example.twoactivities.test.RobotiumTest1.(RobotiumTest1.java:19)
... 18 more
I've tried everything I can find, and none of those solutions work for me. (No parameters in constructor, checking build path to ensure JARs are in the right place, ensuring that my application under test is "debuggable", etc.)
My code is here:
package com.example.twoactivities.test;
import com.example.twoactivities.*;
import com.robotium.solo.Solo;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.CheckBox;
import android.widget.CheckBox;
import android.app.Activity;
public class RobotiumTest1 extends ActivityInstrumentationTestCase2<MainActivity> {
private Solo solo;
public RobotiumTest1() {
super(MainActivity.class);
}
#Override
public void setUp() throws Exception {
//setUp() is run before a test case is started.
//This is where the solo object is created.
solo = new Solo(getInstrumentation(), getActivity());
}
// #Override
// public void tearDown() throws Exception {
// //tearDown() is run after a test case has finished.
// //finishOpenedActivities() will finish all the activities that have been opened during the test execution.
// solo.finishOpenedActivities();
// }
public void testClickButton() throws Exception{
solo.assertCurrentActivity("Expected to be on MainActivity activity", "MainActivity.class");
solo.clickOnButton("Go to page 2");
solo.assertCurrentActivity("Not on Activity 2", MainActivity2.class);
solo.clickOnButton("Go to page 1");
solo.assertCurrentActivity("Not on Activity 1", MainActivity.class);
}
}
Any ideas how I can get this test to run?
Thanks,
Stephanie
EDIT:
MainActivity
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends Activity {
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);
final TextView text2 = (TextView) findViewById(R.id.checkBoxTextView);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void activity2(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity2.class);
startActivity(intent);
}
public void onCheckBoxClicked(View view){
if (checkBox.isChecked()) {
text2.setText("Checked");
}
else {
((TextView) findViewById(R.id.checkBoxTextView)).setText("Unchecked");
}
}
}
MainActivity2
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity2 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void activity1(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity.class);
startActivity(intent);
}
}
I actually haven't changed anything (I don't think) since it last ran successfully.
Sept 12 edits:
"solo" object was being initialized after I was trying to use it.
package com.example.twoactivities.test;
import com.example.twoactivities.*;
import com.example.twoactivities.R;
import com.robotium.solo.Solo;
import android.test.ActivityInstrumentationTestCase2;
import android.widget.CheckBox;
import android.widget.TextView;
public class RobotiumTest1 extends ActivityInstrumentationTestCase2<MainActivity> {
public Solo solo;
private TextView checkBoxText;
public CheckBox checkBox1 ;
public RobotiumTest1() {
super(MainActivity.class);
}
#Override
public void setUp() throws Exception {
//setUp() is run before a test case is started.
//This is where the solo object is created.
solo = new Solo(getInstrumentation(), getActivity());
checkBoxText = (TextView) getActivity().findViewById(R.id.checkBoxTextView);
checkBox1 = (CheckBox) getActivity().findViewById(R.id.checkBox1);
}
public void testClickButton() throws Exception{
solo.assertCurrentActivity("Expected to be on MainActivity activity", "MainActivity");
solo.clickOnButton("Go to page 2");
solo.assertCurrentActivity("Not on Activity 2", MainActivity2.class);
solo.clickOnButton("Go to page 1");
solo.assertCurrentActivity("Not on Activity 1", MainActivity.class);
}
The clue is in the log you posted.
Caused by: java.lang.NullPointerException
at android.view.ViewConfiguration.get(ViewConfiguration.java:338)
at android.view.View.(View.java:3490)
at android.view.View.(View.java:3547)
at android.widget.TextView.(TextView.java:674)
at android.widget.Button.(Button.java:107)
at android.widget.CompoundButton.(CompoundButton.java:68)
at android.widget.CheckBox.(CheckBox.java:68)
at android.widget.CheckBox.(CheckBox.java:64)
at android.widget.CheckBox.(CheckBox.java:60) at com.example.twoactivities.test.RobotiumTest1.(RobotiumTest1.java:19) ... 18 more
You have a NullPointerException causing you the issues, this NullPointerException is in your applications code not the code posted here however (Note if you add it, I will look into it here for you)
EDIT
The code below is the issue:
public class MainActivity extends Activity {
final CheckBox checkBox = (CheckBox) findViewById(R.id.checkBox1);
final TextView text2 = (TextView) findViewById(R.id.checkBoxTextView);
The problem is you are trying to find views that do not actually exist until onCreate() is called so these will be null. move the initialisation of these to onCreate() and you should be ok.
Next edit to answer your question in comments.
Ok so now we are away from Robotium and in to core Java, the issue you have now is scope, the thing is where you declare a variable and it is accesible is different to where you instantiate it. You can declare the variables existance in the same scope as you are currently but instantiate it in onCreate().
package com.example.twoactivities;
import com.example.twoactivities.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends Activity {
final CheckBox checkBox;
final TextView text2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkBox = (CheckBox) findViewById(R.id.checkBox1);
text2 = (TextView) findViewById(R.id.checkBoxTextView);
}
public void activity2(View view){
Intent intent = new Intent(this,com.example.twoactivities.MainActivity2.class);
startActivity(intent);
}
public void onCheckBoxClicked(View view){
if (checkBox.isChecked()) {
text2.setText("Checked");
}
else {
((TextView) findViewById(R.id.checkBoxTextView)).setText("Unchecked");
}
}
}
Related
We are working on creating a basic app in my online class and I keep running into this issue where the Instructions have us type a method with an #Override for an onClick. I was able to get one of the methods to work with an autofill help from A.S. itself but this next one won't fix itself out. I have run into other issues over this class as well and I know the Instructions are a few years old. Possibly out of date now?
I'm pretty new to Android Java and coding overall. It seems that the app is trying to use the onClick method incorrectly. I will post the whole class I'm working with because I'm not sure where the problem is exactly.
package com.test.firstandroidapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
public class InformationPageActivity extends AppCompatActivity {
Button btnSave;
Spinner spnSeason;
SeekBar skbTemp;
TextView lblSeekValue;
Switch swchAllergy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information_page);
spnSeason = (Spinner) findViewById(R.id.spnSeason);
skbTemp = (SeekBar) findViewById(R.id.skbTemp);
swchAllergy = (Switch) findViewById(R.id.swchAllergy);
lblSeekValue = (TextView) findViewById(R.id.lblSeekValue);
btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener((View.OnClickListener) this);
skbTemp.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
String display = String.valueOf(progress);
lblSeekValue.setText(display);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
public void onClick(View v) {
String season, allergies;
int temperature;
season = spnSeason.getSelectedItem().toString();
temperature=skbTemp.getProgress();
allergies = (String) (swchAllergy.isChecked() ? swchAllergy.getTextOn() : swchAllergy.getTextOff()); //if the switch is on then the user has allergies
Intent intent = new Intent(InformationPageActivity.this, InformationResultsActivity.class); //pass information to the results activity
intent.putExtra("season", season);
intent.putExtra("temperature", temperature);
intent.putExtra("allergies", allergies);
this.startActivity(intent);
}
}
And here is the Main Menu Class parts that go to the view i'm trying to have opened, The onclicklistener is inside the onCreate method and the goInfo is it's own method
Button btnInfo = (Button) findViewById(R.id.btnInfo);
btnInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goInfo();
}
}
);
}
private void goInfo() {
Intent intent = new Intent(MainMenuActivity.this, InformationPageActivity.class);
this.startActivity(intent);
}
I was able to find the issue. I needed to add an implements statement to the class for the onclicklistener. I'm answering my own question in case someone in the future has the same error. Here is what I did.
My problematic class was
public class InformationPageActivity extends AppCompatActivity {
This was causing the error "java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.firstandroidapp/com.test.firstandroidapp.InformationPageActivity}: java.lang.ClassCastException: com.test.firstandroidapp.InformationPageActivity cannot be cast to android.view.View$OnClickListener"
I solved the issue by fixing the class adding the implements
public class InformationPageActivity extends AppCompatActivity implements View.OnClickListener {
I created a ListDialog extending a DialogFragment class and I have a problem with understanding of this code in the DijalogX class
((MainActivity)getActivity()).setTextField(selectedItem);
I understand that with this code above I put selected String variable to the setTextField method as an argument and after that this variable is showed in TextView on MainActivity class.
My questions:
Why I need a cast from getActivity() to the MainActivity and how I get access from DijalogX(fragment) to the method setTextField in MainActivity? Please explain a little about this process.
I also tried instead of ((MainActivity)getActivity()).setTextField(selectedItem)
use an Interface and everything works nice and I got the same resoult but I am wondering what is better solution here Interface or ((MainActivity)getActivity()).setTextField(selectedItem)?
MainActivity
package com.example.dezox.dijaloglist;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity{
private Button btnStartDialog;
private TextView tvSelectedOption;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initWidgets();
setupListener();
}
private void initWidgets() {
btnStartDialog = findViewById(R.id.btnDialog);
tvSelectedOption = findViewById(R.id.tvselectedOption);
}
private void setupListener() {
btnStartDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DijalogX dijalogX = new DijalogX();
dijalogX.show(getSupportFragmentManager(), "dx");
tvSelectedOption.setText("");
}
});
}
public void setTextField(String odabrano){
tvSelectedOption.setText(odabrano);
}
public String getTextField(){
return tvSelectedOption.getText().toString();
}
}
DijalogX
package com.example.dezox.dijaloglist;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
public class DijalogX extends DialogFragment {
private String[] languageList;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initListResource();
}
private void initListResource() {
languageList = getResources().getStringArray(R.array.language_list);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
android.R.style.Theme_Material_Dialog_Alert)
.setTitle("Select Language: ")
.setItems(languageList, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String selectedItem = languageList[which];
//THIS PART OF THE CODE I DONT UNDERSTAND:
((MainActivity)getActivity()).setTextField(selectedItem);
}
});
return builder.create();
}
}
You have declared a method in MainActivity called setTextField. If you called
Activity a = getActivity();
you would not be able to call your custom method (it is on your derived class, not the base Activity class).
a.setTextField(selectedIte); // WON'T WORK - NO SUCH METHOD
If instead you call
MainActivity ma = (MainActivity)getActivity();
it is now cast as your derived class and you can then call
ma.setTextField(selectedItem);
Doing it in two lines like this is the same as calling the one-liner in your code
((MainActivity)getActivity()).setTextField(selectedItem);
As far as casting vs. an interface, an interface is a bit more flexible of an approach. If you tried to use this fragment in a different activity (not MainActivity) the casting approach would fail. If you are only ever going to use the fragment in this Activity then either would work.
Here, in my Custom Adapter class, while i am tracing the error which i have found after pressing on the image, it goes through the onClick method successfully, attain the intent, but it crashes when it attempts to start the second Activity.
package com.example.prof_mohamed.movieapp;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Prof-Mohamed on 8/3/2016.
*/
public class ImagesAdapter extends RecyclerView.Adapter<ImagesAdapter.ViewHOlder> {
private List<MovieEntity> feedItemList;
private Context mContext;
public ImagesAdapter(Context context, ArrayList<MovieEntity> feedItemList) {
this.feedItemList=feedItemList;
this.mContext= context;
}
#Override
public ImagesAdapter.ViewHOlder onCreateViewHolder(ViewGroup parent, int i) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_layout, null);
RecyclerView.ViewHolder viewHolder=new ViewHOlder(view);
return (ViewHOlder) viewHolder;
}
#Override
public void onBindViewHolder(ViewHOlder customViewholder, final int i) {
final MovieEntity feedItem=feedItemList.get(i);
Picasso.with(mContext).load(feedItem.getPOSTER_PATH_STRING()).into(customView holder.one_img);
customViewholder.one_text.setText(feedItem.getTITLE_STRING());
customViewholder.one_img.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext,DetailActivity.class)
.putExtra(Intent.EXTRA_TEXT,feedItem);
mContext.startActivity(intent);
}
});
}
#Override
public int getItemCount() {
return (null!=feedItemList?feedItemList.size():0);
}
public class ViewHOlder extends RecyclerView.ViewHolder {
protected ImageView one_img;
protected TextView one_text;
public ViewHOlder(View converview) {
super(converview);
this.one_img = (ImageView) converview.findViewById(R.id.img_view);
this.one_text = (TextView) converview.findViewById(R.id.txt_poster_title);
}
}
}
Here are my second Activity, which i have to send my data from the first Activity to it :
package com.example.prof_mohamed.movieapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class DetailActivity extends AppCompatActivity {
private static String mMovieStr;
TextView txtTitle=(TextView) findViewById(R.id.txt_title);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
Intent intent = getIntent();
if(intent != null&&intent.hasExtra(intent.EXTRA_TEXT)){
mMovieStr=intent.getStringExtra(intent.EXTRA_TEXT);
txtTitle.setText(mMovieStr);
}
}
}
This is my error result :
E/AndroidRuntime: FATAL EXCEPTION: main
android.util.AndroidRuntimeException: Calling startActivity() from outside of an Activity context requires the FLAG_ACTIVITY_NEW_TASK flag. Is this really what you want?
at android.app.ContextImpl.startActivity(ContextImpl.java:1278)
at android.app.ContextImpl.startActivity(ContextImpl.java:1265)
at com.example.prof_mohamed.movieapp.ImagesAdapter$1.onClick(ImagesAdapter.java:52)
at android.view.View.performClick(View.java:4432)
at android.view.View$PerformClick.run(View.java:18339)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5283)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
at dalvik.system.NativeStart.main(Native Method)
and after editing these lines inside the onClick method
#Override
public void onClick(View view) {
Intent intent = new Intent(mContext,DetailActivity.class)
.putExtra(Intent.EXTRA_TEXT,feedItem);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
}
it gave me a Null pointer Exception of the txtTitle (TextView) in the DetailActivity.java class.
Can anybody help me to solve this problem. your response will be appreciated.
Try adding the following code after creating the intent
myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try this:
Intent intent = new Intent(mContext,DetailActivity.class)
.putExtra(Intent.EXTRA_TEXT,feedItem);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(intent);
In your adapter class you are passing object,but in second activity you are trying to getStringExtra()
Read this it will be helpful
How to send an object from one Android Activity to another using Intents?
Please check you defined DetailActivity in manifest file.
feedItem is an object. You are passing this with intent and trying to get it from second activity as String, and that is the problem.
I am trying to switch Fragments, replace one with another.
I have the main frame layout - R.layout.fragment_container.
I can add the first Fragment successfully but when I try to change fragments I get an error.
When go to debug mode I do go to my onPageNavigationSelected function but have an exception
package com.book1;
import com.book1.Page1_fragment.onPageNavigationListener;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.widget.Toast;
public class MainActivity extends FragmentActivity
implements onPageNavigationListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_conteiner);
Page1_fragment page1 = new Page1_fragment();
page1.setArguments(getIntent().getExtras());
getSupportFragmentManager().beginTransaction()
.add(R.id.container, page1).commit();
}
#Override
public void onPageNavigationSelected(String back_forward) {
Page2_fragment page2 = new Page2_fragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container, page2);
transaction.addToBackStack(null);
transaction.commit();
}
my fragment code :
package com.book1;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.ImageButton;
import android.widget.ImageView;
public class Page1_fragment extends android.support.v4.app.Fragment
implements AnimationListener{
Animation move;
ImageView big_dood;
onPageNavigationListener callback_page_navigation;
public interface onPageNavigationListener{
public void onPageNavigationSelected(String back_forward);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.page1, container ,false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
big_dood = (ImageView)getActivity().findViewById(R.id.big_bood);
//ImageView black_hear_dood = (ImageView)getActivity().findViewById(R.id.black_hear_dood);
move=AnimationUtils.loadAnimation(getActivity(), R.anim.move_rigth);
move.setAnimationListener(this);
final ImageButton pop = (ImageButton)getActivity().findViewById(R.id.pop);
pop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
pop.startAnimation(move);
//Toast.makeText(getActivity(), "Animation Stopped", Toast.LENGTH_SHORT).show();
}
});
ImageButton forward =(ImageButton)getActivity().findViewById(R.id.forward);
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
callback_page_navigation.onPageNavigationSelected("page2");
//callback_page_navigation.onPageNavigationSelected("forward");
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
callback_page_navigation = (onPageNavigationListener)activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()+" must implement onPageNavigationListener");
}
}
#Override
public void onAnimationStart(Animation animation)
{}
#Override
public void onAnimationEnd(Animation animation) {
if (animation == move) {
//Toast.makeText(getActivity(), "Animation Stopped", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onAnimationRepeat(Animation animation)
{}
}
My log:
FATAL EXCEPTION: main
Process: com.book1, PID: 22241 java.lang.ClassCastException: com.book1.MainActivity#427ba210 must implement onPageNavigationListener
at com.book1.Page2_fragment.onAttach(Page2_fragment.java:87)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:894)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:446)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5017)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
From your log:
java.lang.ClassCastException: com.book1.MainActivity#427ba210 must implement onPageNavigationListener
at com.book1.Page2_fragment.onAttach(Page2_fragment.java:87)
The exception is being thrown in the OnAttach() method in Page2_fragment.
You have only shown us Page1_fragment but I will guess that you also define an Interface that the parent Activity must implement. and that you also called that Interface onPageNavigationListener.
The issue you are having is that there are now 2 Interfaces called onPageNavigationListener:
com.book1.Page1_fragment.onPageNavigationListener
and
com.book1.Page2_fragment.onPageNavigationListener
Since you only imported the first one, you do not actually implement the one that Page2_fragment requires. When your second Fragment tries to cast the parent Activity as a valid Listener you get your ClassCastException.
You have two choices. You can either:
Rename the second Interface and its method so that they do not clash with the first Fragment's Interface.
Make one (optional abstract) parent Fragment that defines one Interface. Extend that Fragment in both your PageX_fragments and then in your Activity import com.book1.ParentPageFragment.OnPageNavigationListener.
In the second option both Fragments will call the same method and it will be up to the Activity to work out which Fragment is calling it and what, if anything, to do differently.
Side note: You should name your Interfaces starting with an upper-case letter. OnPageNavigationListener not 'onPageNavigationListener`.
Well, I'm doing this app just for trial. And there's this error. It says:
04-21 04:11:41.618: E/AndroidRuntime(333): FATAL EXCEPTION: main
04-21 04:11:41.618: E/AndroidRuntime(333): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.windteste/com.example.windteste.MainActivity}: java.lang.NullPointerException
04-21 04:11:41.618: E/AndroidRuntime(333): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
04-21 04:11:41.618: E/AndroidRuntime(333): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
04-21 04:11:41.618: E/AndroidRuntime(333): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
..and a lot more lines of error. So, these are the two methods (Dfig and MainActivity):
package com.example.windteste;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
public class Dfig extends Activity{
#Override
protected void onCreate(Bundle blablu) {
// TODO Auto-generated method stub
super.onCreate(blablu);
setContentView(R.layout.activity_main);
MediaPlayer windsound = MediaPlayer.create(Dfig.this, R.raw.windsound);
windsound.start();
Thread timer = new Thread(){
public void run(){
try{
sleep(4000);
}catch (InterruptedException e){
e.printStackTrace();
}finally{
Intent openMain = new Intent("com.example.windteste.MAIN");
startActivity(openMain);
}
}
};
timer.start();
windsound.release();
}
}
package com.example.windteste;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.app.Activity;
import android.text.InputType;
----------------------------------------------------------------------------------
public class MainActivity extends Activity {
Button check = (Button) findViewById(R.id.calculator);
final EditText UserInput = (EditText) findViewById(R.id.windspeed);
final TextView P = (TextView) findViewById(R.id.potencia);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
UserInput.setInputType(InputType.TYPE_CLASS_NUMBER);
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Number Ws = (Number) UserInput.getText();
P.setText("Your total is " + Ws);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Well, I hope you can help me.
Thank you!
Try:
public class MainActivity extends Activity {
Button check;
final EditText UserInput;
final TextView P;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
check = (Button) findViewById(R.id.calculator);
UserInput = (EditText) findViewById(R.id.windspeed);
P = (TextView) findViewById(R.id.potencia);
//Rest is same
You cannot use findViewById() until after setContentView() has been called.
Make sure both the activities are listed in the manifest. What it looks like is MainActivity is not listed in your manifest file.