Button properties won't change - java

So I have an android app (java in Eclipse) and I want to change the text of some buttons on a keyboard through a shift method. I implemented the same code as I did to change a textview text, the same as everyone says to on similar questions, but for some reason it WILL NOT work. For some reason, after testing other button functions, I've determined that there's something it doesn't like about me changing ANY property of the button. Tried cleaning the project, didn't help. Keep getting an invocation exception. Here is relevant code:
public class MainActivity extends Activity {
boolean shift = true;
static Vector<String> answer = new Vector<String>(1, 1);
static int ansLength = 0;
private TextView answerbox;
private Button a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initializeButtons();
setContentView(R.layout.activity_main);
answerbox = (TextView) findViewById(R.id.answerbox);
}
#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;
}
public void initializeButtons() {
a = (Button) findViewById(R.id.a);
}
public void typeKey(View sender) {
Button pressed = (Button) sender;
answer.add(ansLength, (String) pressed.getText());
//answerbox.setText("test string");
ansLength++;
StringBuilder stringBuilder = new StringBuilder();
for (String string : answer) {
stringBuilder.append(string);
}
answerbox.setText(stringBuilder.toString());
}
public void backSpace(View sender) {
answer.remove(ansLength - 1);
ansLength--;
StringBuilder stringBuilder = new StringBuilder();
for (String string : answer) {
stringBuilder.append(string);
}
answerbox.setText(stringBuilder.toString());
}
public void shift(View sender) {
if (shift == true) {
shift = false;
a.setText("l");
}
}
}
XML below:
<Button
android:id="#+id/a"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="A"
android:onClick="typeKey"/>
<Button
android:id="#+id/shift1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="^"
android:textSize="24sp"
android:onClick="shift" />

