2

So, I'm just starting to learn how to code Java/Android but i've been making this real simple code, but i seem to to get stuck......

MainAcitivty.Java

package com.example.button;

import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
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;
import android.os.Build;

public class MainActivity extends ActionBarActivity {

    int counter;
    Button add, sub;
    TextView display;

    @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();
            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+=1;
                    display.setText("Your Total is "+ counter);
                }
            });

            sub.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    counter-=1;
                    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;
        }
    }

}

fragment_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_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.example.button.MainActivity$PlaceholderFragment" >

<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:hint="Your Total is 0" 
    android:textSize="40dp"
    android:layout_gravity="center"
    android:gravity="center"
    android:id="@+id/tvDisplay"
    android:orientation="vertical"
    />

<Button
    android:id="@+id/bSub"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/tvDisplay"
    android:layout_below="@+id/tvDisplay"
    android:hint="Subtract one"
    android:textSize="20dp" />

<Button
    android:id="@+id/bAdd"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/bSub"
    android:layout_below="@+id/bSub"
    android:hint="Add one"
    android:textSize="20dp" />

  </RelativeLayout>

AndoridManifest.xml

    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.button"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="19" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.button.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Error I've been getting

    04-04 04:15:22.332: E/AndroidRuntime(1524): FATAL EXCEPTION: main
    04-04 04:15:22.332: E/AndroidRuntime(1524): Process: com.example.button, PID: 1524
    04-04 04:15:22.332: E/AndroidRuntime(1524): java.lang.RuntimeException: Unable to start activity     ComponentInfo{com.example.button/com.example.button.MainActivity}: java.lang.NullPointerException
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at android.os.Handler.dispatchMessage(Handler.java:102)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at android.os.Looper.loop(Looper.java:136)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at android.app.ActivityThread.main(ActivityThread.java:5017)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at java.lang.reflect.Method.invokeNative(Native Method)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at java.lang.reflect.Method.invoke(Method.java:515)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at dalvik.system.NativeStart.main(Native Method)
    04-04 04:15:22.332: E/AndroidRuntime(1524): Caused by: java.lang.NullPointerException
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at com.example.button.MainActivity.onCreate(MainActivity.java:35)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at android.app.Activity.performCreate(Activity.java:5231)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
    04-04 04:15:22.332: E/AndroidRuntime(1524):     ... 11 more

Thank you so much for they help :D

New error i got after changing the Activity_main to Fragment

04-04 04:44:46.902: E/AndroidRuntime(1575): FATAL EXCEPTION: main
04-04 04:44:46.902: E/AndroidRuntime(1575): Process: com.example.button, PID: 1575
04-04 04:44:46.902: E/AndroidRuntime(1575): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.button/com.example.button.MainActivity}: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.button:id/container) for fragment PlaceholderFragment{b1dcdaa0 #0 id=0x7f05003c}
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.os.Handler.dispatchMessage(Handler.java:102)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.os.Looper.loop(Looper.java:136)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.app.ActivityThread.main(ActivityThread.java:5017)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at java.lang.reflect.Method.invokeNative(Native Method)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at java.lang.reflect.Method.invoke(Method.java:515)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at dalvik.system.NativeStart.main(Native Method)
04-04 04:44:46.902: E/AndroidRuntime(1575): Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.button:id/container) for fragment PlaceholderFragment{b1dcdaa0 #0 id=0x7f05003c}
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:930)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1115)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1478)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:570)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.app.Activity.performStart(Activity.java:5241)
04-04 04:44:46.902: E/AndroidRuntime(1575):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2168)
04-04 04:44:46.902: E/AndroidRuntime(1575):     ... 11 more
GrIsHu
  • 29,068
  • 10
  • 64
  • 102
hjkim1205
  • 23
  • 3
  • What's your line 35 of your MainActivity.java file? – nKn Apr 04 '14 at 08:42
  • You All Buttons Views belogs to fragment_main.xml layout. – M D Apr 04 '14 at 08:43
  • i think this question asked more than 10 time with other user like http://stackoverflow.com/questions/22737319/unfortunately-application-has-stopped-android-emulator-genymotion?noredirect=1#comment34655134_22737319 with same property – Shayan Pourvatan Apr 04 '14 at 08:43
  • @shayanpourvatan i voted to close this question as a duplicate. But if you think its the same user you can flag the question for moderator attention. Anyway this certainly seems to be a duplicate – Raghunandan Apr 04 '14 at 08:58
  • @Raghunandan i flag for moderator attention, because i think is same user with multiple account, thanks for support – Shayan Pourvatan Apr 04 '14 at 08:59
  • what... I just joined this website.... – hjkim1205 Apr 04 '14 at 16:52

6 Answers6

1

Your EditText and command Button are in fragment_main.xml file , hence change this line

setContentView(R.layout.activity_main);

to

setContentView(R.layout.fragment_main);  
Lucifer
  • 29,392
  • 25
  • 90
  • 143
1

What you ahve

setContentView(R.layout.activity_main);

Button add is in fragment layout

<Button
android:id="@+id/bAdd"

SO your initializaton fails leading to NullPointerException.

You need to move the initization of your views to fragment.

Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.example.button:id/container) for fragment PlaceholderFragment{b1dcdaa0 #0 id=0x7f05003c}

This clearly indicates that you do not have a ViewGroup with the id container in the layout that you set to the Activity.

coz you have

getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
Raghunandan
  • 132,755
  • 26
  • 225
  • 256
0

Your Button, TextView and all other UI elements are not in your activity_main but it is in fragment_main.xml. So check your xml file and find id for all UI elements according to it.

Also you have to call

setContentView(R.layout.fragment_main);

instead of

setContentView(R.layout.activity_main);
Rajendra
  • 127
  • 4
0

Check the layout name you use when calling

setContentView(R.layout.activity_main);

corresponds to the file name in your project res/layout folder

As you mentioned above the layout seems to be fragment_main.xml not activity_main*.xml..

Rajendra
  • 127
  • 4
csharpwinphonexaml
  • 3,659
  • 10
  • 32
  • 63
0

The problem is that you're trying to do the click event handling of fragment buttons from the activity. The bAdd and bSub buttons belong to the fragment's layout, but you're trying to access them from the activity (by calling findViewById on the activity). These calls produce null since they are not in the activity's layout.

The correct way to go about this, would be to move the handling for buttons in the fragment's layout to the fragment class. This is how fragments are intended to be used: self-contained pieces which you can use in a parent activity. Thus, you should move most of the code from MainActivity.onCreate to PlaceholderFragment.onActivityCreated.

Alternatively, if you aren't really planning to reuse PlaceholderFragment, you can just get rid of it and move everything into the activity's layout. You don't have to use fragments for simple use cases.

Mattias Buelens
  • 19,609
  • 4
  • 45
  • 51
0

Make sure in your activity_main layout there is view FrameLayout having id container as 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....MainActivity"
    tools:ignore="MergeRootFrame" />
GrIsHu
  • 29,068
  • 10
  • 64
  • 102