I get "non-static variable variable cannot be referenced from a static context" warning eventhough I didn't use static expression at Android Studio. I don't understand why. Could you please help?
I've tried to share code but because it's too long I couldn't.
Problem starts after onClick method.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// gameStart = (Button) findViewById(R.id.start);
newRoundButton = (Button) findViewById(R.id.newRound);
hitButton = (Button) findViewById(R.id.hit);
newGameButton = (Button) findViewById(R.id.newGame);
passButton = (Button) findViewById(R.id.pass);
playerC1 = (ImageView) findViewById(R.id.playerC1);
newRoundButton.setOnClickListener(this);
hitButton.setOnClickListener(this);
newGameButton.setOnClickListener(this);
passButton.setOnClickListener(this);
//hitButton.setVisibility(View.INVISIBLE);
//newGameButton.setVisibility(View.INVISIBLE);
// passButton.setVisibility(View.INVISIBLE);
dealer = (TextView) findViewById(R.id.dealer);
player = (TextView) findViewById(R.id.player);
playerTotal = (TextView) findViewById(R.id.playerTotal);
dealerDeckTable = (TextView) findViewById(R.id.dealerDeckTable);
playerDeckTable = (TextView) findViewById(R.id.playerDeckTable);
skor = (TextView) findViewById(R.id.score);
gameMessage = (TextView) findViewById(R.id.gameMessage);
dealerTotal = (TextView) findViewById(R.id.dealerTotal);
playerSkor = (TextView) findViewById(R.id.playerSkor);
dealerSkor = (TextView) findViewById(R.id.dealerSkor);
kontrol = (TextView) findViewById(R.id.kontrol);
playerDeckTable = (TextView) findViewById(R.id.playerDeckTable);
dealerDeckTable = (TextView) findViewById(R.id.dealerDeckTable);
playerC1.setImageDrawable((ContextCompat.getDrawable(getApplicationContext(),R.drawable.nocard)));
}
public void onClick(View v) {
if (v.getId() == newGameButton.getId()) {
gameMessage.setText(Cards.firstStart());
playerSkor.setText(Cards.pskorS);
dealerSkor.setText(Cards.dskorS);
playerTotal.setText(Cards.pValS);
dealerTotal.setText("N/A");
playerDeckTable.setText(Cards.pHand);
dealerDeckTable.setText(Cards.dHand2);
newGameButton.setVisibility(View.INVISIBLE);
kontrol.setText(Cards.kontrolS);
code continues...
Cards class does not contain any static variable and I get that warning lines getting information from Cards class.
I hope details are enough to explain the problem..
The Prolem is, that u call Cards.firstStart() like a static method. You should initialize your Cardobject with Cards cards = new Cards()
Related
I'm creating a simple Android app with 2 Activities. Activity B displays a bunch of data passed from A. When the user press the back button from B I need to clear some variables in order to not duplicate the data shown on B, but both variables I'm erasing on onResume() aren't clearing at all. Here's my code:
public class MainActivity extends AppCompatActivity {
List<Camarera> camareras = new ArrayList<Camarera>();
List<String> resultados = new ArrayList<String>();
int camHabs = 0;
Button boton;
TextView dinero;
TextView camarera1, camarera2, camarera3, camarera4, camarera5;
EditText hora1, hora2, hora3, hora4, hora5;
EditText resta1, resta2, resta3, resta4, resta5;
Switch switch1, switch2, switch3, switch4, switch5;
#Override
public void onResume()
{
super.onResume();
resultados = new ArrayList<>();
camHabs = 0;
Toast.makeText(getApplicationContext(),"Resumiendo", Toast.LENGTH_LONG).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
boton = (Button) findViewById(R.id.Boton);
camHabs = 0;
boton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calcular();
}
});
}
void Calcular(){
dinero = (TextView) findViewById(R.id.Dinero);
camarera1 = (TextView) findViewById(R.id.Camarera1);
camarera2 = (TextView) findViewById(R.id.Camarera2);
camarera3 = (TextView) findViewById(R.id.Camarera3);
camarera4 = (TextView) findViewById(R.id.Camarera4);
camarera5 = (TextView) findViewById(R.id.Camarera5);
hora1 = (EditText) findViewById(R.id.C_Horas1);
hora2 = (EditText) findViewById(R.id.C_Horas2);
hora3 = (EditText) findViewById(R.id.C_Horas3);
hora4 = (EditText) findViewById(R.id.C_Horas4);
hora5 = (EditText) findViewById(R.id.C_Horas5);
resta1 = (EditText) findViewById(R.id.C_Resta1);
resta2 = (EditText) findViewById(R.id.C_Resta2);
resta3 = (EditText) findViewById(R.id.C_Resta3);
resta4 = (EditText) findViewById(R.id.C_Resta4);
resta5 = (EditText) findViewById(R.id.C_Resta5);
switch1 = (Switch) findViewById(R.id.C_Switch1);
switch2 = (Switch) findViewById(R.id.C_Switch2);
switch3 = (Switch) findViewById(R.id.C_Switch3);
switch4 = (Switch) findViewById(R.id.C_Switch4);
switch5 = (Switch) findViewById(R.id.C_Switch5);
List<TextView> nombres = Arrays.asList(camarera1, camarera2, camarera3, camarera4, camarera5);
List<EditText> horas = Arrays.asList(hora1, hora2, hora3, hora4, hora5);
List<EditText> restas = Arrays.asList(resta1, resta2, resta3, resta4, resta5);
List switches = Arrays.asList(switch1, switch2, switch3, switch4, switch5);
int resultado;
int maxHoras = 0;
int Dinero = Integer.parseInt(dinero.getText().toString());
for (int i = 0; i < nombres.size(); i++) {
Camarera cam = new Camarera();
cam.SetNombre(nombres.get(i).getText().toString());
cam.SetHoras(horas.get(i).getText().toString());
maxHoras += cam.GetHoras();
cam.SetResta(restas.get(i).getText().toString());
Switch var = (Switch) switches.get(i);
cam.activa = var.isChecked();
camareras.add(cam);
}
for (int i = 0; i < camareras.size(); i++) {
Camarera cam = camareras.get(i);
if (cam.activa) {
camHabs++;
if (cam.error) {
Toast.makeText(getApplicationContext(),cam.error_S, Toast.LENGTH_LONG).show();
return;
}
resultado = ((cam.GetHoras() * Dinero) / maxHoras) - cam.GetResta();
resultados.add(cam.GetNombre() + " se lleva " + resultado + "€");
}
}
Intent intent = new Intent(MainActivity.this, Tabla.class);
intent.putExtra("lista", (ArrayList<String>) resultados);
intent.putExtra("habs", camHabs);
startActivity(intent);
}
Could you help me please? Been stuck with this the whole day.
Try to equal them to null into on Resume and then after that recreate the empty value as you've already done. Let me know if it works.
From the docs on OnResume:
Be aware that the system calls this method every time your activity comes into the foreground, including when it's created for the first time.
It is even called when you press home button/switch apps, so I don't think it is a good idea to do this here.
Why not just do it before you call your startActivity call:
Intent intent = new Intent(MainActivity.this, Tabla.class);
intent.putExtra("lista", (ArrayList<String>) resultados);
intent.putExtra("habs", camHabs);
//Reset variables here
resultados = new ArrayList<>();
camHabs = 0;
startActivity(intent);
Actually, the error wasn't on those two variables, it was on a third one called "camareras" I wasn't clearing it and because I use it in each cycle it would add again and again to "camHabs".
Thanks anyways!
I have a problem. I do not know how to call a different class. the code is for a button (when you click the button a message appears in random) so i thought it would be better if i placed it in a different class as i have also used arrays.Now i do not know how to call the class.
This is my code.I want to call "Firstin" inside SecondActivity.
public class SecondActivity extends Activity {
private Firstin mFirst = new Firstin ();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
//finds textview
final Text Ftext = (Text) findViewById(R.id.textView2);
#SuppressWarnings("unused")
final Text Stext = (Text) findViewById(R.id.textView3);
//finds button view
Button btnView = (Button) findViewById(R.id.button1);
#SuppressWarnings("unused")
Button btnView2 = (Button) findViewById(R.id.button2);
btnView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String Answer = mFirst.firstAnswer();
Ftext.setTextContent(Answer);
}
});
this is the class I'm trying to call:
package com.example.insultgenerator;
import java.util.Random;
public class Firstin {
public String firstAnswer(){
String [] mResults={
"its cool",
"we cool",
"im cool",
"he cool",
"she cool"
};
// the button was clicked so replace the answer label with answer
String Answer = "" ;
// the two double is a 'empty string
Random RandomGen = new Random();// telling the program to construct a random generator
int RandomNum= RandomGen.nextInt(mResults.length);
Answer = mResults[RandomNum];
return(Answer);
}
}
You should cast to TextView
final TextViewFtext = (TextView) findViewById(R.id.textView2);
#SuppressWarnings("unused")
final TextViewStext = (TextView) findViewById(R.id.textView3);
then use TextView.setText(...) method:
String Answer = mFirst.firstAnswer();
Ftext.setText(new Firstin().firstAnswer());
}
});
then last call the method from the other class with new Firstin().firstAnswer() which creates a instance of the class and executes the method.
I'm trying to get a string value from a listview and put into another view. I've managed to do this successfully for my first listview but it won't seem to work for my third. ( I managed to get it to work but its stopped working now for reasons I cant understand) I am using the exact same method and the information i'm trying to retrieve is being retrieved as I have confirmed while running the problem is its just not getting changed.
Code
public void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.statseditor);
dbHelper = new PlayerStatsDatabase(this);
dbHelper.open();
Bundle extras = getIntent().getExtras();
if(extras !=null){
//String value = extras.getString("Name");
}
//Clean all data
// dbHelper.deleteAllStats();
//Add some data
//dbHelper.insertSomeCountries();
//Generate ListView from SQLite Database
//displayListView();
// list = getListView();
PlayerNameText = extras.getString("Name");
btnSave2 = (Button) findViewById(R.id.btnSaveStats);
btnClear = (Button) findViewById(R.id.btnClearStats);
txtGoalsScored = (EditText) findViewById(R.id.txtGoal);
txtMinutesPlayed = (EditText) findViewById(R.id.txtMinPlayed);
txtSubstituteIn = (EditText) findViewById(R.id.txtSubIn);
txtSubstituteOut = (EditText) findViewById(R.id.txtSubOut);
radioSubIn = (RadioButton) findViewById (R.id.rdoSubIn);
radioSubOut = (RadioButton) findViewById (R.id.rdoSubOut);
playerRating = (RatingBar) findViewById (R.id.ratingBar1);
//playerTitle = (TextView) findViewById (R.id.textTitle);
playerName = (TextView) findViewById (R.id.textView1);
playerName.setText(PlayerNameText);
//playerTitle.setText (PlayerNameText);
checkBox = (CheckBox) findViewById (R.id.checkBox1);
if (checkBox.isChecked()){
checkBox.append("Booked");
}
final CharSequence checkText = checkBox.getText();
//final Context context =
btnSave2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PlayerStatsDatabase db = new PlayerStatsDatabase(getApplicationContext());
db.open();
db.createStats(txtGoalsScored.getText().toString(), txtMinutesPlayed.getText().toString(),txtSubstituteIn.getText().toString(),txtSubstituteOut.getText().toString(), checkText.toString());
db.close();
dipsplayPlayerName();
displayListView();
//Intent intent = new Intent(context, ListItemsActivity.class);
// startActivity(intent);
}
});
}
In this first instance where I use this method playerName actually gets changed to PlayerNameText
But further down when I try to use it again it doesnt work
private void dipsplayPlayerName() {
setContentView (R.layout.statslist);
Bundle extras = getIntent().getExtras();
PlayerNameText = extras.getString("Name");
playerTitle = (TextView) findViewById (R.id.textTitle);
playerTitle.setText (PlayerNameText);
}
Any ideas? The is no LogCat as the app doesnt crash
Put the text data you received into a field and use it instead of getting it from the intent again.
Also, check that displayListView() doesn't change the textView.
I'm trying to get some values from a dialog. I have an activity called Splash that shows a dialog with a form. It displays the form wel but i gives me an error when i try to get that values (nullpointer).
I have the folowing code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
//datos objeto
nombre = (TextView) findViewById(R.id.tv_nombre);
padre = (TextView) findViewById(R.id.tv_nom_padre);
madre = (TextView) findViewById(R.id.tv_nom_madre);
rgSexo = (RadioGroup) findViewById(R.id.rg_sexo);
fecha_nac = (DatePicker) findViewById(R.id.dp_fecha_nac);
rb_m = (RadioButton) findViewById(R.id.rb_masc);
rb_f = (RadioButton) findViewById(R.id.rb_fem);
perfil = new PerfilCRUD(this);
perfil.open();
//first time
if (perfil.primeraVez()){
//muestro el popup
Log.v(TAG, "prim vez");
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.dialog_perfil);
dialog.setTitle("Datos del usuario");
dialog.show();
Button botOk = (Button) dialog.findViewById(R.id.b_ok);
botOk.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
Log.v(TAG, "boton ok");
Log.v(TAG, nombre.getText().toString());
}
});
It gives me the error when i try to get the nombre.getText().toString() value. It happens that with all variables/controls values. It forces to close the application.
Thanks!!
Its because nombre is in your original layout. Either call a TextView in the layout that you inflate in the dialog or create a class level variable String name = ""; then in
if (perfil.primeraVez()){
name = nombre.getText().toString();
then you can use name in your dialog
I'm a beginner in application development. My problem is, that when I run my app and I click on the Calculate button, the program stops. The code:
public class screen1 extends Activity {
private EditText name;
private CheckBox box1;
private Spinner spinner;
private TextView text1, text2, text3, text4, text5, text6;
private Button calcbutton, closebutton;
String strength;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Spinner hubSpinner = (Spinner) findViewById(R.id.myspinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource( this, R.array.military_ranks , android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
hubSpinner.setAdapter(adapter);
name = (EditText)findViewById(R.id.editText1);
strength = name.getText().toString();
box1 = (CheckBox)findViewById(R.id.checkBox1);
text1 = (TextView)findViewById(R.id.textView4);
text2 = (TextView)findViewById(R.id.textView6);
text3 = (TextView)findViewById(R.id.textView8);
text4 = (TextView)findViewById(R.id.textView10);
text5 = (TextView)findViewById(R.id.textView12);
text6 = (TextView)findViewById(R.id.textView14);
final Button calcbutton = (Button) findViewById(R.id.button1);
calcbutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int str = Integer.valueOf(strength);
int rank = spinner.getSelectedItemPosition()+1;
double sebzes;
if(box1.isChecked()){
sebzes = (((rank-1)/20+0.3)*((str/10)+40))*1*(1+1/100);
text1.setText(Double.toString(sebzes));
}
else{
sebzes = (((rank-1)/20+0.3)*((str/10)+40))*1;
text1.setText(Double.toString(sebzes));
}
}
});
final Button closebutton = (Button) findViewById(R.id.button2);
closebutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
}
In the edittext component you should be able to write numbers only. I don't know why it's not working.
The problem are these two lines:
int str = Integer.valueOf(strength);
int rank = spinner.getSelectedItemPosition()+1;
The first won't fail if you use only numbers in your EditText but it would be better to ensure that or at least catch the exception that is thrown when you try to convert a character to a numberical value. Additionally you could also use Integer.valueOf(strength).intValue(); even so it is normally not really necessary.
The real problem is the second line. You declared the variable spinner but you never instantiate it. That's why you will get a NullPointerException there.
On an unrelated note: You also should start your class name with a capital letter to follow the Java naming conventions.
You're not instantiating spinner anywhere, but you're referencing it in the second line of your button click method. Probably a null reference problem.