First, findViewById() in initializeButtons() should be called after setContentView() since there is no layout data in Activity object before setContentView()
Therefore, move the statement as following:
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initializeButtons(); // Move this.
answerbox = (TextView) findViewById(R.id.answerbox);
Second, I'd like to advise you that do not use Vector in Java except in a special purpose. Use ArrayList instead. Vector in Java is slow, and almost deprecated. It is just available because of compatibility issues.
static Vector<String> answer = new Vector<String>(1, 1);
should be replaced to
static ArrayList<String> answer = new ArrayList<String>(1, 1);
If you have sync issues, (I don't think you have this issue now) then use Collections.synchronizedList() method: Why is Java Vector class considered obsolete or deprecated?

Related

Why my app wont open after adding this line in my code : TextView t = findViewById(R.id.wina)"?

This is my codebase for a game but it won't open after adding line 4 if I don't use that line then my app works perfectly fine. and no error is thrown. it builds perfectly fine.
I'm new with android dev so I don't know much about it.
below is XML and java code for the TextView and APP respectively.
<TextView
android:id="#+id/wina"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toTopOf="#+id/board"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
android:text="#string/hello"
android:visibility="invisible"
android:textSize="24sp"
/>
.
public class MainActivity extends AppCompatActivity {
int flag = 1; //1 means red and 0 means yellow
int[] gameState = {-1,-1,-1,-1,-1,-1,-1,-1,-1}; //-1 empty , 0 yellow and 1 red
**TextView tv = findViewById(R.id.wina);**
String win ="";
int[][] winningConditions = {
{0,1,2},
{3,4,5},
{6,7,8},
{0,3,6},
{1,4,7},
{2,5,8},
{0,4,8},
{2,4,6}
};
boolean gameActive = true;
public boolean check(){
for(int[] winningCondition : winningConditions){
if(gameState[winningCondition[0]]==gameState[winningCondition[1]] &&
gameState[winningCondition[1]]==gameState[winningCondition[2]] &&
gameState[winningCondition[0]]!=-1){
return true;
}
}
return false;
}
public void dropToken(View view){
ImageView vi = (ImageView) view;
int tag = Integer.parseInt(vi.getTag().toString());
if(gameState[tag]==-1) {
gameState[tag] = flag;
vi.setY(-1500);
if (flag == 1 && gameActive) {
vi.setImageResource(R.drawable.red);
flag = 0;
}
else if (flag == 0 && gameActive) {
vi.setImageResource(R.drawable.yellow);
flag = 1;
}
vi.animate().translationY(0).setDuration(400);
if(check()){
if(flag==1){
win = "yellow";
}
else{
win = "red";
}
Toast.makeText(this,win, Toast.LENGTH_SHORT).show();
gameActive=false;
}
}
#Override protected void onCreate(Bundle savedInstanceState) {
//normal code } }
You have not drawn your XML file of MainActivity yet and you are calling a method to find your textview before actually drawing your activity. So, first you need to implement onCreate() method of AppCompatActivity and set it's content view using setContentView() and only then you initialize your TextView field.
Refer the below sample and make changed accordingly to your code.
public class MainActivity extends AppCompatActivity {
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = findViewById(R.id.wina);
}
}
Read more about Activity Lifecycle

Why can't I set text to an Android?

``Hi, i have a calculator application and on the screen there are buttons for number and add, multiplication, clean, substruction and division buttons. But when I open and click buttons they couldnt make change on editText. When i write number on keybord, it edited. How can i fix it?
Here is full of my java code
private EditText screen; //textbox screen
private float numberBf; // save screen before pressing button operation
private String operation;
private ButtonClickListener btnClick;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
screen = (EditText) findViewById(editText);
int idList[] = {R.id.button0,R.id.button,R.id.button2,R.id.button3,R.id.button4,
R.id.button5,R.id.button6,R.id.button7,R.id.button8,R.id.button9, R.id.buttonAdd,R.id.buttonMul,
R.id.buttonC, R.id.buttonDiv,R.id.buttonDot,R.id.buttonEq,R.id.buttonSub};
for(int id:idList){
View v = (View) findViewById(id);
v.setOnClickListener(btnClick);
}
}
#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;
}
//new class
private class ButtonClickListener implements View.OnClickListener {
public void onClick(View view){
switch (view.getId()){
case R.id.buttonC: //clear button
screen.setText("0");
numberBf = 0;
operation = "";
break;
//adding function
case R.id.buttonAdd:
mMath("+");
break;
case R.id.buttonSub:
mMath("-");
break;
case R.id.buttonMul:
mMath("*");
break;
case R.id.buttonDiv:
mMath("/");
break;
case R.id.buttonEq:
mResult();
break;
default:
String num = ((Button) view).getText().toString();
getKeyboard(num);
break;
}
}
}
public void mMath(String s){
numberBf = Float.parseFloat(screen.getText().toString()); //save the screen
operation = s; //save operation
screen.setText("0"); //clear screen
}
public void mResult(){
float numberFl = Float.parseFloat(screen.getText().toString());
float result = 0;
if(operation.equals("+"))
result = numberFl + numberBf;
if (operation.equals("-"))
result = numberBf - numberFl;
if(operation.equals("*"))
result = numberFl * numberBf;
if (operation.equals("/"))
result = numberBf / numberFl;
screen.setText(String.valueOf(result));
}
public void getKeyboard(String str){
String scrCurrent = screen.getText().toString();
if (scrCurrent.equals("0"))
scrCurrent = "";
scrCurrent = str;
screen.setText(str);
}
}
and some part of my activity_main xml code, number 9 button and text place is
activity_main :
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/editText"
android:text="0"
android:layout_below="#+id/button0"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginTop="57dp"
android:gravity="right"
android:editable="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="9"
android:id="#+id/button9"
android:layout_below="#+id/button5"
android:layout_toRightOf="#+id/button5"
android:textStyle="bold" />
please help me thank you
screen = (EditText) findViewById(editText);
The parameter editText is not a valid Resource Identifier. In XML you should have
<EditText ...
android:id="#+id/thetextid">
And then in your code you should have
screen = (EditText) findViewById(R.id.thetextid);
This should make it work:
screen = (EditText) findViewById(R.id.editText);
You haven't instantiated the button click listener. Add
btnClick = new ButtonClickListener();
before any of the setOnClickListener(btnClick) calls.

Android Application Closing upon Button Click (on custom registration page)

