-2

This is the code I did. But it did not work. Please help? The app itself lets the user enter his/her name on the EditText, he clicks on the button and the TextView will say like for example his name is Sam. "Your name is Sam".

    package com.example.myfirstandroidapp;

        import java.text.Format.Field;
        import java.util.EventListener;

        import javax.security.auth.PrivateCredentialPermission;

        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.view.View.OnClickListener;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.TextView;
        import android.os.Build;
        import android.provider.ContactsContract.CommonDataKinds.Event;


        public class MainActivity extends ActionBarActivity {
        EditText nameTextBox;
        TextView nameTextView;
        Button nameButton;
        @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();
        }
        nameTextBox = (EditText)findViewById(R.id.nameTextBox);
        nameTextView = (TextView)findViewById(R.id.nameTextView);
        nameButton = (Button)findViewById(R.id.nameButton);

        nameButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Clicker();
            }
        });
    }

    public void Clicker()
    {
        if (nameTextBox.getText().toString() != "")
        {
            nameTextView.setText("Your name is " + nameTextBox.getText().toString());
        }
    }


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

}

Xml layout

<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.example.myfirstandroidapp.MainActivity$PlaceholderFragment" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:text="Enter your name:"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <EditText
        android:id="@+id/nameTextBox"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:ems="10" >

        <requestFocus />
    </EditText>

    <Button
        android:id="@+id/nameButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/nameTextBox"
        android:layout_below="@+id/nameTextBox"
        android:text="I&apos;m Done!" />

    <TextView
        android:id="@+id/nameTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/nameButton"
        android:layout_below="@+id/nameButton"
        android:text="Your name has not been entered yet"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
Matty
  • 77
  • 1
  • 9

5 Answers5

0

Replace

nameTextBox.getText().toString() != "" 

with

!nameTextBox.getText().toString().equals("")

Probably this is your error.

João Marcos
  • 3,872
  • 1
  • 19
  • 14
  • IDK if that would cause a crash it just probably won't give the right result. – Rarw Jun 30 '14 at 13:48
  • if you have a fragment class, your code in Clicker() function should be called inside oncreateview function. – João Marcos Jun 30 '14 at 13:48
  • That's more likely the error I think the issue is trying to access views within the fragment from the onCreate method of the activity – Rarw Jun 30 '14 at 13:55
0

Just Change your code by below code :

package com.example.myfirstandroidapp;

        import java.text.Format.Field;
        import android.app.Activity;
        import android.os.Bundle;
        import android.view.View;
        import android.view.ViewGroup;
        import android.view.View.OnClickListener;
        import android.widget.Button;
        import android.widget.EditText;
        import android.widget.TextView;
        import android.os.Build;


        public class MainActivity extends Activity {
        EditText nameTextBox;
        TextView nameTextView;
        Button nameButton;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        nameTextBox = (EditText)findViewById(R.id.nameTextBox);
        nameTextView = (TextView)findViewById(R.id.nameTextView);
        nameButton = (Button)findViewById(R.id.nameButton);

        nameButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Clicker();
            }
        });
    }

    public void Clicker()
    {
        if (!nameTextBox.getText().toString().equals(""))
        {
            nameTextView.setText("Your name is " + nameTextBox.getText().toString());
        }
    }

}

As per your need there is not any requirement of fragments.

Baby Be'el
  • 234
  • 1
  • 4
  • 12
0

Your error probably is that this should be inside onCreateView() in your PlaceHolderFragment rather than in activity

nameTextBox = (EditText)findViewById(R.id.nameTextBox);
nameTextView = (TextView)findViewById(R.id.nameTextView);
nameButton = (Button)findViewById(R.id.nameButton);
Christopher Francisco
  • 15,672
  • 28
  • 94
  • 206
0

In your layout nameTextBox,nameTextBox,nameButton are null,because those are part of fragment not activity_main.

So either use nameTextBox,nameTextBox,nameButton in activity_main layout. or use in onCreateView method of fragment.

For more info see Access Fragment View from Activity's onCreate

Community
  • 1
  • 1
Giru Bhai
  • 14,370
  • 5
  • 46
  • 74
0

The lifecycle of a Fragment is tied to that of its host activity. For example the onActivityCreate() method of a Fragment is called after the host Activity calls its own onCreate method. You are getting an error because you are trying to access View objects that are contained within your Fragment layout from within your activity. This creates a problem because (1) those views do not exist yet at the time the host Activity calls onCreate() because the fragment has yet to be created; (2) findViewById() only searches within the contentView of Activity or Fragment that it is called from (i.e. if you look for a view that is within your Fragment's layout from within the host activity it findViewById will return null becuase the view is not within the Activity's layout).

What you need to do is move the code from your activity's onCreate method to your fragment. You can put this in either onActivityCreated or onViewCreated within your fragment and should access and set content from within the fragment itself. If you need access to the fragment contents you can keep a reference to the fragment within your hosting activity and access public methods within your fragment class.

You should set things up like this public class PlaceholderFragment1 extends Fragment{

    private EditText mNameTextBox;
    private TextView mNameTextView;
    private Button mNameButton;


    public void onActivityCreate(Bundle savedInstanceState){

        mNameTextBox = (EditText)findViewById(R.id.nameTextBox);
        mNameTextView = (TextView)findViewById(R.id.nameTextView);
        mNameButton = (Button)findViewById(R.id.nameButton);
        mNameButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (!mNameTextBox.getText().toString().isEmpty()){
                    mNameTextView.setText(
                        "Your name is "+mNameTextBox.getText().toString());
                 }
            });
    }


 }

I adapted your dropbox code to fix the issues you mentioned.

Rarw
  • 7,645
  • 3
  • 28
  • 46
  • I tried but it says Cannot make a static reference to the non-static field nameTextBox – Matty Jun 30 '14 at 14:05
  • That's right - I did not realize your fragment class is static. In that case you cannot access it as I described above. Do you need to keep it as an inner class? If you just move it to its own file as a regular public class (not static) you can access its methods directly. Otherwise you can use an interface to connect the static inner class to your outer activity. – Rarw Jun 30 '14 at 14:31
  • Sorry but I don't get you. I'm really new to Java and Android programming. Whichever is the simpliest?:) Thanks – Matty Jun 30 '14 at 14:39
  • Ok I did not realize. The "simplest" way is just to make the fragment its own class (i.e. make a new file, create a class the same way you did just make it public don't make it static). You should still look into how an interface works as it is a very useful too to have http://docs.oracle.com/javase/tutorial/java/concepts/interface.html – Rarw Jun 30 '14 at 15:06
  • Do I use extend or implement to create a new class? Public class extends fragment() OR Public class implements fragment()? Thank you for taking your time to help me really appreciate that:) – Matty Jul 01 '14 at 16:43
  • You would use extends. Fragment is a class. You are creating a sub-class of fragment. As you mentioned you are new to Java please do some googling on class and interfaces and how they relate. It is an important topic. – Rarw Jul 01 '14 at 17:52
  • I kinda understand what is a fragment, it is a class that uses interfaces, interface alone cannot do anything. Okay now I have done it. This is my code https://www.dropbox.com/s/g6hfiste1dr0wru/templayout.txt How do I not use the Final statement when it gives errors unless I put it in? Where and how do I call it out and use it? Many thanks. – Matty Jul 02 '14 at 16:05
  • Oh I see - it gives you an error if you don't use final because you are trying to access a non-final field from a different inner class (your onclick listener). You should probably just not set things up they way you are I will show you how above. – Rarw Jul 02 '14 at 17:52