Android My First App Tutorial android:onClick issues - java

I am currently trying to get the basic My First App tutorial of Android (created by google) to work, but I'm having some issues. Currently how the app is made no errors show up in Eclipse, but when I run the app and click the Send button, the app crashes displaying Unfortunately, My First App has stopped.
Looking in the Log cat for the error it states that
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.
sendMessage does exist in the MainActivity class, but it is a nested class inside a function PlaceholderFragment. Originally I thought that this was an indexing error so I tried calling sendMessage like a nested class android:onClick="PlaceholderFragment.sendMessage" with no success. I have included the fragment_main and MainActivity class as well as my full logcat error. Thanks for any help.
MainActivity:
package com.example.myfirstapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
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;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(getActivity(), DisplayMessageActivity.class);
EditText editText = (EditText)getActivity(). findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
}
Fragment Main:
<?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>
LogCat:
04-25 12:04:07.220: D/(1274): HostConnection::get() New Host Connection established 0xb8e4f238, tid 1274
04-25 12:04:07.330: W/EGL_emulation(1274): eglSurfaceAttrib not implemented
04-25 12:04:07.340: D/OpenGLRenderer(1274): Enabling debug mode 0
04-25 12:04:10.620: D/AndroidRuntime(1274): Shutting down VM
04-25 12:04:10.620: W/dalvikvm(1274): threadid=1: thread exiting with uncaught exception (group=0xb2a6bba8)
04-25 12:04:10.750: E/AndroidRuntime(1274): FATAL EXCEPTION: main
04-25 12:04:10.750: E/AndroidRuntime(1274): Process: com.example.myfirstapp, PID: 1274
04-25 12:04:10.750: E/AndroidRuntime(1274): 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-25 12:04:10.750: E/AndroidRuntime(1274): at android.view.View$1.onClick(View.java:3810)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.view.View.performClick(View.java:4438)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.view.View$PerformClick.run(View.java:18422)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.os.Handler.handleCallback(Handler.java:733)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.os.Handler.dispatchMessage(Handler.java:95)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.os.Looper.loop(Looper.java:136)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-25 12:04:10.750: E/AndroidRuntime(1274): at java.lang.reflect.Method.invokeNative(Native Method)
04-25 12:04:10.750: E/AndroidRuntime(1274): at java.lang.reflect.Method.invoke(Method.java:515)
04-25 12:04:10.750: E/AndroidRuntime(1274): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-25 12:04:10.750: E/AndroidRuntime(1274): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-25 12:04:10.750: E/AndroidRuntime(1274): at dalvik.system.NativeStart.main(Native Method)
04-25 12:04:10.750: E/AndroidRuntime(1274): Caused by: java.lang.NoSuchMethodException: sendMessage [class android.view.View]
04-25 12:04:10.750: E/AndroidRuntime(1274): at java.lang.Class.getConstructorOrMethod(Class.java:472)
04-25 12:04:10.750: E/AndroidRuntime(1274): at java.lang.Class.getMethod(Class.java:857)
04-25 12:04:10.750: E/AndroidRuntime(1274): at android.view.View$1.onClick(View.java:3803)
04-25 12:04:10.750: E/AndroidRuntime(1274): ... 11 more
04-25 12:04:12.720: I/Process(1274): Sending signal. PID: 1274 SIG: 9

It looks like your problem is that the sendMessage function should be included in your MainActivity instead of nested in your fragment.
The debug line:
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
shows that the application is looking in your MainActivity class for this method.

place sendMessage(View view) method inside MainActivity class instead of PlaceholderFragment class

Handling clicklistener from xml is not always a good idea. Set a clicklistener in the fragment for the button and call sendMessage method from onClick method of clicklistener.
First set a ID for your button (Example : sendButton).
Then,
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);
Button b = (Button) rootView.findViewByID(R.id.sendButton);
//Here set the clickListener and call sendMessage method
return rootView;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(getActivity(), DisplayMessageActivity.class);
EditText editText = (EditText)getActivity(). findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
Or implement View.OnClickListener in the fragment then have a case statement like:
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.sendButton:
sendMessage();
break;
default:
Log.i(TAG, "Unknown: " + view.getId());
break;
}
}

Do it programmatically:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button b = (Button) rootView.findViewById(R.id.my_button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// handle click here
}
});
return rootView;
}
and insert this into Button section in your main activity layout:
android:id="#+id/my_button"

