Question

I just wanted to start making aps on Android, I know C++ a bit, but I'm fighting for few days with the simpliest thing - I can't make my buttons work.

I try every tutorials methods and I can't make the listener to button - everytime I do it my program just crushes.

The code is simple (I don't change anything below my methods) and I also started brand new Android Project and just did those button and TextView edits as in all the tutorials:

package com.example.buttonwork;

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.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
Button but1;
TextView tv1;
@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();
    }
    tv1 = (TextView) findViewById(R.id.tv1);
    but1 = (Button) findViewById(R.id.b1);
    but1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            tv1.setText("Button pressed");
        }
    });
}


@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;
    }
}

}

The LOGCAT:
04-26 15:51:39.435: W/dalvikvm(7185): threadid=1: thread exiting with uncaught exception (group=0x418762a0)
04-26 15:51:39.450: E/AndroidRuntime(7185): FATAL EXCEPTION: main
04-26 15:51:39.450: E/AndroidRuntime(7185): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.buttonwork/com.example.buttonwork.MainActivity}: java.lang.NullPointerException
04-26 15:51:39.450: E/AndroidRuntime(7185):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at android.app.ActivityThread.access$700(ActivityThread.java:140)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at android.os.Handler.dispatchMessage(Handler.java:99)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at android.os.Looper.loop(Looper.java:137)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at android.app.ActivityThread.main(ActivityThread.java:4921)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at java.lang.reflect.Method.invokeNative(Native Method)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at java.lang.reflect.Method.invoke(Method.java:511)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1027)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:794)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at dalvik.system.NativeStart.main(Native Method)
04-26 15:51:39.450: E/AndroidRuntime(7185): Caused by: java.lang.NullPointerException
04-26 15:51:39.450: E/AndroidRuntime(7185):     at com.example.buttonwork.MainActivity.onCreate(MainActivity.java:29)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at android.app.Activity.performCreate(Activity.java:5206)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
04-26 15:51:39.450: E/AndroidRuntime(7185):     at        android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
    04-26 15:51:39.450: E/AndroidRuntime(7185):     ... 11 more

And the program everytime crashes. I have everything imported, the IDs and names are also good. Please help me because now I am desperate. I just wanted to run through those simple things and start coding something that really works and have and output, but I am stuck in such a simple step...

Was it helpful?

Solution

Here you go.. this is where you were making that mistake. You were trying to get the reference in you activity instead of the fragment you have defined.

Remove the buttons from your onCreate() and in you place holder fragment, add those components. That's the reason you were getting a null pointer.

NOTE: use getActivity() to reference your components in a fragment.

In you fragment you gotta make that change like this:

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;
    }
    
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onActivityCreated(savedInstanceState);
        
        Button but1 = (Button)getActivity(). findViewById(R.id.b1);
        TextView tv1 = (TextView)getActivity(). findViewById(R.id.tv1);
        
        but1.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                
                tv1.setText("Button pressed");
                
            }
        });
    }
}

Hope this helps.. :)

OTHER TIPS

Use this and remove tb1 and bt1 initialization code from onCreate(Bundle savedInstanceState) method

/**
 * 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);
 tv1 = (TextView) (rootView.findViewById(R.id.tv1));
    but1 = (Button) (rootView.findViewById(R.id.b1));
    but1.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            tv1.setText("Button pressed");
        }
    });
        return rootView;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top