Android String to int crashes my app - android

I am trying to make an app where the user inputs a phone number into a EditText variable NumberBox which is than converted to int from string and used in the method intent.putExtra("address", PhoneNumberint); When I try to do this, the app just crashes, so please let me know what the problem is here. Is the conversion from string to int wrong in some way?
package com.example.module09;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity {
//variables
EditText NumberBox;
Button SMSButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
NumberBox = (EditText) findViewById(R.id.NumberBox);
SMSButton = (Button) findViewById(R.id.SMSButton);
final int PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
//onclick
SMSButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("address", PhoneNumberint);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
}
});
}
#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;
}
}

Just move this :
final int PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
from your onCreate method to the onClick method.
The app crashes because you have placed the above code in your onCreate method. Since at the time of Activity creation the value of EditText is null the String contains null. When null is parsed to Integer it throws an exception.

you try get value on onCreate method that is null, you must get value of that on button click like following code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//
NumberBox = (EditText) findViewById(R.id.NumberBox);
SMSButton = (Button) findViewById(R.id.SMSButton);
//onclick
SMSButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.putExtra("address", PhoneNumberint);
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);
}
});

You can't perform this on onCreate() method
final int PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
At first time your String contains null data because it always be null values for your EditText and that's why you will be always get null pointer because you can't parse null value to int.
So better way it to move that line on Click event of Button.

The app crashes because of NumberFormatException
The problem lies where you are extracting text from EditText before it is being set. If the content of EditText is empty/null string, Integer.parseInt will throw java.lang.NumberFormatException
The culprit is this line:
final int PhoneNumberint = Integer.parseInt(NumberBox.getText().toString());
To fix this, move this line under onClick(). But the App will still crash, if the button is clicked without inputting anything in EditText.
Before parsing the String to Int, write to check if the String is empty/null.
On the lighter side, there is no need of final keyword here.

Related

