Android/Eclipse - saving button error - android

I have some problems with the "setOnClickListener(onSave)” and “View.OnClickListener”
Below is my code:
package apt.tutorial;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class LunchList extends Activity {
Restaurant r = new Restaurant ();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//save button
//be notified when the button is clicked
Button save =(Button)findViewById(R.id.save);
save.setOnClickListener(onSave){
}
private View.OnClickListener onSave=new View.OnClickListener();
public void onClick(View v) {
EditText name=(EditText)findViewById(R.id.name);
EditText address=(EditText)findViewById(R.id.addr);
r.setName(name.getText().toString());
r.setAdress(address.getText().toString());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
for save.setOnClickListener(onSave) I get the error save.setOnClickListener(onSave) and for View.OnClickListener I get the error Cannot instantiate the type View.OnClickListener.
I looked on this website and googled for this problem put I didn’t find a solution. I hope you guys can help me out.
Greets.

Remove semicolon after
private View.OnClickListener onSave=new View.OnClickListener();
and write onClick(View v) inside anonomous constructor of onClickListener
or else change your code with below code.
private View.OnClickListener onSave=new View.OnClickListener(
public void onClick(View v) {
EditText name=(EditText)findViewById(R.id.name);
EditText address=(EditText)findViewById(R.id.addr);
r.setName(name.getText().toString());
r.setAdress(address.getText().toString());
});
Button save =(Button)findViewById(R.id.save);
save.setOnClickListener(onSave);

try the following code:
start.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
mainactivity();
}
});

Related

Android Studio Unable to Start Activity, Cannot cast to android.view.View$OnClickListener

