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`.
Related
After scanning the QR code normally, it stops running and cannot display the scanned content.
Barcode scanner (Main2Activity.java):
package com.example.barcodescanner;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
import com.google.zxing.Result;
import me.dm7.barcodescanner.zxing.ZXingScannerView;
public class Main2Activity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
private ZXingScannerView mScannerView;
#Override
public void onCreate(Bundle state) {
super.onCreate(state);
mScannerView = new ZXingScannerView(this); // Programmatically initialize the scanner view
setContentView(mScannerView); // Set the scanner view as the content view
}
#Override
public void onResume() {
super.onResume();
mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
mScannerView.startCamera(); // Start camera on resume
}
#Override
public void onPause() {
super.onPause();
mScannerView.stopCamera(); // Stop camera on pause
}
#Override
public void handleResult(Result rawResult) {
// Do something with the result here
MyFragment.textViewQr.setText(rawResult.getText());
onBackPressed();
}
}
Here is my Fragment that is using the above (MyFragment.java):
package com.example.barcodescanner;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import androidx.fragment.app.Fragment;
/**
* A simple {#link Fragment} subclass.
*/
public class MyFragment extends Fragment {
public MyFragment() {
// Required empty public constructor
}
static TextView textViewQr;
Button buttonScanner;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_my,container,false);
final TextView textViewQr = (TextView) view.findViewById( R.id.textViewQr );
final Button buttonScanner = (Button) view.findViewById( R.id.buttonScanner );
buttonScanner.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity( new Intent( getActivity(), Main2Activity.class ) );
}
} );
return view;
}
}
Logcat:
2020-03-13 10:54:50.267 20894-20927/com.example.Barcodescanner D/EGL_emulation: eglMakeCurrent: 0xa08052a0: ver 2 0 (tinfo 0xa0803340)
2020-03-13 10:54:52.959 20894-20894/com.example.Barcodescanner D/AndroidRuntime: Shutting down VM
--------- beginning of crash
2020-03-13 10:54:52.959 20894-20894/com.example.Barcodescanner E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.Barcodescanner, PID: 20894
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.Barcodescannerwith.Main2Activity.handleResult(Main2Activity.java:37)
at me.dm7.barcodescanner.zxing.ZXingScannerView$1.run(ZXingScannerView.java:164)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:866)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:756)
After scanning the QR code normally, it stops running, and the following tips:
Barcodescanner has stopped open app again
MyFragment.textViewQr.setText(rawResult.getText());
is Null because in fragment you are initializing another TextView.
This One:-
final TextView textViewQr = (TextView) view.findViewById( R.id.textViewQr );
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.
There is an error in this line:
addSlide(AppIntroSampleSlider.newInstance(R.layout.app_intro1));
addSlide (android.support.v4.app.Fragment)
In AppIntroBase, it cannot be applied
My code is here:
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
import com.github.paolorotolo.appintro.AppIntro;
/**
* Created by Arvind on 2/6/2017.
*/
public class MyIntro extends AppIntro {
#Override
public void init(Bundle savedInstanceState) {
//adding the three slides for introduction app you can ad as many you needed
addSlide(AppIntroSampleSlider.newInstance(R.layout.app_intro1));
addSlide(AppIntroSampleSlider.newInstance(R.layout.app_intro2));
addSlide(AppIntroSampleSlider.newInstance(R.layout.app_intro3));
// Show and Hide Skip and Done buttons
showStatusBar(false);
showSkipButton(false);
// Turn vibration on and set intensity
// You will need to add VIBRATE permission in Manifest file
setVibrate(true);
setVibrateIntensity(30);
//Add animation to the intro slider
setDepthAnimation();
}
#Override
public void onSkipPressed() {
// Do something here when users click or tap on Skip button.
Toast.makeText(getApplicationContext(),
getString(R.string.app_intro_skip), Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
}
#Override
public void onNextPressed() {
// Do something here when users click or tap on Next button.
}
#Override
public void onDonePressed() {
// Do something here when users click or tap tap on Done button.
finish();
}
#Override
public void onSlideChanged() {
// Do something here when slide is changed
}
}
I created a class i.e. AppIntroSampleSlider.
My AppIntroSampleSlider class is:
package com.example.arvind.appintro1;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by Arvind on 13-Feb-17.
*/
public class AppIntroSampleSlider extends Fragment {
private static final String ARG_LAYOUT_RES_ID = "layoutResId";
public static AppIntroSampleSlider newInstance(int layoutResId) {
AppIntroSampleSlider sampleSlide = new AppIntroSampleSlider();
Bundle bundleArgs = new Bundle();
bundleArgs.putInt(ARG_LAYOUT_RES_ID, layoutResId);
sampleSlide.setArguments(bundleArgs);
return sampleSlide;
}
private int layoutResId;
public AppIntroSampleSlider() {}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(getArguments() != null && getArguments().containsKey(ARG_LAYOUT_RES_ID))
layoutResId = getArguments().getInt(ARG_LAYOUT_RES_ID);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(layoutResId, container, false);
}
}
I want to why it is showing error in the code.So Please help me to solve this error.
I found a better example without error
http://www.androidhive.info/2016/05/android-build-intro-slider-app/
AppIntro library works best with the following import in your AppIntroSampleSlider.java file:
import android.support.v4.app.Fragment;
Instead of:
import android.app.Fragment;
I am trying to learn fragment.I am clicking a fragment class and my app crashes.I have declared it in the manifest..But why it is happening..My Menu class
public class Menu extends ListActivity {
String classes[] = { "SpinnerDemo", "GridDemo", "AutoCompleteDemo", "DynamicDemo",
"WebViewDemo1", "WebViewDemo3", "LaunchDemo", "LifecycleLoggingActivity", "IntentCheckActivity", "CallIntentActivity",
"MainFragmentDemoActivity", "Simplebrowser", "Flipper", "SharedPrefs", "Internaldata",
"Externaldata", "Sqliteexample", "GLexample", "TextVoice",
"StatusBar", "SeekBarVolume" };
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setListAdapter(new ArrayAdapter<String>(Menu.this,
android.R.layout.simple_list_item_1, classes));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Class ourclass;
String path = classes[position];
try {
ourclass = Class.forName("com.example.practise." + path);
Intent ourintent = new Intent(Menu.this, ourclass);
startActivity(ourintent);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
My MainFragmentDemoActivity class
public class MainFragmentDemoActivity extends Activity implements ListFragmentDemo.Communicator {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_fragmenttesting);
}
#Override
public void Message(String os_name) {
DetailFragmentDemo detail=(DetailFragmentDemo)getFragmentManager().findFragmentById(R.id.detail_Fragment);
if (detail != null && detail.isInLayout()) {
detail.setText(os_name);
}
}
My menifest
<activity
android:name="com.example.practise.MainFragmentDemoActivity"
android:label="MainFragmentDemoActivity" >
</activity>
I have two other class ListFragmentDemo and DetailFragmentDemo.These are the fragments which i am implemening from MainFragmentDemoActivity.My xml
<fragment
android:id="#+id/list_Fragment"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
class="com.example.practise.ListFragmentDemo"></fragment>
<fragment
android:id="#+id/detail_Fragment"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="2"
class="com.example.practise.DetailFragmentDemo">
</fragment>
logcat
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.practise/com.example.practise.MainFragmentDemoActivity}
Caused by: android.view.InflateException: Binary XML file line #8: Error inflating class fragment
Caused by: java.lang.ClassCastException: com.example.practise.ListFragmentDemo cannot be cast to android.app.Fragment
I am learning from this link
http://www.tutorialsbuzz.com/2014/03/android-fragments-example-ui-multi-pane.html
my ListFragmentDemo
package com.example.practise;
import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import static android.widget.AdapterView.*;
public class ListFragmentDemo extends Fragment implements View.OnClickListener {
private Communicator communicator;
Button android_btn, ios_btn, window_btn;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (activity instanceof Communicator) {
communicator = (Communicator) activity;
} else {
throw new ClassCastException(activity.toString() + "must implement ListFragmentDemo");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.list_fragment, container, false);
android_btn = (Button) view.findViewById(R.id.android_btn_id);
ios_btn = (Button) view.findViewById(R.id.ios_btn_id);
window_btn = (Button) view.findViewById(R.id.windows_btn_id);
android_btn.setOnClickListener(this);
ios_btn.setOnClickListener(this);
window_btn.setOnClickListener(this);
return view;
}
public interface Communicator {
public void Message(String os_name);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.android_btn_id:
updateFragment("Android");
break;
case R.id.windows_btn_id:
updateFragment("Windows");
break;
case R.id.ios_btn_id:
updateFragment("IOS");
break;
}
}
private void updateFragment(String os_name){
communicator.Message(os_name);
}
}
My DetailFragmentDemo
package com.example.practise;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DetailFragmentDemo extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.detail_fragment,container,false);
return view;
}
// we call this method when button from listfragment is clicked
public void setText(String item)
{
TextView textView=(TextView)getView().findViewById(R.id.display_tv);
textView.setText(item);
}
}
Your ListFragmentDemo extends from android.support.v4.app.Fragment (the support version of the Fragment class) and not android.app.Fragment (the version which is inside Android)
Change
import android.support.v4.app.Fragment;
to
import android.app.Fragment;
in the ListFragmentDemo class
Any Class that extends Activity in your application must be declared in the manifest, however, that does not appear to be your problem. Technically, this does answer your question though ;)
This line:
Caused by: java.lang.ClassCastException: com.example.practise.ListFragmentDemo cannot be cast to android.app.Fragment
Does "ListFragmentDemo" extend Fragment?
I think the problem is that you're Activity(Main Activity/ Activity that hosts the Fragments) doesn't extend the FragmentActivity class.
If you're using the Support Library for ActionBar, the just make sure your Activity class extends the ActionBarActivity class.
That's why your Fragments can't be cast into the Main Activity.(ClassCastException)
So it should be:
public class MainFragmentDemoActivity extends FragmentActivity .... {
or:
public class MainFragmentDemoActivity extends ActionBarActivity .... {
Open for correction, as always!
Regards,
Edward Quixote.
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");
}
}
}