How do I test the user name in android [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
i finally figured out where to find most of this.
but now i need to know how to test one part of this program for a username.
My goal is if the user doesn't put anything in the program then don't allow anything to continue.
This is a big app. I have like 3 layout files and 3 java files.
Any help would be good if you need me to send the file i can.
package edu.jones.demogamestartarrayadaptor;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
//import android.view.KeyEvent;
import android.view.View;
//import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
//import android.widget.Toast;
public class GameControlMainActivity extends ListActivity
{
//Class-wide variables for data passed/returned
private String userName = "";
//Use an int for gameLevel,naturally...but, this requires
//use of various methods to convert to String and back!
private int gameLevel = 1;
private EditText nameEntryET;
private TextView gameLevelAnnouncerTV;
private TextView gameLevelTV;
Button doneButton;
//This TV prompts user to enter name in the EditText
//Then, it is made invisible
private TextView namePromptTV;
//These two start out invisible and then show the name
private TextView nameSetTV;
private TextView nameEntTV;
//Array of choices for user
static final String[] CHOICES = new String[]
{
"Read directions",
"Play Game",
"Quit"
};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Set up View ids
nameEntryET = (EditText)findViewById(R.id.enter_nameET);
gameLevelAnnouncerTV = (TextView) findViewById(R.id.game_level_announcer_TV);
gameLevelTV = (TextView) findViewById(R.id.game_level_TV);
//Set the game level in the TextView
gameLevelTV.setText(Integer.toString(gameLevel));
namePromptTV = (TextView)findViewById(R.id.name_prompt_tv);
nameSetTV = (TextView)findViewById(R.id.name_set_tv);
nameEntTV = (TextView)findViewById(R.id.name_entered_tv);
//Set Done button listener to get user's name
doneButton = (Button) findViewById(R.id.doneBtn);
setDoneButtonListener();
//Set up ArrayAdaptor for the options
setListAdapter(new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, CHOICES));
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
getListView().setTextFilterEnabled(true);
//Set up the listener for user clicks on the list
setListClickListener();
//this toast is for when it opens
Toast.makeText(this, "yo whats up", Toast.LENGTH_SHORT).show();
}//END onCreate
private void setDoneButtonListener()
{
doneButton.setOnClickListener
(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
//Get user's name when button is clicked
//Call method to set text and hide button
setUserNameAndHideButton();
}
}
);//END setOnClickListener
}//END setDoneButtonListener
//Sets up username in its TextView, and game level Views,
//then hides the other Views & button
private void setUserNameAndHideButton()
{
userName = nameEntryET.getText().toString();
doneButton.setVisibility(View.GONE);
Toast.makeText(this, "Your name has been entered", Toast.LENGTH_SHORT).show();
//After getting the input, hide the EditText
//VISIBLE(0), INVISIBLE(4) or GONE(8)
nameEntryET.setVisibility(View.INVISIBLE);
namePromptTV.setVisibility(View.GONE);
nameEntTV.setText(userName);
nameSetTV.setVisibility(View.VISIBLE);
nameEntTV.setVisibility(View.VISIBLE);
gameLevelAnnouncerTV.setVisibility(View.VISIBLE);
gameLevelTV.setVisibility(View.VISIBLE);
}//END setUserNameAndHideButton
//Set up the listener for the ListView to interpret user clicks
private void setListClickListener()
{
//Set up the click listener for the options
getListView().setOnItemClickListener
(
new OnItemClickListener()
{
//#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
switch(arg2)
{
case 0: launchDirectionsPage();
break;
case 1: startGame();
break;
case 2: finish();
break;
default: break;
}
}
}//END OnItemClickListener
);//END setOnItemClickListener
}//END setListClickListener
//Launch a simple activity to show a scroll view of directions
protected void launchDirectionsPage()
{
//Set up Intent
Intent launchDirections = new Intent(this, DirectionsPageActivity.class);
startActivity(launchDirections);
}//END launchDirectionsPage
//Launch the activity that allows user to input new game value
//Upon return the onActivityResult method is called
protected void startGame()
{
//Set up Intent to launch other activity: PlayGame
Intent launchGame = new Intent(this, PlayGameActivity.class);
//Info added to the Intent's Bundle to pass to PlayGameActivity
launchGame.putExtra("bdl_username", userName);
launchGame.putExtra("bdl_gamelevel", gameLevel);
startActivityForResult(launchGame, 0);
}//END startGame
//This method will be called when the startGame activity terminates
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == 0 && resultCode == RESULT_OK)
{
//Reset the views to possibly updated info returned in the Intent
//First, access the Bundle's values
userName = data.getExtras().getString("bdl_returnUserName");
gameLevel = data.getExtras().getInt("bdl_returnGameLevel");
//Update the user name & game level with values from other activity
nameEntTV.setText(userName);
gameLevelTV.setText(Integer.toString(gameLevel));
}
}//END onActivityResult
#Override
protected void onSaveInstanceState (Bundle outState)
{
super.onSaveInstanceState(outState);
//Add the username and game level to the Bundle
outState.putString("bdl_savedusername", userName);
outState.putInt("bdl_savedgamelevel", gameLevel);
}//END onSaveInstanceState
#Override
public void onRestoreInstanceState (Bundle savedInstanceState)
{
super.onRestoreInstanceState(savedInstanceState);
//Restore the username and game level from the Bundle
userName = savedInstanceState.getString("bdl_savedusername");
gameLevel = savedInstanceState.getInt("bdl_savedgamelevel");
}//END onRestoreInstanceState
}//END GameControlMainActivity
If you are asking to stop if the username is not entered, just do this:
private void setDoneButtonListener()
{
doneButton.setOnClickListener
(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (nameEntryET.getText().toString().equals("")) {
Toast.makeText(this, "Enter a username", Toast.LENGTH_LONG).show();
} else {
//Get user's name when button is clicked
//Call method to set text and hide button
setUserNameAndHideButton();
}
}
}
);//END setOnClickListener
}//END setDoneButtonListener
if nameEntryET does not have a value entered, nameEntryET.getText().toString() will return an empty string.

Android: putExtras and Intents