android:onClick="sendMessage"
button onClick attribute search the corresponding method in the Activity. but you define that method in the Fragment that's why you get the exception
method could not find exception.
Android Recommended way to do handle the onClick for button inside the fragment is
First Assign id to Button
<?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:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
/>
</LinearLayout>
your Fragment then register the button with onClick listener
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment implements OnItemClickListener{
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
Button b = (Button) rootView.findViewById(R.id.button1);
b.setOnClickListener(this);
return rootView;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(getActivity(), DisplayMessageActivity.class);
EditText editText = (EditText)getActivity(). findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
public void onClick(View view)
{
sendMessage(view);
}
}

Related

MediaPlayer onClick crashes when start() is called

I have an app that simply displays 1 picture, implemented through Picasso. The onClick works fine if I replace the contents with a simple toast, so it must be the MediaPlayer calls. I don't know why it keeps crashing though.
package com.example.andrew.crossfade;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import com.squareup.picasso.Picasso;
public class MainActivity extends ActionBarActivity{
MediaPlayer mp;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
ImageView imageView = (ImageView) findViewById(R.id.imageView);
imageView.setClickable(true);
Picasso.with(this)
.load("http://i.imgur.com/vpeH7S2.jpg")
.into(imageView);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mp = MediaPlayer.create(MainActivity.this, R.raw.later);
mp.start();
}
});
}
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;
}
}
}
The XML:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:id="#+id/container"
android:layout_width="match_parent" android:layout_height="match_parent"
tools:context=".MainActivity" tools:ignore="MergeRootFrame" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imageView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
/>
And finally, the log cat:
10-29 12:12:07.343 18409-18409/com.example.andrew.crossfade W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x41f38da0)
10-29 12:12:07.343 18409-18409/com.example.andrew.crossfade E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.andrew.crossfade, PID: 18409
java.lang.NullPointerException
at com.example.andrew.crossfade.MainActivity$1.onClick(MainActivity.java:47)
at android.view.View.performClick(View.java:4633)
at android.view.View$PerformClick.run(View.java:19330)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:157)
at android.app.ActivityThread.main(ActivityThread.java:5356)
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:1265)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
at dalvik.system.NativeStart.main(Native Method)
something is null in your code
java.lang.NullPointerException
call mp.prepare() before start
and make sure R.raw.later is playable audio for media player

fragments in viewpager, no view found error

