1

I am a student and this is an assignment. I followed the directions for this program but when I run my app it crashes. Based off of the stack trace I believe the issue is with the Intent. But I do not know for sure. Could someone examine my code and explain what is wrong and why.

The main activity that calls another activity

  package edu.cvtc.android.activitylab;

  import android.os.Bundle;
  import android.app.Activity;
  import android.content.Intent;
  import android.view.Menu;
  import android.view.View;
  import android.view.View.OnClickListener;


  public class EnterNameActivity extends Activity implements OnClickListener{

    android.widget.EditText nameField;
    android.widget.Button okButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.name_getter);

        //EditText nameField = (EditText) findViewById(R.id.editText1);
        this.nameField.findViewById(R.id.editText1); 
        //Button okButton =  (Button) findViewById(R.id.button1);
        this.okButton.findViewById(R.id.button1);
        //EditText and Button are used to type cast the variables because
        //findViewById only returns an object. 

        okButton.setOnClickListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_entername, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        // Get the text value the user entered
        String tempText =  nameField.getText().toString();

        //Clear the text field if there is data
        if(tempText != ""){

            nameField.setText("");
        }

        //Create an Intent to call another activity
        Intent myIntent = new Intent(this, LayoutMainActivity.class);

        //Passing the user entered name to the main greeting activity
        myIntent.putExtra("name", tempText);
        this.startActivity(myIntent);
    }

  }

The other activity

  package edu.cvtc.android.activitylab;

  import android.os.Bundle;
  import android.app.Activity;
  import android.view.Menu;
  import android.widget.TextView;

  public class LayoutMainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);

        android.os.Bundle temp = this.getIntent().getExtras();

        if(temp != null){
            //Extract the username from the bundle
            String userName = temp.getString("name");

            //get the TextView Id to change the text
            TextView text = (TextView) findViewById(R.id.textView1);

            text.setText("Hello " + userName);
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_layout_main, menu);
        return true;
    }

  }

The manifest

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

    <uses-sdk
        android:minSdkVersion="10"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="edu.cvtc.android.activitylab.LayoutMainActivity"
            android:label="@string/app_name" >

        </activity>
        <activity
            android:name="edu.cvtc.android.activitylab.EnterNameActivity"
            android:label="@string/title_activity_enter_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

  </manifest>

Stack trace from the debug

Thread [<1> main] (Suspended (exception RuntimeException))  
    <VM does not provide monitor information>   
    ActivityThread.handleLaunchActivity(ActivityThread$ActivityClientRecord, Intent) line: 2261 
    ActivityThread.access$600(ActivityThread, ActivityThread$ActivityClientRecord, Intent) line: 141    
    ActivityThread$H.handleMessage(Message) line: 1256  
    ActivityThread$H(Handler).dispatchMessage(Message) line: 99 
    Looper.loop() line: 137 
    ActivityThread.main(String[]) line: 5103    
    Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]  
    Method.invoke(Object, Object...) line: 525  
    ZygoteInit$MethodAndArgsCaller.run() line: 737  
    ZygoteInit.main(String[]) line: 553

If you need any of the other XML files please let me know.

user1793408
  • 113
  • 11

4 Answers4

1

What you are doing here is wrong I suppose:

//EditText nameField = (EditText) findViewById(R.id.editText1);
        this.nameField.findViewById(R.id.editText1); 
        //Button okButton =  (Button) findViewById(R.id.button1);
        this.okButton.findViewById(R.id.button1);
        //EditText and Button are used to type cast the variables because
        //findViewById only returns an object.

Just replace:

this.nameField.findViewById(R.id.editText1); 

and

this.okButton.findViewById(R.id.button1);

By:

nameField = (EditText) findViewById(R.id.editText1);

and

okButton =  (Button) findViewById(R.id.button1);

Hope this helps.

user2652394
  • 1,686
  • 1
  • 13
  • 15
  • Thank you, that fixed the problem and everything is working now. would it have worked if I had done: this.nameField = (EditText) findViewById(R.id.editText1); – user1793408 Sep 10 '13 at 03:06
1

You didn't provide the full stacktrace so its hard to say exactly what is causing your first error but there are many issues here. I will provide some comments in the code that hopefully will help.