We are working on creating a basic app in my online class and I keep running into this issue where the Instructions have us type a method with an #Override for an onClick. I was able to get one of the methods to work with an autofill help from A.S. itself but this next one won't fix itself out. I have run into other issues over this class as well and I know the Instructions are a few years old. Possibly out of date now?
I'm pretty new to Android Java and coding overall. It seems that the app is trying to use the onClick method incorrectly. I will post the whole class I'm working with because I'm not sure where the problem is exactly.
package com.test.firstandroidapp;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.Spinner;
import android.widget.Switch;
import android.widget.TextView;
public class InformationPageActivity extends AppCompatActivity {
Button btnSave;
Spinner spnSeason;
SeekBar skbTemp;
TextView lblSeekValue;
Switch swchAllergy;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_information_page);
spnSeason = (Spinner) findViewById(R.id.spnSeason);
skbTemp = (SeekBar) findViewById(R.id.skbTemp);
swchAllergy = (Switch) findViewById(R.id.swchAllergy);
lblSeekValue = (TextView) findViewById(R.id.lblSeekValue);
btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener((View.OnClickListener) this);
skbTemp.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
String display = String.valueOf(progress);
lblSeekValue.setText(display);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
#Override
public void onClick(View v) {
String season, allergies;
int temperature;
season = spnSeason.getSelectedItem().toString();
temperature=skbTemp.getProgress();
allergies = (String) (swchAllergy.isChecked() ? swchAllergy.getTextOn() : swchAllergy.getTextOff()); //if the switch is on then the user has allergies
Intent intent = new Intent(InformationPageActivity.this, InformationResultsActivity.class); //pass information to the results activity
intent.putExtra("season", season);
intent.putExtra("temperature", temperature);
intent.putExtra("allergies", allergies);
this.startActivity(intent);
}
}
And here is the Main Menu Class parts that go to the view i'm trying to have opened, The onclicklistener is inside the onCreate method and the goInfo is it's own method
Button btnInfo = (Button) findViewById(R.id.btnInfo);
btnInfo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
goInfo();
}
}
);
}
private void goInfo() {
Intent intent = new Intent(MainMenuActivity.this, InformationPageActivity.class);
this.startActivity(intent);
}
I was able to find the issue. I needed to add an implements statement to the class for the onclicklistener. I'm answering my own question in case someone in the future has the same error. Here is what I did.
My problematic class was
public class InformationPageActivity extends AppCompatActivity {
This was causing the error "java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.firstandroidapp/com.test.firstandroidapp.InformationPageActivity}: java.lang.ClassCastException: com.test.firstandroidapp.InformationPageActivity cannot be cast to android.view.View$OnClickListener"
I solved the issue by fixing the class adding the implements
public class InformationPageActivity extends AppCompatActivity implements View.OnClickListener {

Going to second activity by password

I am new to coding.I want to code
in order to go to second activity using a button,
an editText and a pasdword in case it maches.
But it does n`t work.Please help me.Following is my code:
package com.mycompany.myapp;
import android.app.*;
import android.os.*;
import android.content.*;
import android.view.*;
import android.view.View.*;
import android.widget.*;
public class MainActivity extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
EditText eText= (EditText)findViewById(R.id.mainEditText1);
String myCode=eText.getText().toString();
Button nextPage= (Button)findViewById(R.id.mainButton1);
if(myCode.equals("Titan")){
nextPage.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v){
startActivity(new Intent(MainActivity.
this,actor.class));
}
});
}
}
}
Move your condition and getText() call in listener
nextPage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
String myCode=eText.getText().toString();
if(myCode.equals("Titan")){
startActivity(new Intent(MainActivity.
this,actor.class));
}
}
}
So, here's what's happening:
You have an EditText field in your app, where the user types their password.
You capture that EditText in your code using EditText eText = ...
You then check to see if eText.equals("Titan");
If it matches Titan, you see the onClick listener.
But, when this code is ran, the EditText is always empty, so you never set the onClick listener!
The fix is fairly straightforward:
nextPage.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
String myCode=eText.getText().toString();
if(myCode.equals("Titan")) {
startActivity(new Intent(MainActivity.this,actor.class));
}
}
});
Now, when the button is clicked:
You capture the value of eText as myCode.
You check if myCode is equal to Titan
If true (ie it matches), you then run startActivity(new Intent(MainActivity.this,actor.class));
You have written class name actor.class starting with a smaller case. Make it starts with uppercase Actor.class. Bellow is the answer to your questions.
Button nextPage = (Button)findViewById(R.id.mainButton1);
nextPage.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v){
String myCode=eText.getText().toString();
if(myCode.equals("Titan"))
{
startActivity(new Intent(MainActivity.
this,Actor.class));
}else{
//password not matching
}
});

click listener is not working

Hi I am new in android learning and I'm practice it. I Want to implement click listener on my button but it is giving me error. even i imported android.view.View.OnClickListener; and other all libraries.
please have look at my code check where is my mistake
Cannot Resolve symbol onClickelistner.
package com.example.nexus.myapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import android.view.View.OnClickListener;
public class MainActivity extends AppCompatActivity {
Button button;
TextView loginresulttext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.loginbutton);
loginresulttext = (TextView) findViewById(R.id.loginresult);
}
button.OnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getApplicationContext(),"Button Is Clicked",Toast.LENGTH_LONG).show();
}
});
}
Try this and put it in onCreate method
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
Combine R2R and Toan Tran answers will give you the best solution:
public class MainActivity extends AppCompatActivity {
Button button;
TextView loginresulttext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.loginbutton);
loginresulttext = (TextView) findViewById(R.id.loginresult);
button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast.makeText(getApplicationContext(),"Button Is Clicked",Toast.LENGTH_LONG).show();
}
});
}
This should work.
Button button = (Button) findViewById(R.id.testButton);
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
// TODO Auto-generated method stub
}
});
Try button click inside Oncreate()
public class MainActivity extends AppCompatActivity {
Button button;
TextView loginresulttext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.loginbutton);
loginresulttext = (TextView) findViewById(R.id.loginresult);
button.setOnClickListener(new OnClickListener(){
public void onClick(View v)
{
Toast.makeText(getApplicationContext(),"Button Is Clicked",Toast.LENGTH_LONG).show();
}
});
}
}

Android TextView and Buttons not working in my app

I am learning Android and trying one simple Android app development, I got one demo code from my lecture and the teacher simply do the following:
There are 2 buttons, 1 textview. When touching button A, it will show "text A" in the textview, while touching button B, it will present "text B" in textview.
I followed the code and rewrote it, but i can't get the correct result when I ran with emulator.
When I touch either button, there's no content in the TextView. But my teacher's reference code works:
import android.view.View;
import android.widget.TextView;
import android.os.Bundle;
import android.app.Activity;
public class ActTwo extends Activity {
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_act_two);
tv = (TextView) this.findViewById(R.id.textView2);
}
public void report(View v) {
if(v.getId() == R.id.button1)
tv.setText(R.string.anrep);
else
tv.setText(R.string.iprep);
}
}
How is report(View v) called? I can't understand how this class is called. Could someone please help me out?
You need to let your button know that, when pressed, report() should be called. This may be done through the android:onClick attribute of your button on your layout's XML:
<Button
android:id="#+id/button1"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="#string/button_text"
android:onClick="report" />
Or by code, attaching an OnClickListener to the button:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_act_two);
button1 = (Button) this.findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
report(v);
}
});
}
Hope it helps.
You should implements the View.OnClickListener, and override that OnClick method. You also need to setOnClickListener on your buttons. So your code should be like:
import android.view.View;
import android.widget.TextView;
import android.os.Bundle;
import android.app.Activity;
public class ActTwo extends Activity implements View.OnClickListener{
private TextView tv;
private Button button1, button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_act_two);
tv = (TextView) this.findViewById(R.id.textView2);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
button2 = (Button) findViewById(R.id.button2);
button2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.button1)
tv.setText(R.string.anrep);
else
tv.setText(R.string.iprep);
}
}
import android.view.View;
import android.widget.TextView;
import android.os.Bundle;
import android.app.Activity;
public class ActTwo extends Activity {
private TextView tv;
private Button button1, button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_act_two);
tv = (TextView) this.findViewById(R.id.textView2);
button1 =(Button)this.findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener(){
public void onClick(View v){
report(v);
}
});
button2 =(Button)this.findViewById(R.id.button2):
button2.setOnClickListener(new OnClickListener(){
public void onClick(View v){
report(v);
}
});
}
public void report(View v) {
if(v.getId() == R.id.button1)
tv.setText(R.string.anrep);
else
tv.setText(R.string.iprep);
}
}

ListView: Null pointer exception

Good day. I'm having some issues with my android project specifically listview. I tried searching for other information here in this site, and implemented some of the answers. However, it is still not working.
The error specifically is
NullPointerException at line 76 at MainActivity
Here is the code of my MainActivity
import java.util.ArrayList;
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;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
final ArrayList<String> studentName = new ArrayList<String>();
ArrayAdapter<String> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView myList = (ListView) findViewById(R.id.listName);
aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, studentName);
myList.setAdapter(aa);
//droid.R.id.list;
//add
Button bAdd = (Button) findViewById(R.id.addstudent);
bAdd.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
startActivity(new Intent("android.intent.action.ADDSTUDENTS"));
}
});
//edit
Button bEdit = (Button) findViewById(R.id.editstudent);
bEdit.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.EDITSTUDENTS"));
}
});
//edit
Button bDelete = (Button) findViewById(R.id.deletestudent);
bDelete.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View x) {
startActivity(new Intent("android.intent.action.DELETESTUDENTS"));
}
});
}
public ArrayList<String> getArray(){
return studentName;
}
public void notifyArray(){
aa.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
and line 76 by the way is
aa.notifyDataSetChanged();
Here is my code for the AddStudents class
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class AddStudents extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.add_student);
Button bAddStudents = (Button) findViewById(R.id.add);
final EditText et = (EditText) findViewById(R.id.student_name);
bAddStudents.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
MainActivity as = new MainActivity();
as.getArray().add(et.getText().toString());
as.notifyArray();
finish();
}
});
Button bBack = (Button) findViewById(R.id.backadd);
bBack.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
finish();
}
});
}
}
and the xml part with the list view is
<ListView
android:id="#+id/listName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1" >
</ListView>
I hope you can help me cause I want to also learn what my mistakes are. I can add other information if you want.
In your AddStudents class, you're calling notifyArray() right after you instantiated MainActivity. MainActivity.onCreate() will not be called just by instantiating it.
Instantiating your MainActivity there is probably not what you want anyway (because that object will be disposed directly after the onClick handler is done).
What you want instead is to access the existing instance of MainActivity. For that, add a reference to the current instance to a static member of your MainActivity class, e.g.
public class MainActivity extends Activity {
public static MainActivity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
activity = this;
}
}
Then in your AddStudent class access it via
MainActivity.activity.notifyArray()
This is not the most beautiful way to solve your issue, but it works as long as you can be sure to only have one MainActivity instance. (If not, you could make the array itself static; or create a Singleton wrapper class for it.)
notifyArray() is being called before onCreate.
Try calling getArray().add(et.getText().toString()); and notifyArray(); inside onResume() of MainActivity and NOT from AddStudentActivity( not recommended!)
So onResume() you would ideally want to add a new student to the list, so in your case, you can retrieve the student name using a common sharable object like a hashtable or somethiing similar, make it a singleton, and use it from anywhere in the applciation
The common class may go something like:
class CommonHashtable{
private static Hashtable<String, Object> commonHashtable = null;
public static getInstance(){
if(commonHashtable == null)
commonHashtable = new Hashtable<String, Object>();
return commonHashtable;
}
on getInstance(), it returns a commonHashtable which can be used to store values temporarily!
so, add this on addbutton click event
Hashtable hash = CommonHashtable.getInstance();
hash.put("NEW_STUDENT_NAME", et.getText().toString());
and add this in you onResume() of MainActivity
Hashtable hash = CommonHashtable.getInstance();
Object studentName = (String) hash.get("NEW_STUDENT_NAME");
if(studentName != null){
notifyArray();
}

Categories

Resources