Need some help debugging my code. I am very new to the Android SDK and am working on learning it. From what I can glean from several posts on SO and other google search results... I formulated this code.
public class MainMenu extends Activity {
private int str = 8, dex = 8, inte = 8, luk = 8, stats = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayShowHomeEnabled(false);
getActionBar().setDisplayShowTitleEnabled(false);
setContentView(R.layout.activity_main_menu);
}
As you can see, I have created a few private variables my app is going to use to store data. In order to interact with these values, I will redraw the TextView each time they are modified. *Feel free to correct me here if this is not an ideal strategy.
public void strup(View view) {
if(stats > 0) {
TextView tv = (TextView)findViewById(R.id.textView4);
TextView st = (TextView)findViewById(R.id.textView18);
str++;
stats--;
tv.setText(str);
st.setText(stats);
} else {
Toast.makeText(this, "Out of stats!", Toast.LENGTH_SHORT).show();
}
I use a button with the following format.
Str [X] [+1]
Where Str [X] is TextView with X a dynamic value.
Also where [+1] is a button with an Onclick function preset by the XML file.
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Str [" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8" />
<TextView
android:id="#+id/textView13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="]" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="strup"
android:text="+1" />
Now for simplicity, I have altered the "android:text="" " lines to reflect their actual values instead of linking to #string/... I don't think this makes of much difference but I wanted to acknowledge it.
So my question is why does my Application crash when I click the "+1" button? All my app is trying to do is to redraw the TextView with a higher value (under str) and a lower value (under stats).
Thanks for any and all help!
You are passing integer value in settext. Either cast integer to string or you can try changing settext like this:
tv.setText(""+str);
st.setText(""+stats);
You tried to create this object:
TextView st = (TextView)findViewById(R.id.textView18);
where is textView18 in the xml?
u can caste using toString method like this:
tv.setText(str.toString());
st.setText(stats.toString());
Try this change the position of your setContentView(R.layout.activity_main_menu);
public class MainMenu extends Activity {
private int str = 8, dex = 8, inte = 8, luk = 8, stats = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
getActionBar().setDisplayShowHomeEnabled(false);
getActionBar().setDisplayShowTitleEnabled(false);
}

How to change textView (digitalClock) color on touch(screen)

I'm making an app that just displays a clock, but I want is so that everytime a user touches the screen it changes the color of the text (from a list of preselected colors in a colors.xml file) but I haven't got a clue where to start. Can someone point me in the right direction?
Here's the main activity:
public class MainActivity extends Activity {
private static final Random RANDOM = new Random();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
Handler handler = new RandomMoveHandler((TextView) findViewById(R.id.digitalClock1));
handler.sendEmptyMessage(0);
}
// Make the handler subclass static because of this: http://stackoverflow.com/a/11408340/111777
private static class RandomMoveHandler extends Handler {
private final WeakReference<TextView> textViewWeakReference;
private RandomMoveHandler(TextView textView) {
this.textViewWeakReference = new WeakReference<TextView>(textView);
}
#Override
public void handleMessage(Message msg) {
TextView textView = textViewWeakReference.get();
if (textView == null) {
Log.i(TAG, "WeakReference is gone so giving up.");
return;
}
int x = RANDOM.nextInt(350 - 100);
int y = RANDOM.nextInt(800 - 100);
Log.i(TAG, String.format("Moving text view to (%d, %d)", x, y));
textView.setX(x);
textView.setY(y);
//change the text position here
this.sendEmptyMessageDelayed(0, 30000);
}
}
private static final String TAG = MainActivity.class.getSimpleName();
}
and here's the layout xml:
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity"
android:background="#color/black" >
<DigitalClock
android:id="#+id/digitalClock1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="DigitalClock"
android:textColor="#color/ics_blue"
android:textSize="28sp" />
I haven't making deal with DigitalClock but I think, at first, you should reference DigitalClock variable, not TextView. And second, to intercept touch event you need to override onTouckEvent method of your activity, it will callback everytime user touches the screen.
You should follow these steps
Use a TimerTask to.continusly show the time
Implement a touchlistener on that clock view
like this
view.setOnTouchListener
Make an array Colors like this
int[] colr={Color.BLACK,Color.BLUE};
and use random index in your touch event andset it as your color of the view

Android App Clicking Button Calls Incorrect OnClick Listener