First, you almost had your initialization of your Views correct but you changed them. Change your onCreate() from

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.name_getter);

    //EditText nameField = (EditText) findViewById(R.id.editText1);
    this.nameField.findViewById(R.id.editText1); // this returns an EditText object so it isn't being applied to a variable. 
    //Button okButton =  (Button) findViewById(R.id.button1);
    this.okButton.findViewById(R.id.button1);
    //EditText and Button are used to type cast the variables because
    //findViewById only returns an object. 

    okButton.setOnClickListener(this);
}

to

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.name_getter);

    EditText nameField = (EditText) findViewById(R.id.editText1);
    Button okButton =  (Button) findViewById(R.id.button1);

    okButton.setOnClickListener(this);
}

Also change your initialization of the Intent to use the Activty Context by changing

  //Create an Intent to call another activity
    Intent myIntent = new Intent(this, LayoutMainActivity.class);

to

  //Create an Intent to call another activity
    Intent myIntent = new Intent(EnterNameActivity .this, LayoutMainActivity.class);

Here is another problem

if(tempText != ""){

when you compare Strings this way you compare if the objects are equal but not what they reference. It should be

if(!"".equals(tempText)){

This says, if an empty String is not equal to the value of tempText. Alternatively you may see

if (!tempText.equals("")){

but the first way will protect against a NPE because if tempText is null you will get a NPE in the second way since you would be calling a function on an object that is null

codeMagic
  • 44,549
  • 13
  • 77
  • 93
  • Thank you, I did post everything that appeared in the stack trace. But then I had over 2 hours where nothing would run on the emulator and now logcat and console do not even show anything either. On the activity context isn't "this" already supplying the context? – user1793408 Sep 10 '13 at 03:23
  • When you can, testing on an actual device is always better. As far as `Context` you should be ok here, but you will really need to understand when to use which `Context` if you continue to develop for Android. [This answer](http://stackoverflow.com/questions/18704228/is-there-any-difference-between-activityname-this-this/18704355#18704355) should help with that. Also, pay special attention to the last part of my answer about comparing `Strings` because that will get you later if you don't understand it – codeMagic Sep 10 '13 at 03:52
  • I made the change to the if statement. The difference between comparing objects and primitives is one of those things that hasn't stuck yet. I read part of the other post and will finish it, but I understand what you mean now. "this" can be referring to the method that it is in when I actually want the activity. So many rules, so little brain space! – user1793408 Sep 10 '13 at 04:19
  • Keep trying. All of a sudden it will just start to click and you will be fine – codeMagic Sep 10 '13 at 12:38
0
        EditText nameField = (EditText) findViewById(R.id.editText1);

        Button okButton =  (Button) findViewById(R.id.button1);

        //EditText and Button are used to type cast the variables because
        //findViewById only returns an object. 

okButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View arg0) {
        // Get the text value the user entered
        String tempText =  nameField.getText().toString();

        //Clear the text field if there is data
        if(tempText != ""){

            nameField.setText("");
        }

        //Create an Intent to call another activity
        Intent myIntent = new Intent(EnterNameActivity.this, LayoutMainActivity.class);

        //Passing the user entered name to the main greeting activity
        myIntent.putExtra("name", tempText);
        startActivity(myIntent);
}

this is better way to deal with edittexts, buttons, and onClicks.

*remove onClick from activity, and remove onclick method and button and edittext importing methods that u used this.

Ahmed Ekri
  • 4,601
  • 3
  • 23
  • 42
  • Why would you suggest changing the way the `onClick()` is handled? The way the OP is doing it is fine and much cleaner, IMHO. The problem doesn't appear to be with the way the `onClick()` is handled but with the initialization of the variables – codeMagic Sep 10 '13 at 03:08
0

Try this way

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_main);




            //Extract the username from the bundle
            String userName = getIntent().getStringExtra("name"); // UPDATE HERE

            //get the TextView Id to change the text
            TextView text = (TextView) findViewById(R.id.textView1);

            text.setText("Hello " + userName!=null?userName:""); // UPDATE HERE

    }
Biraj Zalavadia
  • 28,348
  • 10
  • 61
  • 77