0

I got the program to crash when using the simple code below as it is closed automatically after installing it

package com.zaki.thenewboston;

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.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

    int         counter;
    Button      add,sub;        //used to reference to xml view ids
    TextView    display;        //used to reference to xml view ids


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

            //zaki: this is to wait the R.layout.activity_main to load first other wise the program may crash
            counter =0;
            add = (Button) findViewById(R.id.bAdd);   
           // sub = (Button) findViewById(R.id.bSub); 
            display = (TextView) findViewById(R.id.tvDisplay);     
            add.setOnClickListener(new OnClickListener() {              
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    counter ++;
                    display.setText("Your total is" + counter);

                }
            });

          /*  
            sub.setOnClickListener(new OnClickListener() {  
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub  
                    counter --;
                    display.setText("Your total is" + 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.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;
        }
    }

}

Here is the logcat: I think there is a null returned, but why? I don't know the reason. and I'm sure that the problem in onCreateView

09-21 12:58:37.277: D/AndroidRuntime(1449): Shutting down VM
09-21 12:58:37.277: W/dalvikvm(1449): threadid=1: thread exiting with uncaught exception (group=0xb2a81ba8)
09-21 12:58:37.277: E/AndroidRuntime(1449): FATAL EXCEPTION: main
09-21 12:58:37.277: E/AndroidRuntime(1449): Process: com.zaki.thenewboston, PID: 1449
09-21 12:58:37.277: E/AndroidRuntime(1449): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.zaki.thenewboston/com.zaki.thenewboston.MainActivity}: java.lang.NullPointerException
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.os.Handler.dispatchMessage(Handler.java:102)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.os.Looper.loop(Looper.java:136)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.ActivityThread.main(ActivityThread.java:5017)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at java.lang.reflect.Method.invokeNative(Native Method)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at java.lang.reflect.Method.invoke(Method.java:515)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at dalvik.system.NativeStart.main(Native Method)
09-21 12:58:37.277: E/AndroidRuntime(1449): Caused by: java.lang.NullPointerException
09-21 12:58:37.277: E/AndroidRuntime(1449):     at com.zaki.thenewboston.MainActivity.onCreate(MainActivity.java:38)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.Activity.performCreate(Activity.java:5231)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-21 12:58:37.277: E/AndroidRuntime(1449):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-21 12:58:37.277: E/AndroidRuntime(1449):     ... 11 more

the file Activity_main.xml is below

 <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.zaki.thenewboston.MainActivity"
    tools:ignore="MergeRootFrame" />

and the file fragment_main.xml is below

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/LinearLayout1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    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.zaki.thenewboston.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/tvDisplay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="@string/your_total_is" />

    <Button
     android:layout_width="240dp"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:text="@string/add_one"
     android:textSize="20sp"
     android:id="@+id/bAdd"
     />

    <Button
     android:layout_width="240dp"
     android:layout_height="wrap_content"
     android:layout_gravity="center"
     android:text="@string/subtract_one"
     android:textSize="20sp"
     android:id="@+id/bSub"
     />

</LinearLayout>

note also that i changed the line

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

to be

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_main);

and the problem still exists

  • Copy paste the it :-) – Nabin Sep 21 '14 at 17:11
  • 1
    post the line number 38 in your class – SHASHIDHAR MANCHUKONDA Sep 21 '14 at 17:17
  • 1
    Paste your layout file(activity_main). My best guess is the layout file is missng the button. – Psypher Sep 21 '14 at 17:18
  • Does you activity_main XML file have a `Button` with id = bAdd ? – mt0s Sep 21 '14 at 17:37
  • @Nabin thanks , it wasnt the problem , i had to press Ctrl+ k for this – Fast Solutions Sep 21 '14 at 18:14
  • @Ranjith i updated the post now please check – Fast Solutions Sep 21 '14 at 18:21
  • @mt0s i updated the post now please check – Fast Solutions Sep 21 '14 at 18:23
  • @SHASHIDHARMANCHUKONDA the `add.setOnClickListener(new OnClickListener() {` – Fast Solutions Sep 21 '14 at 18:25
  • your activity_main does does not have the button. You have to move the button setonclicklistener code to the PlaceholderFragment along with declaration of add button – Psypher Sep 21 '14 at 18:33
  • @Ranjith i used the first sample which come with the ADT which print hello world and i modified it and i saw one file for the code and 2 xml files for the layout and i dont know the difference between both of them . also i replaced the line which uses the activity_main as i told in the last of the original post . so can you tell me the difference between both xml and what code should i change now ? – Fast Solutions Sep 21 '14 at 18:38
  • @Ranjith when i moved the code to the PlaceholderFragment , i got the following error " Cannot make a static reference to the non-static method findViewById(int) from the type Activity" – Fast Solutions Sep 21 '14 at 19:11
  • @SHASHIDHARMANCHUKONDA when i moved the code to the PlaceholderFragment , i got the following error " Cannot make a static reference to the non-static method findViewById(int) from the type Activity" – Fast Solutions Sep 21 '14 at 19:19
  • That's because the nested fragment class is static: `public static class PlaceholderFragment extends Fragment`. – stkent Sep 21 '14 at 21:13

2 Answers2

0

move this to fragment class

  counter =0;
            add = (Button) rootView.findViewById(R.id.bAdd);   

            display = (TextView) rootView.findViewById(R.id.tvDisplay);     
            add.setOnClickListener(new OnClickListener() {              
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    counter ++;
                    display.setText("Your total is" + counter);

                }
            });
SHASHIDHAR MANCHUKONDA
  • 3,302
  • 2
  • 19
  • 40
0

i discovered that the problem isn't only in moving the code to the PlaceholderFragment as i got a new compilation error as i posted

but also the following codes

            add = (Button) findViewById (R.id.bAdd);
            sub = (Button) findViewById(R.id.bSub);
            display = (TextView) findViewById(R.id.tvDisplay);

should be converted to be as following

            add = (Button) rootView.findViewById (R.id.bAdd);
            sub = (Button) rootView.findViewById(R.id.bSub);
            display = (TextView) rootView.findViewById(R.id.tvDisplay);

i appreciate comments with the explanation to what i made