I'm in the very early stages of developing this android app, and I'm trying to setText to buttons from within a method. Doing it not in a method is fine, but I want to call the method over and over. However when I try to create the method to do this, I get a "Non-static method findViewById(int) cannot be referenced from a static context" error.
eg: Button button = (Button) findViewById(R.id.button);
button.setText(options[0]);
The findViewById will be red highlighted
package com.example.lp1;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private Button button;
private Button button2;
private Button button3;
private Button button4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
int score = 0;
int count = 3;
static int getQuestion(){
ArrayList set = addingThree();
final int a = (int) set.get(0);
final int b = (int) set.get(1);
final int c = (int) set.get(2);
final int d = (int) set.get(3);
final int ans = (int) set.get(4);
String qText = (String) set.get(5);
String[] options = new String[] {Integer.toString(a),
Integer.toString(b),Integer.toString(c),Integer.toString(d)};
Button button = (Button) findViewById(R.id.button);
button.setText(options[0]);
Button button2 = (Button) findViewById(R.id.button2);
button2.setText(options[1]);
Button button3 = (Button) findViewById(R.id.button3);
button3.setText(options[2]);
Button button4 = (Button) findViewById(R.id.button4);
button4.setText(options[3]);
TextView textView = (TextView)findViewById(R.id.textView);
textView.setText(qText);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
}
static ArrayList addingThree(){
Random rand = new Random();
int numa = rand.nextInt(99);
int numb = rand.nextInt(99);
int numc = rand.nextInt(99);
int ans = numa + numb + numc;
int fake1 = rand.nextInt(200) + 50;
int fake2 = rand.nextInt(200) +50;
int fake3 = rand.nextInt(200) +50;
int[ ] options = {fake1, fake2, fake3, ans};
String stringQuestion = ("What is the sum of " + numa + ", " + numb + ",
and " + numc + "? ");
Arrays.sort(options);
ArrayList parcel = new ArrayList();
parcel.add(options[0]);
parcel.add(options[1]);
parcel.add(options[2]);
parcel.add(options[3]);
parcel.add(ans);
parcel.add(stringQuestion);
return parcel;
}
}
Remove the
static
from your functions.
Also remove the functions from the onCreate callback, they don't belong there.
When you're invoking the functions in onCreate, the functions/methods cannot be static
If you want to use findViewById() in static method then make your rootview Global variable
Related
i tried to make my first converter in android studio with java but 2 functions setText and getText are not working
package com.example.unitconvertor;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity<editTextTextPersonName> extends AppCompatActivity {
private Button button;
private editTextTextPersonName editTextTextPersonName;
private View editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "value saved", Toast.LENGTH_SHORT).show();
String s = editText.getText().toString();
int inch = Integer.parseInt(s);
double cm = 2.54 * inch;
editText.setText( "the value is" + cm);
}
});
}
}
i hope that i am clear
thankyou
Try this-
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
editText = findViewById(R.id.your_id);//ADD YOUR EDIT TEXT ID HERE
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(MainActivity.this, "value saved", Toast.LENGTH_SHORT).show();
String s = editText.getText().toString();
int inch = Integer.parseInt(s);
double cm = 2.54 * inch;
editText.setText( "the value is" + cm);
}
});
}
}
The error is that your "edittext" is declared as view, correct it like this : private EditText edittext;
then, retrieve it by id like this in your onCreate method edittext = findViewById(R.id.your_id);
this code work very well but now when question is CAR button1 = A button2 = R button3 = C when I click button3 button1 = INVISIBLE edit text = A and when I click button2 edit text = A I want when click on button edit text get text from button and check text in edit text
requires: edit text get char form button, add this code to function , remove last index from array
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
LinearLayout linearlayout;
Button button;
EditText txt;
String Array[]= {"car","blue","red","fox"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearlayout = findViewById(R.id.linearlayout);
txt = findViewById(R.id.txt);
int random = (int) (Math.random() * Array.clone().length);
StringBuilder word = new StringBuilder(Array[random]);
for (int i = 0; i < Array[random].length(); i++) {
char id = 'b';
button = new Button(this);
button.setId(id + i);
linearlayout.addView(button);
int randIndex = new Random().nextInt(word.length());
button.setText("" + word.charAt(randIndex));
word.deleteCharAt(randIndex);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
button.setVisibility(View.INVISIBLE);
txt.setText(txt.getText().toString() + button.getText());
}
});
}
}
}
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
LinearLayout linearlayout;
//Button button; //TODO: is local var!
EditText txt; //Global var
String Array[]= {"car","blue","red","fox"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearlayout = findViewById(R.id.linearlayout);
txt = findViewById(R.id.txt);
int random = (int) (Math.random() * Array.clone().length);
StringBuilder word = new StringBuilder(Array[random]);
for (int i = 0; i < Array[random].length(); i++) {
char id = 'b';
final Button button = new Button(this); //local var
button.setId(id + i);
linearlayout.addView(button);
int randIndex = new Random().nextInt(word.length());
button.setText("" + word.charAt(randIndex));
word.deleteCharAt(randIndex);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//the problem was here (var button)
button.setVisibility(View.INVISIBLE);
txt.setText(txt.getText().toString() + button.getText());
}
});
}
}
}
Not sure of the questions, but the one thing I did find to be an issue with the code.
txt.setText(txt.getText().toString() + button.getText());
The bolded part doesn't returns a char sequence. Should be the same thing as the edit text.
button.getText().toString();
I'm basically a beginner android dev and am struggling to remove items from the linkedList i am using. The function i can't get to work is "deleteLast()", any help wold be appreciated. I am also probably quite a bit of fixing that could be done but the main issue is the as mentioned problem.
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
private EditText problemView;
private String problem;
private TextView answerView;
int cursorPosition = 0;
List<String> operationsList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//initialising views
problemView = (EditText) findViewById(R.id.problemView);
answerView = (TextView) findViewById(R.id.answerView);
//prevents an underline appearing in the editText
problemView.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS|InputType.TYPE_NULL);
//initialise the the linkedList for the data structure
operationsList = new LinkedList<>();
problem = "";
//create numerical buttons
Button button0 = (Button) findViewById(R.id.button0);
Button button1 = (Button) findViewById(R.id.button1);
Button button2 = (Button) findViewById(R.id.button2);
Button button3 = (Button) findViewById(R.id.button3);
Button button4 = (Button) findViewById(R.id.button4);
Button button5 = (Button) findViewById(R.id.button5);
Button button6 = (Button) findViewById(R.id.button6);
Button button7 = (Button) findViewById(R.id.button7);
Button button8 = (Button) findViewById(R.id.button8);
Button button9 = (Button) findViewById(R.id.button9);
//create symbolic buttons
Button buttonDivide = (Button) findViewById(R.id.buttonDivide);
Button buttonMultiply = (Button) findViewById(R.id.buttonMultiply);
Button buttonAddition = (Button) findViewById(R.id.buttonAddition);
Button buttonSubtract = (Button) findViewById(R.id.buttonSubtract);
Button buttonPoint = (Button) findViewById(R.id.buttonPoint);
Button buttonScientificNotation = (Button) findViewById(R.id.buttonScientificNotation);
Button buttonAnswer = (Button) findViewById(R.id.buttonAnswer);
//create non-displaying buttons
Button buttonClearAll = (Button) findViewById(R.id.buttonClearAll);
Button buttonDelete = (Button) findViewById(R.id.buttonDelete);
Button buttonEquals = (Button) findViewById(R.id.buttonEquals);
//onClickListener for showable buttons, numbers, signs etc.
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
Button b = (Button) view;
String value = b.getText().toString();
operationsList.add(problemView.getSelectionStart(), value);
// problem += b.getText().toString();
cursorPosition = problemView.getSelectionStart() + 1;
displayArray();
}
};
// //onClickListener for scientific notation button since need to advance cursor more
// View.OnClickListener listenerScientific = new View.OnClickListener() {
// #Override
// public void onClick(View view) {
// Button b = (Button) view;
// String value = b.getText().toString();
//
// operationsList.add(problemView.getSelectionStart(), value);
//// problem += b.getText().toString();
// cursorPosition = problemView.getSelectionStart() + 1;
// displayArray();
// }
// };
button0.setOnClickListener(listener);
button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
button3.setOnClickListener(listener);
button4.setOnClickListener(listener);
button5.setOnClickListener(listener);
button6.setOnClickListener(listener);
button7.setOnClickListener(listener);
button8.setOnClickListener(listener);
button9.setOnClickListener(listener);
buttonDivide.setOnClickListener(listener);
buttonMultiply.setOnClickListener(listener);
buttonAddition.setOnClickListener(listener);
buttonSubtract.setOnClickListener(listener);
buttonPoint.setOnClickListener(listener);
buttonScientificNotation.setOnClickListener(listener);
buttonAnswer.setOnClickListener(listener);
View.OnClickListener nonListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
if (view.getId() == R.id.buttonClearAll){
clearAll();
displayArray();
}
if (view.getId() == R.id.buttonDelete){
deleteLast();
}
if (view.getId() == R.id.buttonEquals){
}
}
};
buttonClearAll.setOnClickListener(nonListener);
buttonDelete.setOnClickListener(nonListener);
buttonEquals.setOnClickListener(nonListener);
}
public void displayArray(){
Iterator<String> iterator = operationsList.listIterator();
String temp = "";
while (iterator.hasNext()){
temp += iterator.next();
}
problemView.setText(temp);
problemView.setSelection(cursorPosition);
}
// public boolean delete(){
// stringProblemArray[spaceUsed-1] = null;
// spaceUsed -= 1;
// problemView.setSelection(problemView.getSelectionStart() - 1);
// return true;
// }
//
public void clearAll(){
operationsList.clear();
cursorPosition = 0;
}
public void deleteLast(){
Iterator<String> iterator = operationsList.listIterator();
int index = 0;
while (iterator.hasNext()){
if (index == cursorPosition-1){
iterator.remove();
}else {
iterator.next();
}
}
displayArray();
// if (iterator.hasNext()){
// for (int i =0; i == cursorPosition; i++){
// iterator.next();
// }
// iterator.remove();
// }
// for(Iterator<String> iter = operationsList.iterator(); iter.hasNext();) {
// String data = iter.next();
// if ( == rec1) {
// iter.remove();
// }
// }
}
}
LinkedList already has removeLast() method, no need to write yours, just write
operationsList.removeLast()
that`s all.
Also if you dont want to cast your List to LinkedList (even if you are actually using LinkedList) you can delete last element using index
operationsList.remove(operationsList.size()-1);
It gives me a error cannot resolve symbol sharedpreferences, I'm trying to add a high score for every time the user take the quiz it records the high score of the quiz. I dont know what happen. Please help me with this one and I'll help you with ur reputation.
package com.example.quiz;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;
public class CS_Assembly_Easy extends Activity{
TextView topscore;
public static final String mypreference = "mypref";
public static final String Topscore = "topKey";
ArrayList<Question> quesList;
ArrayList<Question> toSelectFrom; // <--- HERE
int score = 0;
int qid = 0;
int lives = 5;
int round = 1;
int timer;
Question currentQ;
TextView txtQuestion, times, scored, livess, rounds;
Button button1, button2, button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cs_assembly_easy);
CS_Assembly_QuizHelper db = new CS_Assembly_QuizHelper(this); // my question bank class
quesList = db.getAllQuestions();
toSelectFrom = new ArrayList<Question>(); // <--- HERE
toSelectFrom.addAll(quesList); // <--- HERE
Random random = new Random();// this will fetch all quetonall questions
currentQ = toSelectFrom.get( random.nextInt(toSelectFrom.size())); // the current question <-- edited here too.
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <--- HERE
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
// the textview in which the question will be displayed
// the three buttons,
// the idea is to set the text of three buttons with the options from question bank
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
// the textview in which will be displayed
scored = (TextView) findViewById(R.id.score);
// the timer
times = (TextView) findViewById(R.id.timers);
rounds = (TextView) findViewById(R.id.round);
// method which will set the things up for our game
setQuestionView();
times.setText("00:02:00");
// A timer of 60 seconds to play for, with an interval of 1 second (1000 milliseconds)
CounterClass timer = new CounterClass(60000, 1000);
timer.start();
// button click listeners
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// passing the button text to other method
// to check whether the anser is correct or not
// same for all three buttons
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
}
});
topscore = (TextView) findViewById(R.id.Topscore);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(topscore) > score) {
topscore.setText(sharedpreferences.getString(topscore, ""));
}
}
public void Save(View view) {
String n = topscore.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Topscore, n);
editor.commit();
}
public void clear(View view) {
topscore = (TextView) findViewById(R.id.Topscore);
topscore.setText("");
}
public void Get(View view) {
topscore = (TextView) findViewById(R.id.Topscore);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(topscore)) {
topscore.setText(sharedpreferences.getString(topscore, ""));
}
}
#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 getAnswer(String AnswerString) {
if (currentQ.getANSWER().equals(AnswerString)) {
// if conditions matches increase the int (score) by 1
// and set the text of the score view
score++;
scored.setText(" Score : " + score);
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.correct,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("CORRECT");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
} else if(lives > -10){
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.wrong,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("WRONG");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
else {
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
{
}
if (qid < 10) {
// if questions are not over then do this
Random random = new Random();
currentQ = toSelectFrom.get(random.nextInt(toSelectFrom.size())); // <<--- HERE
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <<--- AND HERE
setQuestionView();
round++;
rounds.setText(" Question:" + round + "/10");
} else {
// if over do this
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
times.setText("Time is up");
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put all things together
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
qid++;
}
#Override
public void onBackPressed() {
return;
}
}
sharedpreferences is not defined in your CS_Assembly_Easy class.
Try changing your code to this:
SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
There probably is a really simple answer to this. My goal is to divide the the inputed information x and y and put that into z.
Here is my code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public int x = Integer.parseInt("");
public int y = Integer.parseInt("");
public int z = (y/x);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Button
Button btn = (Button) findViewById(R.id.button);
//EditText
EditText nop = (EditText) findViewById(R.id.editText);
EditText cob = (EditText) findViewById(R.id.editText2);
x = Integer.parseInt(nop);
y = Integer.parseInt(cob);
final TextView tv = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tv.setText(z);
}
});
}
}
Declare z inside your onclick function. Or assign it a value inside your function.
Also nop and cob are editText's get the data in it, use getText().
Because Integer.parseInt() accepts only a String but not an editText, so you must use getText() to get the String value in it.
x = Integer.parseInt(nop.getText().toString());
y = Integer.parseInt(cob.getText().toString());
final TextView tv = (TextView) findViewById(R.id.textView);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int z = x / y;
tv.setText(z);
}
});
Also z is declared globally and assigned nothing. But it needs to be assigned a value when ever you click the button, so that your editText changes every time you click the button.
Convert first as a string from Edittext then make it as Integer.
String Val1 = nop.getText().toString();
String Val2 =cob.getText().toString();
x = Integer.parseInt(val1);
y = Integer.parseInt(val2);