I have 2 classes in Java and they are 2 different activities that I'd like to switch with a button click.
The problem is that when I do click the button the app crashes.
my MainActivity extends Activity and my SecondActivity extends Activity AND implements SensorEventListener. So I think this is the problem. My MainActivity CANNOT implement SensorEventListener because I am using an external sensor.
This is my MainActivity
public class MainActivity extends Activity {
//My Code goes here.
//This it the function that gets called from XML's onClick feature when I click my Button
public void gotoPathFinder(View v) {
Intent intent = new Intent(this, pathfinderActivity.class);
startActivity(intent);
}
}
This is my SecondActivity
package ca.concordia.sensortag.minimal;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class pathfinderActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mStepCounterSensor;
private Sensor mStepDetectorSensor;
private TextView textView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
mSensorManager = (SensorManager) getSystemService(this.SENSOR_SERVICE);
mStepCounterSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
mStepDetectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
}
#Override
public void onSensorChanged(SensorEvent event) {
// Sensor sensor = event.sensor;
// float[] values = event.values;
// int value = -1;
//
// if (values.length > 0) {
// value = (int) values[0];
// }
//
// if (sensor.getType() == Sensor.TYPE_STEP_COUNTER) {
// textView.setText("Step Counter Detected : " + value);
// } else if (sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
// textView.setText("Step Detector Detected : " + value);
// }
}
#Override
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mStepCounterSensor,SensorManager.SENSOR_DELAY_FASTEST);
mSensorManager.registerListener(this, mStepDetectorSensor,SensorManager.SENSOR_DELAY_FASTEST);
}
#Override
protected void onStop() {
super.onStop();
mSensorManager.unregisterListener(this, mStepCounterSensor);
mSensorManager.unregisterListener(this, mStepDetectorSensor);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
So I think the app crashes because I'm trying to switch to an activity that implements sensoreventlistener from an activity that doesn't? How can I fix this issue?
LogCat
11-27 20:00:07.312: W/dalvikvm(31178): threadid=1: thread exiting with uncaught exception (group=0x41604ba8)
11-27 20:00:07.312: E/AndroidRuntime(31178): FATAL EXCEPTION: main
11-27 20:00:07.312: E/AndroidRuntime(31178): Process: ca.concordia.sensortag.minimal, PID: 31178
11-27 20:00:07.312: E/AndroidRuntime(31178): java.lang.IllegalStateException: Could not find a method gotoPathFinder(View) in the activity class ca.concordia.sensortag.minimal.pathfinderActivity for onClick handler on view class android.widget.ImageView with id 'pf_button'
11-27 20:00:07.312: E/AndroidRuntime(31178): at android.view.View$1.onClick(View.java:3810)
11-27 20:00:07.312: E/AndroidRuntime(31178): at android.view.View.performClick(View.java:4438)
11-27 20:00:07.312: E/AndroidRuntime(31178): at android.view.View$PerformClick.run(View.java:18422)
11-27 20:00:07.312: E/AndroidRuntime(31178): at android.os.Handler.handleCallback(Handler.java:733)
11-27 20:00:07.312: E/AndroidRuntime(31178): at android.os.Handler.dispatchMessage(Handler.java:95)
11-27 20:00:07.312: E/AndroidRuntime(31178): at android.os.Looper.loop(Looper.java:136)
11-27 20:00:07.312: E/AndroidRuntime(31178): at android.app.ActivityThread.main(ActivityThread.java:5017)
11-27 20:00:07.312: E/AndroidRuntime(31178): at java.lang.reflect.Method.invokeNative(Native Method)
11-27 20:00:07.312: E/AndroidRuntime(31178): at java.lang.reflect.Method.invoke(Method.java:515)
11-27 20:00:07.312: E/AndroidRuntime(31178): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
11-27 20:00:07.312: E/AndroidRuntime(31178): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
11-27 20:00:07.312: E/AndroidRuntime(31178): at dalvik.system.NativeStart.main(Native Method)
11-27 20:00:07.312: E/AndroidRuntime(31178): Caused by: java.lang.NoSuchMethodException: gotoPathFinder [class android.view.View]
11-27 20:00:07.312: E/AndroidRuntime(31178): at java.lang.Class.getConstructorOrMethod(Class.java:472)
11-27 20:00:07.312: E/AndroidRuntime(31178): at java.lang.Class.getMethod(Class.java:857)
11-27 20:00:07.312: E/AndroidRuntime(31178): at android.view.View$1.onClick(View.java:3803)
11-27 20:00:07.312: E/AndroidRuntime(31178): ... 11 more
NOTE: When I click the button it brings me to the SAME activity... and then i click the button again THEN i get an error
MainActivity's XML
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/bg"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="ca.concordia.sensortag.minimal.MainActivity$PlaceholderFragment" >
<ImageView
android:id="#+id/compass"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/compass" />
<ImageView
android:id="#+id/pointer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="#drawable/pointer" />
<TextView
android:id="#+id/degree"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/imageView1"
android:layout_centerHorizontal="true"
android:text="TextView" />
<ImageView
android:id="#+id/pf_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/compass"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp"
android:src="#drawable/pf_button"
android:onClick="gotoPathFinder" />
</RelativeLayout>
you dont have the method gotoPathFinder in your pathfinderActivity class, am I right that you have also a view with an onclick event in this class too that calls this method?
you do this in your second class:
setContentView(R.layout.activity_main);
so your second class has same layout like your first class. first time you click the button the acticity changes but layout stays the same then when you click it again there is no method in the current class that the botton onclick can run and switch to the other class
so if you have 2 separate layouts you want to use then switch the lone above with
setContentView(R.layout.other_acticity);
and if its intended then add method with same name to second class
This is your error:
Could not find a method gotoPathFinder(View)
android.widget.ImageView with id 'pf_button'
In your XML, find the ImageView with the id "pf_button".
For that ImageView, get rid of whatever android:onClick is already there, and change it to this:
android:onClick="gotoSecond"
You just had the wrong method name in the XML file...your app was looking for that name, but couldn't find it!
Let me know if that works. It should.
Related
Note: I'm using the YouTube Android Player API
Expected behavior:
The activity remains in portrait mode when the video is not fullscreen (Enforced by AndroidManifest ok).
The activity is set to landscape orientation when the video enters fullscreen mode (ok).
The activity returns to portrait orientation when the user exits fullscreen mode (ExceptionInInitializerError occurs here).
See the problem in action here
YouTubeFailureRecoveryActivity.java (This is included in the library under sample/src/com/examples/youtubeapidemo)
Main Activity
package test.testapp;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
public class MainActivity extends YouTubeFailureRecoveryActivity implements YouTubePlayer.OnFullscreenListener {
static final String API_KEY = "PLACE YOUTUBE DATA API KEY HERE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
youTubeView.initialize(API_KEY, this);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
youTubePlayer.setOnFullscreenListener(this);
youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI);
if(!wasRestored){
youTubePlayer.cueVideo("wKJ9KzGQq0w");
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView) findViewById(R.id.youtube_view);
}
#Override
public void onFullscreen(boolean isFullscreen) {
if(isFullscreen){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}else if(!isFullscreen){
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="test.testapp.MainActivity">
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</com.google.android.youtube.player.YouTubePlayerView>
</LinearLayout>
Stack trace
06-10 09:47:09.205 2646-2646/test.testapp E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.ExceptionInInitializerError
at android.support.v7.widget.RecyclerView.onSaveInstanceState(SourceFile:201)
at android.view.View.dispatchSaveInstanceState(View.java:11839)
at android.view.ViewGroup.dispatchFreezeSelfOnly(ViewGroup.java:2576)
at android.support.v7.widget.RecyclerView.dispatchSaveInstanceState(SourceFile:220)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.View.saveHierarchyState(View.java:11822)
at com.android.internal.policy.impl.PhoneWindow.saveHierarchyState(PhoneWindow.java:1566)
at android.app.Activity.onSaveInstanceState(Activity.java:1188)
at com.google.android.youtube.player.YouTubeBaseActivity.onSaveInstanceState(Unknown Source)
at android.app.Activity.performSaveInstanceState(Activity.java:1137)
at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1215)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3486)
at android.app.ActivityThread.access$700(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1201)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoClassDefFoundError: rt
at rs.<clinit>(SourceFile:17)
at android.support.v7.widget.RecyclerView.onSaveInstanceState(SourceFile:201)
at android.view.View.dispatchSaveInstanceState(View.java:11839)
at android.view.ViewGroup.dispatchFreezeSelfOnly(ViewGroup.java:2576)
at android.support.v7.widget.RecyclerView.dispatchSaveInstanceState(SourceFile:220)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.ViewGroup.dispatchSaveInstanceState(ViewGroup.java:2562)
at android.view.View.saveHierarchyState(View.java:11822)
at com.android.internal.policy.impl.PhoneWindow.saveHierarchyState(PhoneWindow.java:1566)
at android.app.Activity.onSaveInstanceState(Activity.java:1188)
at com.google.android.youtube.player.YouTubeBaseActivity.onSaveInstanceState(Unknown Source)
at android.app.Activity.performSaveInstanceState(Activity.java:1137)
at android.app.Instrumentation.callActivityOnSaveInstanceState(Instrumentation.java:1215)
at android.app.ActivityThread.handleRelaunchActivity(ActivityThread.java:3486)
at android.app.ActivityThread.access$700(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1201)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Looks like the application is crashing when restarting because of a configuration change
https://developer.android.com/guide/topics/resources/runtime-changes.html
You can disable the automatic activity recreation for orientation changes, and handle it yourself.
To do that, add
android:configChanges="orientation|screenLayout|screenSize"
With orientation alone it probably works, but the other ones I think were triggered also on some devices.
You can then override onConfigurationChanged() to do stuff on an orientation change if you need it, like showing / hiding views, etc.. as Android will not recreate your layouts automatically (that's what it does when restarts the activity on an orientation change)
So you can do:
#Override
public void onConfigurationChanged(final Configuration newConfiguration) {
Log.wtf(
"Orientation",
newConfiguration.orientation == Configuration.ORIENTATION_PORTRAIT
? "portrait"
: "landscape"
);
}
How can I start activity in adapter? I use this method in my adapter:
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
context.startActivity(new Intent(context,asabani_cat.class));
}
});
But this worked just for fragment of my app, when I called this code in Activity App suddenly crashed!
Another question that I have, is it the good way to start activity in adapter?
my logcat:
11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: FATAL EXCEPTION: main 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: java.lang.NullPointerException 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at com.katibehpayam.mahdi.katibehpayam.adapter_common$7.onClick(adapter_common.java:266) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.view.View.performClick(View.java:4377) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.view.View$PerformClick.run(View.java:18044) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.os.Handler.handleCallback(Handler.java:725) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:92) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.os.Looper.loop(Looper.java:137) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5306) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at java.lang.reflect.Method.invokeNative(Native Method) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:511) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869) 11-27 21:25:25.086 22237-22237/com.katibehpayam.mahdi.katibehpayam E/AndroidRuntime: at dalvik.system.NativeStart.main(Native Method)
You could try:
post.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.getContext().startActivity(new Intent(v.getContext(),asabani_cat.class));
}
});
You should post the error from the Logcat so we can help you further. However from what you've shown I can find nothing inherently wrong with your code. Make sure your context is set correctly. Furthermore if you are already in an Activity you do not need to say
context.startActivity(new Intent(context,asabani_cat.class));
you can simply say
startActivity(new Intent(this, asabani_cat.class));
If you are not in an Activity then you need to pass the context like so
MyAdapter myAdapter = new MyAdapter(this);
Then inside your adapter set your context like this:
MyAdapter(Context context) {
this.context = context;
}
EDIT
Your logcat shows a null pointer exception is the cause of your crash. Can you please post the code from adapter_common.java at line 266? Thanks
In kotlin, on your view:
class YourClass: ArrayAdapter<Feature>(), View.OnClickListener{
override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
var yourView = inflater.inflate(mResource, parent, false)
yourView .setOnClickListener(){
onClick(convertView)
}
}
override fun onClick(v: View?) {
val intent = Intent(mContext, SeckondActivity::class.java)
mContext.startActivity(intent)
}
}
I have this code in my MainActivity class:
public class MainActivity extends ActionBarActivity {
Button mButton;
EditText mEdit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button)findViewById(R.id.btnAsk);
mEdit = (EditText)findViewById(R.id.txtQuestion);
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Toast.makeText(getApplicationContext(),
mEdit.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Everything was just fine, but after adding setOnClickListener() to mButton it started crashing at the very beginning.
Here is the error log:
04-26 14:12:26.255: E/AndroidRuntime(1447): FATAL EXCEPTION: main
04-26 14:12:26.255: E/AndroidRuntime(1447): Process: com.gelasoft.answeringball, PID: 1447
04-26 14:12:26.255: E/AndroidRuntime(1447): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.gelasoft.answeringball/com.gelasoft.answeringball.MainActivity}: java.lang.NullPointerException
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.os.Handler.dispatchMessage(Handler.java:102)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.os.Looper.loop(Looper.java:136)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-26 14:12:26.255: E/AndroidRuntime(1447): at java.lang.reflect.Method.invokeNative(Native Method)
04-26 14:12:26.255: E/AndroidRuntime(1447): at java.lang.reflect.Method.invoke(Method.java:515)
04-26 14:12:26.255: E/AndroidRuntime(1447): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-26 14:12:26.255: E/AndroidRuntime(1447): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-26 14:12:26.255: E/AndroidRuntime(1447): at dalvik.system.NativeStart.main(Native Method)
04-26 14:12:26.255: E/AndroidRuntime(1447): Caused by: java.lang.NullPointerException
04-26 14:12:26.255: E/AndroidRuntime(1447): at com.gelasoft.answeringball.MainActivity.onCreate(MainActivity.java:30)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.Activity.performCreate(Activity.java:5231)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-26 14:12:26.255: E/AndroidRuntime(1447): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-26 14:12:26.255: E/AndroidRuntime(1447): ... 11 more
What am I missing here? I know that it is something really small, but I can't spot it right now.
P.S Here is my fragment xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.xx.ss.MainActivity$PlaceholderFragment" >
<ImageView
android:id="#+id/sphereIcon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:contentDescription="#string/magicBallDescr"
android:src="#drawable/ic_launcher" />
<LinearLayout
android:id="#+id/table"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/sphereIcon"
android:orientation="vertical" >
<TextView
android:id="#+id/txtAnswer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<EditText
android:id="#+id/txtQuestion"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="#string/textHint"
android:inputType="textMultiLine"
android:lines="8"
/>
<Button
android:id="#+id/btnAsk"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/btnAskQ"
android:paddingEnd="#dimen/activity_vertical_margin"
/>
</LinearLayout>
</RelativeLayout>
Replace
mButton = (Button)findViewById(R.id.btnAsk);
with
mButton = (Button)rootView.findViewById(R.id.btnAsk); // this will go in Fragment onCreateView
And move setOnClicklistener code as well to onCreateView.
Hope it helps.
Move this code :
mButton.setOnClickListener(
new View.OnClickListener()
{
public void onClick(View view)
{
Toast.makeText(getApplicationContext(),
mEdit.getText().toString(), Toast.LENGTH_SHORT).show();
}
});
into your fragment's onCreateView() method. It should work then.
MainActivity.java
package com.example.myfirstapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.EditText;
import android.content.Intent;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
DisplayMessageActivity.java
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message,
container, false);
return rootView;
}
}
}
Error Log
04-10 01:37:00.460: W/dalvikvm(1650): threadid=1: thread exiting with uncaught exception (group=0xb3aaeba8)
04-10 01:37:00.520: E/AndroidRuntime(1650): FATAL EXCEPTION: main
04-10 01:37:00.520: E/AndroidRuntime(1650): Process: com.example.myfirstapp, PID: 1650
04-10 01:37:00.520: E/AndroidRuntime(1650): java.lang.IllegalStateException: Could not find a method sendMessage(View) in the activity class com.example.myfirstapp.MainActivity for onClick handler on view class android.widget.Button
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.view.View$1.onClick(View.java:3810)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.view.View.performClick(View.java:4438)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.view.View$PerformClick.run(View.java:18422)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.os.Handler.handleCallback(Handler.java:733)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.os.Handler.dispatchMessage(Handler.java:95)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.os.Looper.loop(Looper.java:136)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-10 01:37:00.520: E/AndroidRuntime(1650): at java.lang.reflect.Method.invokeNative(Native Method)
04-10 01:37:00.520: E/AndroidRuntime(1650): at java.lang.reflect.Method.invoke(Method.java:515)
04-10 01:37:00.520: E/AndroidRuntime(1650): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-10 01:37:00.520: E/AndroidRuntime(1650): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-10 01:37:00.520: E/AndroidRuntime(1650): at dalvik.system.NativeStart.main(Native Method)
04-10 01:37:00.520: E/AndroidRuntime(1650): Caused by: java.lang.NoSuchMethodException: sendMessage [class android.view.View]
04-10 01:37:00.520: E/AndroidRuntime(1650): at java.lang.Class.getConstructorOrMethod(Class.java:472)
04-10 01:37:00.520: E/AndroidRuntime(1650): at java.lang.Class.getMethod(Class.java:857)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.view.View$1.onClick(View.java:3803)
04-10 01:37:00.520: E/AndroidRuntime(1650): ... 11 more
04-10 01:37:04.820: I/Process(1650): Sending signal. PID: 1650 SIG: 9
I've tried to look at other questions answered similar to mine, but I can't find an answer that seems to help my situation. Can anyone help?
I was struggling with a similar error following the android tutorial
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myfirstapp, PID: 18300
java.lang.IllegalStateException: Could not find method sendMessage (MainActivity)(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5197)
at android.view.View$PerformClick.run(View.java:20909)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5944)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
but in my case the WYSIWYG editor (IntelliJ w/Android Studio plugin) ended up populating the onClick property in activity_main.xml with some extra junk about MainActivity:
android:onClick="sendMessage (MainActivity)"
So I deleted " (MainActivity)" and it stopped crashing. I see this is different from your problem as your xml file already seems correct with android:onClick="sendMessage". But wanted to add it here for any others struggling with what I saw. This was the closest post to the issue I was seeing. I'm just getting started and this was killing me, so hope it helps someone else.
The problem is the onClick property in one of your Button tags:
android:onClick="sendMessage" />
Just make sure you have a method sendMessage(View) in your Activity.
It is because you need to implement implements android.view.View.OnClickListener in your class, therefore add the correct imports i.e. import android.view.View.
I am new to Android. I am trying to build this tiny app however every time I add the code in bold:
d = (Button) findViewById (R.id.tvDis);
the app crashes and if I remove this line, everything works fine. I am runing this on android 2.2 api 8 version and nexus s emulator.
package com.maximusstudios.numtowords;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
/**Called when the activity is first created.*/
int counter;
Button add, sub;
TextView d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById (R.id.bAdd);
**d = (Button) findViewById (R.id.tvDis);**
sub = (Button) findViewById(R.id.bSub);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter--;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
XML CODE:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Your Total is 0"
android:textSize="20dp"
android:layout_gravity="center"
android:gravity="center"
android:id="#+id/tvDis"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one"
android:layout_gravity="center"
android:textSize="20dp"
android:id="#+id/bAdd"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add one"
android:layout_gravity="center"
android:textSize="20dp"
android:id="#+id/bSub"
/>
</LinearLayout>
Error list:
02-10 18:00:21.452: D/AndroidRuntime(910): Shutting down VM
02-10 18:00:21.452: W/dalvikvm(910): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
02-10 18:00:21.472: E/AndroidRuntime(910): FATAL EXCEPTION: main
02-10 18:00:21.472: E/AndroidRuntime(910): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.maximusstudios.numtowords/com.maximusstudios.numtowords.MainActivity}: java.lang.ClassCastException: android.widget.TextView
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.os.Handler.dispatchMessage(Handler.java:99)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.os.Looper.loop(Looper.java:123)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.main(ActivityThread.java:4627)
02-10 18:00:21.472: E/AndroidRuntime(910): at java.lang.reflect.Method.invokeNative(Native Method)
02-10 18:00:21.472: E/AndroidRuntime(910): at java.lang.reflect.Method.invoke(Method.java:521)
02-10 18:00:21.472: E/AndroidRuntime(910): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
02-10 18:00:21.472: E/AndroidRuntime(910): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
02-10 18:00:21.472: E/AndroidRuntime(910): at dalvik.system.NativeStart.main(Native Method)
02-10 18:00:21.472: E/AndroidRuntime(910): Caused by: java.lang.ClassCastException: android.widget.TextView
02-10 18:00:21.472: E/AndroidRuntime(910): at com.maximusstudios.numtowords.MainActivity.onCreate(MainActivity.java:23)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-10 18:00:21.472: E/AndroidRuntime(910): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
02-10 18:00:21.472: E/AndroidRuntime(910): ... 11 more
Change to
d = (TextView) findViewById (R.id.tvDis);
Your casting was wrong. With your code, when you do (Button), you are trying to cast the TextView that is returned by findViewById() into a Button, which doesn't work due to them being incompatible types.
You define d as a TextView and try to cast it to a Button
Should be
d = (TextView) findViewById (R.id.tvDis);
The error you're getting is a ClassCastException