Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

onClick method not called on Android

I am doing the simplest of onClick models and cannot get the onClick method to fire. I know it is something simple, and I am new to Android. Any help is appreciated.

package com.bordeloniphone.timeentry;

import android.app.Activity;
import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class TimeEntryActivity extends Activity implements OnClickListener{
    /** Called when the activity is first created. */

    Button okButton;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        okButton = (Button) findViewById(R.id.btnOK);
        okButton.setText(":)");
        okButton.setOnClickListener(this);
        //setContentView(okButton);

    }

    public void onClick(View v) {
        Log.d("TEST", "TEST");
        Toast.makeText(this, "TEST", Toast.LENGTH_SHORT).show();

    }

}

Here is the main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:id="@+id/btnOK"
        android:layout_width="80dp"
        android:layout_height="wrap_content"
        android:text="OK" />

</LinearLayout>
like image 683
Michael Bordelon Avatar asked Dec 03 '11 03:12

Michael Bordelon


3 Answers

After much angst and gnashing of teeth, I figured it out. I had to delete the emulator device and add an new one and now it works like a champ. I appreciate everyone trying to help.

like image 189
Michael Bordelon Avatar answered Nov 01 '22 11:11

Michael Bordelon


Instead of setting the onClicklistener to this, try this approach:

okButton.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            Log.d("TEST", "TEST");
            Toast.makeText(this, "TEST", Toast.LENGTH_SHORT).show();
        }
    });
like image 27
Chris Avatar answered Nov 01 '22 11:11

Chris


You should try Cleaning your project or try to restart your Eclipse or any other Editor you are using as it is a valid code and should work fine.

UPDATE:

Also, you should check your Logcat, are you getting the output of Log.d("TEST", "TEST"); because your Toast seems to be implemented in a wrong manner.

Toast.makeText(this, "TEST", Toast.LENGTH_SHORT).show(); // wrong
Toast.makeText(Activity_name.this, "TEST", Toast.LENGTH_SHORT).show(); // correct

Using this in Toast inside the Listener means you are Referencing the Listener, which indeed should not be the case. You have to reference to the Activity itself so better use Activity_name.this.

like image 33
Lalit Poptani Avatar answered Nov 01 '22 10:11

Lalit Poptani