I have an activity holding a fragment, in this fragment there is a button , when it is clicked, a dialog is popped out.
In this dialog, there is a Viewpager, which holds some fragments to display.
Here are the code and the error, please spare your valuable time to show me where I am wrong. I much appreciate your help.
MainActivity.class
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fm.beginTransaction();
MyFragment fragment = new MyFragment();
fragmentTransaction.add(R.id.container, fragment);
fragmentTransaction.commit();
}
}
MyFragment.class
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_sandbox, container, false);
Button button = (Button) v.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
PagerDialog dialog = new PagerDialog(getActivity(),
getChildFragmentManager());
dialog.show();
}
});
return v;
}
}
PagerDialog.class
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
public class PagerDialog extends Dialog {
ViewPager mViewPager;
FragmentStatePagerAdapter mAdapter;
FragmentManager mFragmentManager;
public PagerDialog(Context context, FragmentManager fm) {
super(context);
mFragmentManager = fm;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
mViewPager = (ViewPager) findViewById(R.id.pager);
mAdapter = new MyAdapter(mFragmentManager);
mViewPager.setAdapter(mAdapter);
}
private class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return new DummyFragment();
}
#Override
public int getCount() {
return 2;
}
}
private class DummyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_dummy_layout,
container, false);
return v;
}
}
}
Here is the dialog.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
Here is the error
03-06 19:43:38.487: E/AndroidRuntime(1167): FATAL EXCEPTION: main
03-06 19:43:38.487: E/AndroidRuntime(1167): Process: com.me.sandbox, PID: 1167
03-06 19:43:38.487: E/AndroidRuntime(1167): java.lang.IllegalArgumentException: No view found for id 0x7f05003d (com.mochimira.sandbox:id/pager) for fragment DummyFragment{b2d9f8c8 #0 id=0x7f05003d}
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:939)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:739)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1489)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.app.FragmentManagerImpl.executePendingTransactions(FragmentManager.java:486)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.app.FragmentStatePagerAdapter.finishUpdate(FragmentStatePagerAdapter.java:163)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.view.ViewPager.populate(ViewPager.java:1073)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.view.ViewPager.populate(ViewPager.java:919)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1441)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.View.measure(View.java:16497)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.View.measure(View.java:16497)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.View.measure(View.java:16497)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.View.measure(View.java:16497)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1404)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.LinearLayout.measureVertical(LinearLayout.java:695)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.View.measure(View.java:16497)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5125)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
03-06 19:43:38.487: E/AndroidRuntime(1167): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2291)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.View.measure(View.java:16497)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:1916)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1113)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1295)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.Choreographer.doCallbacks(Choreographer.java:574)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.Choreographer.doFrame(Choreographer.java:544)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.os.Handler.handleCallback(Handler.java:733)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.os.Handler.dispatchMessage(Handler.java:95)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.os.Looper.loop(Looper.java:136)
03-06 19:43:38.487: E/AndroidRuntime(1167): at android.app.ActivityThread.main(ActivityThread.java:5017)
03-06 19:43:38.487: E/AndroidRuntime(1167): at java.lang.reflect.Method.invokeNative(Native Method)
03-06 19:43:38.487: E/AndroidRuntime(1167): at java.lang.reflect.Method.invoke(Method.java:515)
03-06 19:43:38.487: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
03-06 19:43:38.487: E/AndroidRuntime(1167): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
03-06 19:43:38.487: E/AndroidRuntime(1167): at dalvik.system.NativeStart.main(Native Method
I have found a solution to the problem and have modified your classes so that this error no longer occurs.
The only major difference was that you should use a DialogFragment instead of a Dialog, that way you have access to call getChildFragmentManager() and receive the correct FragmentManager from the DialogFragment.
Even though you were using getChildFragmentManager() before, it was coming from MyFragment and the PagerDialog class was not a child fragment in MyFragment.
I have tested the code below, and it should be working fine now.
MyFragment
public class MyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_sandbox, container, false);
Button button = (Button) v.findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
DialogFragment newFragment = PagerDialog.newInstance();
newFragment.show(getChildFragmentManager(), "dialog");
}
});
return v;
}
}
PagerDialog
public class PagerDialog extends DialogFragment {
public static PagerDialog newInstance() {
return new PagerDialog();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.dialog_fragment, container, false);
ViewPager mViewPager = (ViewPager) v.findViewById(R.id.view_pager);
/* Use childFragmentManager here provided from the PagerDialog */
MyAdapter mAdapter = new MyAdapter(getChildFragmentManager());
mViewPager.setAdapter(mAdapter);
return v;
}
private class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return new DummyFragment();
}
#Override
public int getCount() {
return 2;
}
}
}
DummyFragment
public class DummyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_dummy_layout, container, false);
return v;
}
}
fragment_sandbox.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Test Fragment Dialog Pager"
android:textSize="24sp"
android:padding="20dp" />
</LinearLayout>
dialog_fragment.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment Dialog Title Text "
android:padding="10dp"
android:textColor="#333"
android:textSize="24sp"/>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="200dp"/>
</LinearLayout>
fragment_dummy_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment Dummy Text"
android:textSize="24sp"
android:textColor="#ff0000"/>
</LinearLayout>
I found in Google a blog post, it says that viewpager doesn't work on Dialog.
It also says we should use DialogFragment instead.
Here is the link to that blog: http://www.intellicode.in/viewpager-inside-dialog/
getChildFragmentManager() is available since API 17 while you're using the v4 support library. Try using the support fragment manager instead:
PagerDialog dialog = new PagerDialog(getActivity(),
getActivity().getSupportFragmentManager());
The Dialog class is the base class for dialogs, but you should avoid instantiating Dialog directly. Instead, use one of the following subclasses:
AlertDialogA dialog that can show a title, up to three buttons, a list of selectable items, or a custom layout. And also DatePickerDialog or TimePickerDialog.
These classes define the style and structure for your dialog, but you should use a DialogFragment as a container for your dialog. The DialogFragment class provides all the controls you need to create your dialog and manage its appearance, instead of calling methods on the Dialog object.
For more detail please go through Dialog Design
The error sounds like it's looking for the id pager in the xml file for DummyFragment (fragment_dummy_layout.xml). I wonder if this is due to calling View v = inflater.inflate(R.layout.fragment_dummy_layout, container, false); in the same file as setContentView(R.layout.dialog);. Have you tried separating DummyFragment into it's own file?
You could also try
View v = getActivity().getLayoutInflater().inflate(R.layout.fragment_dummy_layout,
container, false);
Try using DialogFragment and pass getChildFragmentManager() to your FragmentPagerAdapter's constructor.
DialogFragment:
public static class MyDialogFragment extends DialogFragment {
private ViewPager viewPager;
MySectionPagerAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.m_layout, container);
viewPager = (ViewPager) view.findViewById(R.id.viewpager);
mAdapter = new MySectionPagerAdapter(getChildFragmentManager());
viewPager.setAdapter(mAdapter);
return view;
}
}
so far, we can't figure out why there is an error, but I have a way to work around this, using this tip:
Tip: If you want a custom dialog, you can instead display an Activity as a dialog instead of using the Dialog APIs. Simply create an activity and set its theme to Theme.Holo.Dialog in the manifest element:
<activity android:theme="#android:style/Theme.Holo.Dialog"
Based on this tip, I don't make PagerDialog extend Dialog but from Fragment. And then put this Fragment inside an Activity , set the theme of this activity as above in AndroidManifest.xml.
The updated code for the PagerDialog is as followed.
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class PagerDialog extends Fragment {
ViewPager mViewPager;
FragmentStatePagerAdapter mAdapter;
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.id.dialog, container, false);
mViewPager = (ViewPager) v.findViewById(R.id.pager);
mAdapter = new MyAdapter(getFragmentManager());
mViewPager.setAdapter(mAdapter);
return v;
}
private class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
return new DummyFragment();
}
#Override
public int getCount() {
return 2;
}
}
private class DummyFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_dummy_layout,
container, false);
return v;
}
}
}
If you have any better solutions or you can find out why the original code in my question does not work, please teach me. I am a newbie in Android programing and I am happy to learn from you all.
Cheers.
I think you used
Dialog dialog = new Dialog(context);
Instends this.
1st Step: Used DialogFragment
public class MyCustomDialog extends DialogFragment {
Button mButton;
EditText mEditText;
List<MasterPageModel> listdata;
int position;
ViewPager viewpager;
public MyCustomDialog(List<MasterPageModel> listdata, int position) {
this.listdata = listdata;
this.position = position;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View dialog = inflater.inflate(R.layout.dailoglayout, container);
final Dialog dailog = getDialog();
dailog.getWindow().setLayout(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
dailog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
dailog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
ImageView closebtn = (ImageView) dialog.findViewById(R.id.closeimgeview);
closebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dailog.dismiss();
}
});
viewpager = (ViewPager) dialog.findViewById(R.id.dailog_viewpager);
**viewpager.setAdapter(new PagerAdapter(getChildFragmentManager(), listdata));** //This Line is Very important
viewpager.setCurrentItem(position);
return dialog;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen); //For Full Screen of DailogBox
}
}
2nd Step :set The FragmentViewPager
public class PagerAdapter extends FragmentPagerAdapter {
private final List<MasterPageModel> pages;
public PagerAdapter(FragmentManager fm, List<MasterPageModel> pages) {
super(fm);
this.pages = pages;
}
#Override
public Fragment getItem(int position) {
return new ViewPagerFragment(pages.get(position));
}
#Override
public int getCount() {
return pages.size();
}
}
3rd Step : Fragment View For ViewPager:
public class ViewPagerFragment extends Fragment {
MasterPageModel masteDetailModel;
public ViewPagerFragment(MasterPageModel questionItem) {
this.masteDetailModel = questionItem;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.pagerlayout, container, false);
ImageView image = (ImageView) v.findViewById(R.id.pager_imageview);
Log.i("Image", "=>" + masteDetailModel.imagelarge);
Picasso.with(getActivity()).load(masteDetailModel.imagethumb).error(R.drawable.img).into(image);
return v;
}
4th How to Use this dialogfragment:
MyCustomDialog fragment1 = new MyCustomDialog(listdata, position);
EditionDetailActivity act = (EditionDetailActivity) context;
FragmentManager fm = act.getSupportFragmentManager();
fragment1.show(fm, "");