I am having a problem with passing strings from a fragment to another activity.
I have tried numerous methods of passing them using intents (eg normal extras, bundles) , but the extras are always null in the activity.
I have looked at
http://www.vogella.com/articles/AndroidIntent/ But no change
http://developer.android.com/training/basics/firstapp/starting-activity.html This method of passing the data also doesn't work
Other similar questions on stackoverflow - but these are not quite the same
What I'm trying to do is get the text that was input in the two EditTexts in the fragment, and then pass that text to the activity where the two EditTexts there are filled with the same text. The problem is that nothing appears in the the two EditTexts in the activity. I know that the EditTexts in the fragments are working because a can create a notification using them.
My code: I have removed things I think are unneccessary eg adding the fragment to a navigation drawer layout. Please excuse missing brackets - I have removed a lot of code and some may have been removed accidentally! :-)
This is the fragment where I create an intent:
// Package declaring and importing stuff
public class QuickNoteFragment extends Fragment implements OnClickListener {
// Removed some stuff
EditText body;
EditText title;
Button create;
int counter = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.quicknote, container, false);
body = (EditText) rootView.findViewById(R.id.qn_et_body);
title = (EditText) rootView.findViewById(R.id.qn_et_title);
create.setOnClickListener(this);
// Removed stuff
getActivity().setTitle(noter_activity); // Part of navigation drawer?
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.qn_b_create:
String content_text = body.getText().toString();
String content_title = title.getText().toString();
if (content_title.length() >=1){
Context context = v.getContext();
// This intent does not seem to work
Intent eIntent = new Intent(context, QuickNoteEdit.class);
eIntent.putExtra("eTitle", content_title);
eIntent.putExtra("eText", content_text);
PendingIntent EditPendingIntent = PendingIntent.getActivity(context, 0, eIntent, 0);
// This intent works comletely. This is called when a notification action button is pressed
Intent qnCancel = new Intent();
qnCancel.setAction("com.RiThBo.noter.qnCancelBroadcast");
Bundle extras = new Bundle();
extras.putInt("valueOfCounter", counter);
qnCancel.putExtras(extras);
startBroadcast(qnCancel);
PendingIntent pQnCancel = PendingIntent.getBroadcast(this.getActivity(), 0, qnCancel, 0);
// Creates Notification
} else {
// Do something
}
case R.id.*** // Does something else
}
}
private void startBroadcast(Intent qnCancel) { // This is part of the correctly working intent
// TODO Auto-generated method stub
}
}
This is the activity where I'm trying to get the extras
// Removed package and imports
public class QuickNoteEdit extends Activity implements OnClickListener {
EditText body;
EditText title;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quicknote_edit);
variableConnector(); // This gets the id for all the items in the xml
Intent intent = getIntent();
String gotTitle = intent.getStringExtra("content_title"); // This is where I think it equals null. Because the
String gotBody = intent.getStringExtra("content_text");
title.setText(gotTitle);
body.setText(gotBody);
}
private void variableConnector() {
// TODO Auto-generated method stub
body = (EditText) findViewById(R.id.qne_et_body);
title = (EditText) findViewById(R.id.qne_et_title);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Thank you
You're putting:
eIntent.putExtra("eTitle", content_title);
eIntent.putExtra("eText", content_text);
and when you read them:
String gotTitle = intent.getStringExtra("content_title");
String gotBody = intent.getStringExtra("content_text");
You need to match the keys ... put "eTitle" and read "eTitle", not "*content_title*"!
You're tagging your extras with "eTitle" and "eText" and trying to retrieve them with "content_title" and "content_text".
Switch to
String gotTitle = intent.getStringExtra("eTitle");
String gotBody = intent.getStringExtra("eText");
it should work.

how to hide the context of a text field and show it when click button

how do i hide the context of the text field and show it when i click
the button
i do not want to hide the whole text filed just the context i wrote inside it
and show ot when i click a button
*
this is a small code*
package com.example.nonachan;
import android.R.string;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
public class MainActivity extends Activity {
char a;
char b;
char c;
int i = 0;
char buf;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText t =(EditText)findViewById(R.id.t1);
ImageButton n = (ImageButton)findViewById(R.id.b1);
n.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
a = 'a';
t.setText(t.getText().toString() + a);
// t.setVisibility(View.INVISIBLE);
}
});
ImageButton a = (ImageButton)findViewById(R.id.b2);
a.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
b = 'b' ;
t.setText(t.getText().toString() + b);
// t.setVisibility(View.INVISIBLE);
i++;
}
});
ImageButton m = (ImageButton)findViewById(R.id.b4);
m.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
c = 'c' ;
t.setText(t.getText().toString() + c);
//t.setVisibility(View.INVISIBLE);
i++;
}
});
Button l = (Button)findViewById(R.id.b3);
l.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
// t.setVisibility(View.VISIBLE);
}
});
}
#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;
}
}
Assuming you have misspelled contents as context in your question (looks very likely)
instead of trying to hide the contents of the EditText, just save it to a variable and set the text of the EditText to empty. Then in your button click just set the text back to the contents in your local variable
Eg
String hiddenText = null;
EditText text = (EditText)findViewById(R.id.t1);
ImageButton hide = (ImageButton)findViewById(R.id.b1);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// save and hide
hiddenText = text.getText();
text.setText("");
}
});
ImageButton unhide = (ImageButton)findViewById(R.id.b2);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// unhide the text and 'clear' hiddenText
if (hiddenText != null) {
text.setText(hiddenText);
hiddenText = null;
}
}
});
There are several ways of doing it. It depends how you want to do it. These are just some suggestions off the top of my head, you can even use them all together.
You can put any entered text in a separate string and then if invisible set the TextView to show an empty string, if visible set the TextView to the saved string.
You can use the visibility tag.
You can set the text color to the background color.
You can create/remove the TextView on visible/invisible states.
You can replace the text with symbols for secure inputs if you want (for each character in edittext display an asterisk or something) and then change that back to plain text.
There are a hundred and one ways of doing it, if you search around on previously answered questions you will see several different methods.

