-2

I know this has been asked a lot, already have done search on this particular topic. and all of them returns the same answer but doesn't solve my problem, I have a button created on separate xml, used as a fragment. TabbedActivity just wont fire up, App is crashing when button is clicked, even throws NPE on first code used. just don't know what to do.

import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        //Set HomeFragment as user starts the app.
        if (savedInstanceState == null){
            InitStartFrag();
        }

//-----BUG!-----//
1st:Code Used
android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)findViewById(R.id.myButton);
    myButton.setOnClickListener(new View.OnClickListener(){
        @Override
            public void onClick(View v){
                Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
                startActivity(intent);
        }
    });

2nd Code:
public void doThis(View view){
        Intent intent = new Intent(this, TabbedActivity.class);
        MainActivity.this.startActivity(intent);
    }

3rd Code:
public void doThis(View view){
        setContentView(R.layout.activity_tabbed);
    }
//-----Bug Ends-----//


        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

    }



    private void InitStartFrag() {
        android.app.FragmentManager fragmentManager = getFragmentManager();
        android.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        .....
        .....
   }

The Log Cat:

Process: com.my_app.app_one, PID: 3799
java.lang.IllegalStateException: Could not find a method doThis(View) in the activity class android.support.v7.widget.TintContextWrapper for onClick handler on view class android.support.v7.widget.AppCompatButton with id 'myButton'
at android.view.View$1.onClick(View.java:3843)
at android.view.View.performClick(View.java:4471)
at android.view.View$PerformClick.run(View.java:18778)
at android.os.Handler.handleCallback(Handler.java:808)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:5324)
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:824)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NoSuchMethodException: doThis [class android.view.View]
at java.lang.Class.getConstructorOrMethod(Class.java:472)
at java.lang.Class.getMethod(Class.java:864)
at android.view.View$1.onClick(View.java:3836)
at android.view.View.performClick(View.java:4471) 
at android.view.View$PerformClick.run(View.java:18778) 
at android.os.Handler.handleCallback(Handler.java:808) 
at android.os.Handler.dispatchMessage(Handler.java:103) 
at android.os.Looper.loop(Looper.java:193) 
at android.app.ActivityThread.main(ActivityThread.java:5324) 
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:824) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:640) 
at dalvik.system.NativeStart.main(Native Method) 

The Manifest:

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.my_app.app_one">

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:configChanges="keyboardHidden|orientation"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".TabbedActivity"
            android:label="@string/title_activity_tabbed"
            android:parentActivityName=".MainActivity"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value="com.my_app.app_one.MainActivity" />
        </activity>
    </application>

</manifest>

The XML, used as Fragment : buttons_layout.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.percent.PercentRelativeLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <!--Upper Buttons-->

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:text="Fire"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn1"
            android:textColor="@color/colorBtnText1"
            android:drawableStart="@drawable/fire_icon"
            android:drawablePadding="-62dip"
            android:paddingLeft="30dip"
            android:paddingRight="26dip"
            android:singleLine="true"
            android:gravity="center"
            android:onClick="doThis"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton1"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:layout_below="@id/myButton"
            android:text="Flood"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn3"
            android:textColor="@color/colorBtnText3"/>

        <!-- Divider -->

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton2"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@id/myButton1"
            android:text="Thunder"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn2"
            android:textColor="@color/colorBtnText2"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton4"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_below="@id/myButton2"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@id/myButton1"
            android:text="Civil Defense Operation Center"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn4"
            android:textColor="@color/colorBtnText4"/>

        <!--Lower Buttons-->

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton5"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:layout_below="@id/myButton3"
            android:text="Landslide"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn5"
            android:textColor="@color/colorBtnText5"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton7"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:layout_below="@id/myButton5"
            android:text="Women and Children Protection Center"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn7"
            android:textColor="@color/colorBtnText7"/>

        <!-- Divider -->

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton6"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_gravity="center_horizontal"
            android:layout_below="@id/myButton4"
            android:layout_toEndOf="@id/myButton3"
            android:text="Storm"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn6"
            android:textColor="@color/colorBtnText6"/>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/myButton8"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_below="@id/myButton6"
            android:layout_gravity="center_horizontal"
            android:layout_toEndOf="@id/myButton5"
            android:text="Earthquake"
            android:textSize="15sp"
            app:layout_heightPercent="25%"
            app:layout_widthPercent="50%"
            app:backgroundTint="@color/colorBtn8"
            android:textColor="@color/colorBtnText8"/>


    </android.support.percent.PercentRelativeLayout>


</LinearLayout>

New Code Used:

private void InitBtnListener(){
        LayoutInflater layoutInflater = this.getLayoutInflater();
        View view = layoutInflater.inflate(R.layout.buttons_layout,null);

        android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)view.findViewById(R.id.myButton);
        myButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, TabbedActivity.class);
                startActivity(intent);
            }
        });
    }

TabbedFragment.java Code

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;