I uploaded my app yesterday to Google Play and this morning I've wanted to make just a layout tweak as some of the text was overlapping buttons on smaller screens, basically I just want to move the buttons further down the screen. I thought this would be as easy as using eclipse's graphical editor... Nope.
I have no idea why but the small edit I've done to the position of the buttons on my "view_fact" layout has registered the buttons with the wrong OnClick listeners, there's only two buttons on the view and they're using eachothers event listeners and I have no idea why. I didn't touch the event listener code that was working perfectly on the old layout.
Here is my view_fact 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" >
<TextView
android:id="#+id/viewFactTitleText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:text="#string/factTitleText"
android:textSize="22dp"
tools:context=".MainActivity" />
<ImageView
android:id="#+id/randomFactImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/viewFactTitleText"
android:layout_centerHorizontal="true"
android:layout_marginTop="18dp"
android:contentDescription="Fact Image"
android:src="#drawable/canadaflag" />
<TextView
android:id="#+id/factData"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:layout_below="#+id/randomFactImage"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp"
android:text="TextView" />
<Button
android:id="#+id/anotherFactButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/backToHomeButton"
android:layout_alignLeft="#+id/backToHomeButton"
android:layout_alignRight="#+id/backToHomeButton"
android:text="#string/anotherFactButtonText" />
<Button
android:id="#+id/backToHomeButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/factData"
android:layout_alignParentBottom="true"
android:layout_alignRight="#+id/factData"
android:text="#string/backToHomeButtonText" />
</RelativeLayout>
Listener and startup code:
public class MainActivity extends Activity {
/* Declaration of global variables */
private boolean debugMode = true; // Whether debugging is enabled or not
private static String logtag = "CanadianFacts"; // For use as the tag when logging
private TextView factData;
private int totalFacts = 72;
private String[][] facts = new String[totalFacts][5];
private int lastFact = 0;
/* Buttons */
/* Home page */
private Button randomFactButton;
/* View Fact page */
private Button anotherRandomFactButton;
private Button backToHomeButton;
/* About page */
private Button backToHomeFromAboutButton;
/* Image Views */
private ImageView randomFactImage;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/* Home Page Objects */
randomFactButton = (Button)findViewById(R.id.randomFactButton);
randomFactButton.setOnClickListener(randomFactListener); // Register the onClick listener with the implementation above
/* View Fact Page Objects */
/* Build Up Fact Array */
buildFactArray();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_about:
loadAboutPage(); // Call the loadAboutPage method
return true;
}
return false;
}
public void loadAboutPage() {
setContentView(R.layout.about);
/* Set up home page button listener */
backToHomeFromAboutButton = (Button)findViewById(R.id.backToHomeFromAboutButton);
backToHomeFromAboutButton.setOnClickListener(backToHomeListener); // We can reuse the backToHomeListener
}
/* Home Page Listeners */
//Create an anonymous implementation of OnClickListener, this needs to be done for each button, a new listener is created with an onClick method
private OnClickListener randomFactListener = new OnClickListener() {
public void onClick(View v) {
if (debugMode) {
Log.d(logtag,"onClick() called - randomFact button");
Toast.makeText(MainActivity.this, "The random fact button was clicked.", Toast.LENGTH_LONG).show();
}
setContentView(R.layout.view_fact); // Load the view fact page
/* We're now on the View Fact page, so elements on the page are now in our scope, instantiate them */
/* Another Random Fact Button */
anotherRandomFactButton = (Button)findViewById(R.id.anotherFactButton);
anotherRandomFactButton.setOnClickListener(anotherRandomFactListener); // Register the onClick listener with the implementation above
/* Back to Home Button */
backToHomeButton = (Button)findViewById(R.id.backToHomeButton);
backToHomeButton.setOnClickListener(backToHomeListener); // Register the onClick listener with the implementation above
// Get a random fact
String[] fact = getRandomFact();
if (fact[2] == null) { // If this fact doesn't have an image associated with it
fact[2] = getRandomImage();
}
int imageID = getDrawable(MainActivity.this, fact[2]);
/* See if this fact has an image available, if it doesn't select a random generic image */
randomFactImage = (ImageView) findViewById(R.id.randomFactImage);
randomFactImage.setImageResource(imageID);
factData = (TextView) findViewById(R.id.factData);
factData.setText(fact[1]);
if (debugMode) {
Log.d(logtag,"onClick() ended - randomFact button");
}
}
};
/* View Fact Page Listeners */
private OnClickListener anotherRandomFactListener = new OnClickListener() {
public void onClick(View v) {
if (debugMode) {
Log.d(logtag,"onClick() called - anotherRandomFact button");
Toast.makeText(MainActivity.this, "The another random fact button was clicked.", Toast.LENGTH_LONG).show();
}
// Get a random fact
String[] fact = getRandomFact();
if (fact[2] == null) { // If this fact doesn't have an image associated with it
fact[2] = getRandomImage();
}
int imageID = getDrawable(MainActivity.this, fact[2]); // Get the ID of the image
/* See if this fact has an image available, if it doesn't select a random generic image */
randomFactImage = (ImageView) findViewById(R.id.randomFactImage);
randomFactImage.setImageResource(imageID);
factData = (TextView) findViewById(R.id.factData);
factData.setText(fact[1]);
if (debugMode) {
Log.d(logtag,"onClick() ended - anotherRandomFact button");
}
}
};
private OnClickListener backToHomeListener = new OnClickListener() {
public void onClick(View v) {
if (debugMode) {
Log.d(logtag,"onClick() called - backToHome button");
Toast.makeText(MainActivity.this, "The back to home button was clicked.", Toast.LENGTH_LONG).show();
}
// Set content view back to the home page
setContentView(R.layout.main); // Load the home page
/* Reinstantiate home page buttons and listeners */
randomFactButton = (Button)findViewById(R.id.randomFactButton);
randomFactButton.setOnClickListener(randomFactListener); // Register the onClick listener with the implementation above
if (debugMode) {
Log.d(logtag,"onClick() ended - backToHome button");
}
}
};
Thank you.
I've managed to fix this, by moving the buttons around, changing the IDs a few times and then changing them back. And removing all of the align settings and resetting it's position.
A very strange problem, probably due to eclipse's graphical editor.

Categories

Resources