Could not find a method sendMessage(View) in the activity class

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 have just written my first android app, and after 3 hours it still doesn't work

I have just started writing my first piece of code in an android app, however when I run it with the following section uncommented it crashes (anything else I tell you would be a useless guess):
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
With the following error log:
04-07 17:45:30.897: E/AndroidRuntime(15210): FATAL EXCEPTION: main
04-07 17:45:30.897: E/AndroidRuntime(15210): Process: com.ollieapps.helloworld, PID: 15210
04-07 17:45:30.897: E/AndroidRuntime(15210): java.lang.IllegalStateException: Could not execute method of the activity
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$1.onClick(View.java:3823)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View.performClick(View.java:4438)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$PerformClick.run(View.java:18422)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Handler.handleCallback(Handler.java:733)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Handler.dispatchMessage(Handler.java:95)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.os.Looper.loop(Looper.java:136)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-07 17:45:30.897: E/AndroidRuntime(15210): at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.reflect.InvocationTargetException
04-07 17:45:30.897: E/AndroidRuntime(15210): at java.lang.reflect.Method.invoke(Native Method)
04-07 17:45:30.897: E/AndroidRuntime(15210): at android.view.View$1.onClick(View.java:3818)
04-07 17:45:30.897: E/AndroidRuntime(15210): ... 9 more
04-07 17:45:30.897: E/AndroidRuntime(15210): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'boolean android.widget.CheckBox.isChecked()' on a null object reference
04-07 17:45:30.897: E/AndroidRuntime(15210): at com.ollieapps.helloworld.MainActivity.onButton1Click(MainActivity.java:59)
04-07 17:45:30.897: E/AndroidRuntime(15210): ... 11 more
I'm sorry if I have included to much or too little, this is my first question, also I have already searched for 3 hours.
Full Code:
package com.ollieapps.helloworld;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
TextView textView; CheckBox pepBox, cheeseBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pepBox = (CheckBox) findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
textView = (TextView) findViewById(R.id.textView1);
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);
}
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
/**
* 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;
}
}
}
xml:
fragment:
<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.ollieapps.helloworld.MainActivity$PlaceholderFragment" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:orientation="vertical" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Pepperoni" />
<CheckBox
android:id="#+id/checkBox2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ExtraCheese" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="onButton1Click"
android:text="Show" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Plain" />
</LinearLayout>
</RelativeLayout>
Main:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.ollieapps.helloworld.MainActivity"
tools:ignore="MergeRootFrame" />
It seems you built your views inside fragment_main.xml and not activity_main.xml.
When you first create a new android project, you have these files which are automatically created and opened:
Then, when you begin, you add views (e.g: a TextView) inside fragment_main.xml file. Finally, you tried to do a basically event with this view inside your Activity, something like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // Using layout activity_main.xml
// You try to set a simple text on the view (TextView) previously added
TextView text = (TextView) findViewById(R.id.textView1);
text.setText("Simple Text"); // And you get an error here!
/*
* You do an fragment transaction to add PlaceholderFragment Fragment
* on screen - this below snippnet is automatically created.
*/
if(savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
You cannot run your app or sometimes you have only a white screen, because the views that you tried to call/display are into the wrong layout..
Solution: Move all your stuff inside onCreateView method into the Fragment class.
As DoctororDrive said in his comment
Call views and do something in the related fragment and not the parent activity.
For example, in your case, these following lines:
pepBox = (CheckBox) findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) findViewById(R.id.checkBox2);
textView = (TextView) findViewById(R.id.textView1);
might be inside your fragment because you created it in fragment_main.xml layout. Then:
// start fragment
public static class PlaceholderFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Use the layout which is displayed it's fragment_main.xml
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// Find your views here!
// Don't forget to findViewById attached to the inflated view "rootView.findView..."
pepBox = (CheckBox) rootView.findViewById(R.id.checkBox1);
cheeseBox = (CheckBox) rootView.findViewById(R.id.checkBox2);
textView = (TextView) rootView.findViewById(R.id.textView1);
/*
* Do something here: click listener, set a text, check a box..
*/
return rootView;
}
/*
* Perform other methods still inside the fragment
*/
public void onButton1Click(View v){
if(v.getId() == R.id.button1){
StringBuilder str = new StringBuilder("");
if (pepBox.isChecked()) {
str.append("Pepperoni"+" ");
}
if (cheeseBox.isChecked()) {
str.append("Extra Cheese");
}
if (str.length() == 0) {
str.append("Plain");
}
textView.setText(str);
}
}
}
// end fragment
if (pepBox.isChecked()) {
This line of code is failing with a NullPointerException because pepBox was declared but it's not being initialized as it should (and is therefore null at this point in the code).
Here is its declaration line:
TextView textView; CheckBox pepBox, cheeseBox;
And here is its initialization:
pepBox = (CheckBox) findViewById(R.id.checkBox1);
The problem is that (a) this line is not be called, or (b) findViewById(R.id.checkBox1) is returning null.
If findViewByID is returning null then you probably want to refer to this question, which addresses exactly this issue. Its "related questions", down the right-hand side, should also be helpful.

Android application has stopped working -eclipse

I have been tried to build my first Android Application. Every time I open the application in the emulator, I just get a message that says test has stopped working. It must be something simple. Hope you can help me.
04-06 15:43:47.806: W/dalvikvm(4275): threadid=1: thread exiting with
uncaught exception (group=0xa614d908)
04-06 15:43:47.826: E/AndroidRuntime(4275): FATAL EXCEPTION: main
04-06 15:43:47.826: E/AndroidRuntime(4275):
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.test/com.test.MainActivity}:
java.lang.NullPointerException
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.access$600(ActivityThread.java:141)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.os.Handler.dispatchMessage(Handler.java:99)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.os.Looper.loop(Looper.java:137)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.main(ActivityThread.java:5041)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
java.lang.reflect.Method.invokeNative(Native Method)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
java.lang.reflect.Method.invoke(Method.java:511)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
dalvik.system.NativeStart.main(Native Method)
04-06 15:43:47.826: E/AndroidRuntime(4275): Caused by:
java.lang.NullPointerException
04-06 15:43:47.826: E/AndroidRuntime(4275): at
com.test.MainActivity.onCreate(MainActivity.java:30)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.Activity.performCreate(Activity.java:5104)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
04-06 15:43:47.826: E/AndroidRuntime(4275): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
04-06 15:43:47.826: E/AndroidRuntime(4275): ... 11 more
Above is the log file
public class Main extends ActionBarActivity {
int counter ;
Button add, sub ;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
counter = 0;
add = (Button) findViewById (R.id.bAdd);
sub = (Button) findViewById (R.id.bsub);
display = (TextView) findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter --;
display.setText("Your total is " + counter);
}
});
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;
}
}
}
Above is the Main class
<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.test.MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/tvDisplay"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignLeft="#+id/bsub"
android:layout_alignParentBottom="true"
android:layout_below="#+id/bsub"
android:gravity="center"
android:text="Your total is 0"
android:textSize="45dp" />
<Button
android:id="#+id/badd"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="16dp"
android:layout_marginTop="78dp"
android:gravity="center"
android:text="Add one"
android:textSize="20dp" />
<Button
android:id="#+id/bsub"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/badd"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Subtract one"
android:textSize="20dp" />
</RelativeLayout>
Above is the fragment_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.Hello.firstapp.Main"
tools:ignore="MergeRootFrame" />
ABove is the activity_main.xml
Instead of onCreate() move all ur initialization into onCreateView() as those buttons and textview is in ur fragment_main.xml thats why u got NPE as those buttons and textview is not the part of activity_main.xml.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
counter = 0;
add = (Button) rootView.findViewById (R.id.bAdd);
sub = (Button) rootView.findViewById (R.id.bsub);
display = (TextView) rootView.findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter --;
display.setText("Your total is " + counter);
}
});
return rootView;
}
I see your issue. activity_main.xml contains a frame layout, in which your fragment_main.xml is inflated. The thing is that, both add and sub are null, as you're looking for them in the wrong layout. Thus, call the FragmentTransaction first and move all your button code to the onCreateView of the PlaceHolderFragment and your issue should be fixed. I have provided the fixed code, all you have to do is copy it and remove the button code from onCreate (...)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
counter = 0;
add = (Button) rootView.findViewById (R.id.bAdd);
sub = (Button) rootView.findViewById (R.id.bsub);
display = (TextView) rootView.findViewById(R.id.tvDisplay);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter++;
display.setText("Your total is " + counter);
}
});
sub.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter --;
display.setText("Your total is " + counter);
}
});
return rootView;
}
Most likely
add = (Button) findViewById (R.id.bAdd);
returns null, because the element is not defined on your activity_main view.

Categories