Pass value outside of public void onClick

So im sure this is probably a fairly easy question but I am stumped because I am a beginner.
I am looking to pass a value from one class to another, and I have my helper function down and working just fine. If i create an integer outside of my onClick I can pass it no problem. If I create it inside the onClick though it doesn't seem to make it out.
package com.movi.easypar;
//import java.util.logging.Handler;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class EntryScreen extends Activity implements OnClickListener {
Button buttonSetHoles, buttonSetPlayers, buttonLetsGo;
TextView textGameSetup;
public int setHoles; <--- declared here###############################
private String name1 = "Crista";
private String name2 = "Rob";
private String name3 = "Gato";
private String name4 = "Movi";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.entryscreen);
//******************//
//***DEFINE FONTS***//
//******************//
Typeface merge = Typeface.createFromAsset(getAssets(), "merge.otf");
//*****************************************************//
//***CREATES THE UI FOR EACH OF THESE IN JAVA MEMORY***//
//*****************************************************//
buttonSetHoles = (Button)findViewById(R.id.buttonSetHoles);
buttonSetPlayers = (Button)findViewById(R.id.buttonSetPlayers);
buttonLetsGo = (Button)findViewById(R.id.buttonLetsGo);
textGameSetup = (TextView)findViewById(R.id.textGameSetup);
buttonSetHoles.setTypeface(merge);
buttonSetPlayers.setTypeface(merge);
buttonLetsGo.setTypeface(merge);
textGameSetup.setTypeface(merge);
buttonSetHoles.setText("Set Holes");
buttonLetsGo.setText("Lets Go");
buttonSetPlayers.setText("Set Players");
//******************************//
//***DEFINES BUTTON LISTENERS***//
//******************************//
buttonSetHoles.setOnClickListener(this);
buttonSetPlayers.setOnClickListener(this);
buttonLetsGo.setOnClickListener(this);
}
//*************************************************//
//***SETS ON CLICK FUNCTIONALITY FOR ALL BUTTONS***//
//*************************************************//
#Override
public void onClick(View src) {
switch(src.getId()){
case R.id.buttonSetPlayers:
break;
case R.id.buttonSetHoles:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final CharSequence[] items = {"18", "9"};
builder.setTitle("Set Holes");
builder.setItems(items, new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialogInterface, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
if (items[item].equals("9")){
EntryScreen.this.setHoles = 9; <---#### VALUE SET HERE ####
}
else if (items[item].equals("18")){
EntryScreen.this.setHoles = 18;
}
return;
}
});
builder.create().show();
return;
case R.id.buttonLetsGo:
//*********************************//
//***LAUNCHES ACTUAL APPLICATION***//
//*********************************//
TranslateAnimation slide = new TranslateAnimation(0, -500, 0,0 );
slide.setDuration(1000);
slide.setFillAfter(true);
buttonLetsGo.startAnimation(slide);
buttonSetPlayers.startAnimation(slide);
buttonSetHoles.startAnimation(slide);
Intent myIntent = new Intent(src.getContext(), EasyPar.class);
startActivityForResult(myIntent, 0);
break;
}
EntryScreen.this.finish();
}
public String getNames() {
return name1;
}
public void setNames(String playerName1) {
name1 = playerName1;
}
public int getHoles() {
return setHoles; <---- #### THIS DOES NOT SEE VALUE SET IN ONCLICK ####
}
}
This helper does not seem to be able to see the setHoles value that is created onClick.
Any suggestions? Thanks in advance!
It's a scope thing. A variable defined in a function has local scope, and will be destroyed when the function returns. You need a field to hold your value if you wish to retain it.
[EDIT]
Then allow me to elaborate. You can create a field by typing the following line outside a function, inside the class:
[Access][Type][Name];
ex:
class foo{
public int dice;
public void onClick(){
//now the dice's value is saved throught the lifecycle of the Activity
}
}
[EDIT]
I copied your code and ran it. (Modified just a little.)
public class Main extends Activity implements OnClickListener {
Button buttonSetHoles, buttonSetPlayers, buttonLetsGo;
TextView textGameSetup;
public int setHoles; //<--- declared here###############################
private String name1 = "Crista";
private String name2 = "Rob";
private String name3 = "Gato";
private String name4 = "Movi";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//******************//
//***DEFINE FONTS***//
//******************//
Typeface merge = Typeface.createFromAsset(getAssets(), "merge.otf");
//*****************************************************//
//***CREATES THE UI FOR EACH OF THESE IN JAVA MEMORY***//
//*****************************************************//
/*
buttonSetPlayers = (Button)findViewById(R.id.buttonSetPlayers);
buttonLetsGo = (Button)findViewById(R.id.buttonLetsGo);
textGameSetup = (TextView)findViewById(R.id.textGameSetup);
*/
buttonSetHoles = (Button) findViewById(R.id.buttonSetHoles);
/*
buttonSetHoles.setTypeface(merge);
buttonSetPlayers.setTypeface(merge);
buttonLetsGo.setTypeface(merge);
textGameSetup.setTypeface(merge);
buttonSetHoles.setText("Set Holes");
buttonLetsGo.setText("Lets Go");
buttonSetPlayers.setText("Set Players");
*/
//******************************//
//***DEFINES BUTTON LISTENERS***//
//******************************//.
buttonSetHoles.setOnClickListener(this);
/*
buttonSetPlayers.setOnClickListener(this);
buttonLetsGo.setOnClickListener(this);
*/
}
//*************************************************//
//***SETS ON CLICK FUNCTIONALITY FOR ALL BUTTONS***//
//*************************************************//
#Override
public void onClick(View src) {
switch (src.getId()) {
case R.id.buttonSetHoles:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final CharSequence[] items = { "18", "9" };
builder.setTitle("Set Holes");
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int item) {
Toast.makeText(getApplicationContext(), items[item], Toast.LENGTH_SHORT).show();
if (items[item].equals("9")) {
setHoles = 9;// <---#### VALUE SET HERE ####
Toast.makeText(Main.this, "getHoles()=" + getHoles(), Toast.LENGTH_SHORT);
}
else if (items[item].equals("18")) {
setHoles = 18;
Toast.makeText(Main.this, "getHoles()=" + getHoles(), Toast.LENGTH_SHORT);
}
return;
}
});
builder.create().show();
return;
}
//finish();
}
public String getNames() {
return name1;
}
public void setNames(String playerName1) {
name1 = playerName1;
}
public int getHoles() {
return setHoles;
}
}
And it seems to work just fine.
If you declare the variable inside the method, an external method is surely not able to see it, it's not in the same scope, you can still declare it outside and then set a value from inside the onClick() method.
Declare it as public/private variable outside the methods.
are you sure your setHoles is even being set? to 9 or 18? try adding a println(setHoles) in your onclick to ensure that the value is being set properly. Also, you are declaring your setHoles variable outside of onCreate but within the same class as getHoles() and onClick() right?
when you compare Strings always use equal method.
like:
if (items[item].equals( "9")){
}
and i prefer to user Setters and Getters on variables:
setHoles(int value){}
and
int getHoles(){}

setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (SequencerActivity) back.setOnClickListener(this);

I want to display an image on button click, but I have three errors in my code. What's wrong?
class name "SequencerActivity"
The type SequencerActivity must implement the inherited abstract method DialogInterface.OnClickListener.onClick(DialogInterface, int).
next.setOnClickListener(this);
The method setOnClickListener(View.OnClickListener) in the type View is not applicable for the arguments (SequencerActivity).
onClick(View v)
The method onClick(View) of type SequencerActivity must override or implement a supertype method.
Here's the code giving those errors:
public class SequencerActivity extends Activity implements OnClickListener
{
private int imageCounter = 0;
private ImageView imageLoader;
private int[] imageList = {R.drawable.f03, R.drawable.f04, R.drawable.f05, R.drawable.f06};
#Override
public void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.main);//this one is the common parent layout for all image views
super.onCreate(savedInstanceState);
/*requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);*/
//int image1 = R.drawable.image_w_lbl_0;
imageLoader = (ImageView) findViewById(R.id.imageLoader);
//imageLoader.setImageResource(image1);
Button next = (Button) findViewById(R.id.next);
Button back = (Button) findViewById(R.id.back);
next.setOnClickListener(this);
back.setOnClickListener(this);
back.setEnabled(false);
//show the default image
this.loadImage(imageList[imageCounter]);
}
#Override
public void onClick(View v)
{
int imagePath = 0;
// TODO Auto-generated method stub
switch (v.getId())
{
case R.id.next:
Log.i("Tag","tag");
if(imageCounter < imageList.length)
{
imageCounter++;
imagePath = imageList[imageCounter];
if (imageCounter==(imageList.length)-1)
{
{
ImageButton next=(ImageButton)findViewById(R.id.next);
next.setEnabled(false);
}
}
else
{
ImageButton back=(ImageButton)findViewById(R.id.back);
back.setEnabled(true);
}
}
break;
case R.id.back:
if(imageCounter > 0)
{
imageCounter--;
imagePath = imageList[imageCounter];
if (imageCounter==0)
{
ImageButton back=(ImageButton)findViewById(R.id.back);
back.setEnabled(false);
}
else
{
ImageButton next=(ImageButton)findViewById(R.id.next);
next.setEnabled(true);
}
}
break;
}
this.loadImage(imagePath);
}
private void loadImage(int imagePath)
{
imageLoader.setImageResource(imagePath);
}
}
The OnClickListener that you implement is not correct,
try to implement View.OnClickListener and not DialogInterface.OnClickListener.
You can see that in your import
import View.OnClickListener
instead of
import DialogInterface.OnClickListener
you need to import import android.view.View.OnClickListener;
So your code look like
import android.view.View.OnClickListener;
public class MainActivity extends Activity implements OnClickListener{
// Your oncreate() and rest of all code
}
// you should have method as below
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(v.getId() == R.id.editText1) // just for instance
{
.. your onclick handle code
}
}
Still you are not able to resolve the error type import View.OnClickListener; then move the cursor on the View in import View.OnClickListener; It will open up pop-up then choose the Organize imports option.
Use simply import View.OnClickListener; at the top.
The OnClickListener you're implementing is the wrong one. It says it's DialogInterface.OnClickListener, while you probably want View.OnClickListener. You can correct that in the corresponding import statement.
Just do only One thing. Use "import android.view.View.OnClickListener" statement at the top of the program.
Do one thing
remove import android.content.DialogInterface.OnClickListener;
and import
android.View.View.OnClickListener
this will solve the problem
Happy Coding
Implement View.view.onClickListener

Categories

Resources