public class TabbedFragment extends Fragment implements OnClickListener {

    View myView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        myView = inflater.inflate(R.layout.survival_tips_layout,container,false);
        android.support.v7.widget.AppCompatButton myButton = (android.support.v7.widget.AppCompatButton)myView.findViewById(R.id.myButton);
        myButton.setOnClickListener(this);
        return myView;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.myButton:

        //--Missing Code:--// 
        After Btn Click Fire up that TabbedActivity.
        //--Ends--//

        // Can I do intents Here?
        Intent intent = new Intent(MainActivity.this,TabbedActivity.class);
        startActivity(intent);
        break;

        }

    }
}
xenteros
  • 15,586
  • 12
  • 56
  • 91

1 Answers1

0

This line needs to be above any findViewById

setContentView(R.layout.activity_main);

If the android:onClick is defined from the XML, you need a public method that accepts a View parameter with that name.

For example, android:onClick="doThis" means you need this method

public void doThis(View view) {
    // TODO: Handle click
}

i have a button created on separate xml, used as a fragment

Then you need to find that button from the Fragment class. You can't find it from the Activity.

For example

public class MyFragment extends Fragment {

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState) {
        // Inflate the layout
        View rootView = inflater.inflate(R.layoutbuttons_layout, parentViewGroup, false);

        Button button = (Button) rootView.findViewById(R.id.button);
        // TODO: button.setOnClickListener();

        return rootView;
    }

    // OR... if you have android:onclick="doThis"
    public void doThis(View view) {
        // TODO: Handle click
    }
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • Thanks, i did defined it from the xml. i also created that separate function from the MainActivity.java. i just dont what exact code to put when it calls that function. notice the 2nd code used. is that a proper approach? – NewbieBeLike Aug 31 '16 at 17:04
  • That depends in which XML the button is. But, that is the correct approach if that method were not inside of another method. "1st code used" is my recommended approach, but again, you have to set the content view of the activity before you can find the button. Please `edit` your question to show which XML file that the button is contained in – OneCricketeer Aug 31 '16 at 17:07
  • dude, i am currently using the second code. when i clicked the button, app crash. am i doing something wrong? that function stands alone in MainActivity.java – NewbieBeLike Aug 31 '16 at 17:46
  • Yes, 1) Your second code block is displayed inside the `onCreate` method, so it shouldn't compile. But, let's pretend it isn't actually where you have placed it in the question... 2) `setContentView(R.layout.activity_main);` means that whatever you are using `findViewById` for **must be** in `activitiy_main.xml`, however you have shown your XML is named `buttons_layout.xml`, which is for a Fragment class, which you have not shown, and **cannot** find that button from the Activity, thus the error – OneCricketeer Aug 31 '16 at 17:51
  • Thanks dude i get the idea, just dont know how to execute it, so ill just use that function to revert that setContentView(activity_main) to (activity_tabbed) then cast that XML in the doThis() function to navigate that Button then set the listener? just correct me dude, if something is wrong. – NewbieBeLike Aug 31 '16 at 18:01
  • Your error hints that the Fragment class might need the `doThis(View view)` method. With regards to any NPE, that's caused by the `findViewById` not finding the view – OneCricketeer Aug 31 '16 at 18:06
  • dude, ill did get what ur trying to tell me and ended up something like this. new code in the box. now, just want to know why still TabbedActivity doesn't fire up when button is clicked? – NewbieBeLike Aug 31 '16 at 20:20
  • Because you inflated a layout without attaching it to anything, probably. You say you are using a Fragment for that XML, but you still have not shown any Fragment class. You have to set the click listener from that class, not the Activity – OneCricketeer Aug 31 '16 at 20:28
  • yeah, my bad i was using a fragment with a button in it to fire up an activity. I just don't get it. i think i attached the inflated layout=view into that myButton, my question is, can i attach that on the listener to? sorry bro. im just new in this platform. – NewbieBeLike Aug 31 '16 at 20:35
  • Start simple. An activity has a XML layout. `setContentView` with that XML. You find a Button using `findViewById`. You attach a listener to that button. Straightforward enough. Now, using Fragments. Same XML. Load that into using a `LayoutInflater`. Use `findViewById` on the **inflated** view. Returning that view from `onCreateView` is how you "set the content view" of a Fragment. – OneCricketeer Aug 31 '16 at 22:08
  • Thanks dude. my bad i was coding all up in my MainActivity.java not in the TabbedFragment.java, TYVM, my last question is. how can i fire up an activity while im on this TabbedFragment.java? New code is up top. – NewbieBeLike Sep 01 '16 at 11:22
  • If you know the words to search for, I bet your questions have been answered already. http://stackoverflow.com/questions/12074608/how-do-i-start-an-activity-from-within-a-fragment – OneCricketeer Sep 01 '16 at 13:15
  • Atlast, the app works fine. how can i commend you dude? Thank you very much. – NewbieBeLike Sep 01 '16 at 15:37