I am programming a small game app in with every player gets to choose a drawable which is then set for the following activity which is the small game.
This is my code so far:
public class Nameeingabespieler2 extends AppCompatActivity {
public static final String EXTRA_NAME1 = "com.example.die_trinkspielapp.EXTRA_NAME1";
public static final String EXTRA_NAME2 = "com.example.die_trinkspielapp.EXTRA_NAME2";
public static final String Dinonametest1 = "com.example.die_trinkspielapp.DinoSpieler1";
private TextInputLayout namespieler1;
private TextInputLayout namespieler2;
private ArrayList<DinoWahl> mDinoWahl;
private DinoAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nameeingabespieler2);
namespieler1 = findViewById(R.id.Spieler_1_input);
namespieler2 = findViewById(R.id.Spieler_2_input);
final TextView testtest = (TextView) findViewById(R.id.textView3);
initList();
final Spinner dinospinner = findViewById(R.id.spinner);
Spinner dinospinner2 = findViewById(R.id.spinner2);
mAdapter = new DinoAdapter(this, mDinoWahl);
dinospinner.setAdapter(mAdapter);
dinospinner2.setAdapter(mAdapter);
dinospinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
DinoWahl clickedItem = (DinoWahl) adapterView.getItemAtPosition(i);
String DinoName = clickedItem.getmDinoName();
Toast.makeText(Nameeingabespieler2.this,DinoName + " ausgewählt", Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
dinospinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
DinoWahl clickedItem = (DinoWahl) adapterView.getItemAtPosition(i);
String DinoName2 = clickedItem.getmDinoName();
Toast.makeText(Nameeingabespieler2.this,DinoName2 + " ausgewählt", Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void initList(){
mDinoWahl = new ArrayList<>();
mDinoWahl.add(new DinoWahl("Brutus",R.drawable.alkdino));
mDinoWahl.add(new DinoWahl("Skitty",R.drawable.coolerdino));
mDinoWahl.add(new DinoWahl("Pharmi",R.drawable.drogendino));
mDinoWahl.add(new DinoWahl("Luise",R.drawable.frauendino));
mDinoWahl.add(new DinoWahl("Rex",R.drawable.koenigsdino));
mDinoWahl.add(new DinoWahl("Cookie",R.drawable.kochdino));
mDinoWahl.add(new DinoWahl("Divi",R.drawable.magierdino));
mDinoWahl.add(new DinoWahl("Fumu",R.drawable.shishadino));
mDinoWahl.add(new DinoWahl("Dr. Saurum",R.drawable.streberdino));
}
private boolean wertspieler1() {
String usernameInput = namespieler1.getEditText().getText().toString().trim();
if (usernameInput.isEmpty()) {
namespieler1.setError("Spieler bitte eintragen");
return false;
} else if (usernameInput.length() > 15) {
namespieler1.setError("Name zu lang");
return false;
} else {
namespieler1.setError(null);
return true;
}
}
private boolean wertspieler2() {
String usernameInput = namespieler2.getEditText().getText().toString().trim();
if (usernameInput.isEmpty()) {
namespieler2.setError("Spieler bitte eintragen");
return false;
} else if (usernameInput.length() > 15) {
namespieler2.setError("Name zu lang");
return false;
} else {
namespieler2.setError(null);
return true;
}
}
public void starteaktivity(View view) {
if (!wertspieler1() | !wertspieler2()) {
return;
}
EditText editText1 = (EditText) findViewById(R.id.spieler1id);
String name1 = editText1.getText().toString();
EditText editText2 = (EditText) findViewById(R.id.Spieler2id);
String name2 = editText2.getText().toString();
if(name1.equals(name2)) {
Toast.makeText(Nameeingabespieler2.this, "bitte unterschiedliche Namen eingeben",Toast.LENGTH_LONG).show();
} else {
Intent intent = new Intent(this, Trinkspiel2spieler.class);
intent.putExtra(EXTRA_NAME1, name1);
intent.putExtra(EXTRA_NAME2, name2);
startActivity(intent);
}
}
}
This is my code so far and the most relevant Part is this one.
initList();
final Spinner dinospinner = findViewById(R.id.spinner);
Spinner dinospinner2 = findViewById(R.id.spinner2);
mAdapter = new DinoAdapter(this, mDinoWahl);
dinospinner.setAdapter(mAdapter);
dinospinner2.setAdapter(mAdapter);
dinospinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
DinoWahl clickedItem = (DinoWahl) adapterView.getItemAtPosition(i);
String DinoName = clickedItem.getmDinoName();
Toast.makeText(Nameeingabespieler2.this,DinoName + " ausgewählt", Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
dinospinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
DinoWahl clickedItem = (DinoWahl) adapterView.getItemAtPosition(i);
String DinoName2 = clickedItem.getmDinoName();
Toast.makeText(Nameeingabespieler2.this,DinoName2 + " ausgewählt", Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
I don't get the choosen drawable to transfer and I really need your help.
EDIT
This is now my updated code
I have different classes
Nameeingabespieler2 (Class where I want the spinner type to be selceted and transfered to Trinkspiel2spieler.java)
Trinkspiel2spieler (this is the class where the Value should go and set the drawable for each player choosen in Nameeingabespieler2)
DinoWahl (for the Spinner)
DinoAdapter (adapter for the Spinner)
My Problem Now is, that I just wont get the Value transfered, even if I type(line: 162) everything as you said.
If I add (line 26 & 27) these Spinner declarations, they wont be used and if I remove (line: 41 & 42) then the app crashes.
But even with this version now, the next Activity (Trinkspiel2spieler) won't open.
I really don't know what to do now.
I am really sorry to bother you this much but I would be really really thankfull if you can help me.
public class Nameeingabespieler2 extends AppCompatActivity {
public static final String EXTRA_NAME1 = "com.example.die_trinkspielapp.EXTRA_NAME1";
public static final String EXTRA_NAME2 = "com.example.die_trinkspielapp.EXTRA_NAME2";
public static final String EXTRA_DINO1 = "com.example.die_trinkspielapp.DinoSpieler1";
public static final String Dinonametest2 = "com.example.die_trinkspielapp.DinoSpieler2";
private TextInputLayout namespieler1;
private TextInputLayout namespieler2;
private Spinner dinospinner;
private Spinner dinospinner2;
private ArrayList<DinoWahl> mDinoWahl;
private DinoAdapter mAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nameeingabespieler2);
namespieler1 = findViewById(R.id.Spieler_1_input);
namespieler2 = findViewById(R.id.Spieler_2_input);
Spinner dinospinner = findViewById(R.id.spinner);
Spinner dinospinner2 = findViewById(R.id.spinner2);
initList();
mAdapter = new DinoAdapter(this, mDinoWahl);
dinospinner.setAdapter(mAdapter);
dinospinner2.setAdapter(mAdapter);
dinospinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
DinoWahl clickedItem = (DinoWahl) adapterView.getItemAtPosition(i);
String DinoName = clickedItem.getmDinoName();
Toast.makeText(Nameeingabespieler2.this,DinoName + " ausgewählt", Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
dinospinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Context ctx = view.getContext();
DinoWahl clickedItem = (DinoWahl) adapterView.getItemAtPosition(i);
String DinoName2 = clickedItem.getmDinoName();
Toast.makeText(Nameeingabespieler2.this,DinoName2 + " ausgewählt", Toast.LENGTH_SHORT).show();
Intent intent = new Intent();
intent.setClass(ctx, Constants.class);
intent.putExtra(Dinonametest2, DinoName2);
}
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
private void initList(){
mDinoWahl = new ArrayList<>();
mDinoWahl.add(new DinoWahl("Brutus",R.drawable.alkdino));
mDinoWahl.add(new DinoWahl("Skitty",R.drawable.coolerdino));
mDinoWahl.add(new DinoWahl("Pharmi",R.drawable.drogendino));
mDinoWahl.add(new DinoWahl("Luise",R.drawable.frauendino));
mDinoWahl.add(new DinoWahl("Rex",R.drawable.koenigsdino));
mDinoWahl.add(new DinoWahl("Cookie",R.drawable.kochdino));
mDinoWahl.add(new DinoWahl("Divi",R.drawable.magierdino));
mDinoWahl.add(new DinoWahl("Fumu",R.drawable.shishadino));
mDinoWahl.add(new DinoWahl("Dr. Saurum",R.drawable.streberdino));
}
private boolean wertspieler1() {
String usernameInput = namespieler1.getEditText().getText().toString().trim();
if (usernameInput.isEmpty()) {
namespieler1.setError("Spieler bitte eintragen");
return false;
} else if (usernameInput.length() > 15) {
namespieler1.setError("Name zu lang");
return false;
} else {
namespieler1.setError(null);
return true;
}
}
private boolean wertspieler2() {
String usernameInput = namespieler2.getEditText().getText().toString().trim();
if (usernameInput.isEmpty()) {
namespieler2.setError("Spieler bitte eintragen");
return false;
} else if (usernameInput.length() > 15) {
namespieler2.setError("Name zu lang");
return false;
} else {
namespieler2.setError(null);
return true;
}
}
public void starteaktivity(View view) {
if (!wertspieler1() | !wertspieler2()) {
return;
}
EditText editText1 = (EditText) findViewById(R.id.spieler1id);
String name1 = editText1.getText().toString();
EditText editText2 = (EditText) findViewById(R.id.Spieler2id);
String name2 = editText2.getText().toString();
if(name1.equals(name2)) {
Toast.makeText(Nameeingabespieler2.this, "bitte unterschiedliche Namen eingeben",Toast.LENGTH_LONG).show();
}
else{
Intent intent = new Intent(this, Trinkspiel2spieler.class);
intent.putExtra(EXTRA_NAME1, name1);
intent.putExtra(EXTRA_NAME2, name2);
intent.putExtra(EXTRA_DINO1, ((DinoWahl) dinospinner.getSelectedItem()).getmDinoName());
startActivity(intent);
}
}
}
Trinkspiel2spieler (not finished yet)
public class Trinkspiel2spieler extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trinkspiel2spieler);
Button testnamentest = (Button) findViewById(R.id.namenbuttonid);
testnamentest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startetest();
}
});
}
public void startetest() {
//namen einlesen
Intent intent = getIntent();
String nametextstring1 = intent.getStringExtra(Constants.EXTRA_NAME1);
String nametextstring2 = intent.getStringExtra(Constants.EXTRA_NAME2);
String Dino_uerbertragung1 = intent.getStringExtra(Constants.Dinonametest1);
String Dino_uerbertragung2 = intent.getStringExtra(Constants.Dinonametest2);
String Namen[] = {nametextstring1,nametextstring2};
//TextViews deklarieren
TextView Textview1 = (TextView) findViewById(R.id.nameanzeige1);
TextView Textview2 = (TextView) findViewById(R.id.nameanzeige2);
ImageView Dinoimage = (ImageView) findViewById(R.id.imageView2);
//TextView Textview3 = (TextView) findViewById(R.id.nameanzeige3);
Random random = new Random();
int num = random.nextInt(Namen.length);
Textview1.setText(Namen[num]);
if (Namen[num] == nametextstring1){
if (Dino_uerbertragung1 == "Cookie")
Dinoimage.setImageResource(R.drawable.kochdino);
}
else {
Dinoimage.setImageResource(R.drawable.coolerdinomrk2klein);
}
Resources resources = getResources();
String[] Trinkspielfragen = resources.getStringArray(R.array.Trinkspiel);
Random random1 = new Random();
int num2 = random1.nextInt(Trinkspielfragen.length);
Textview2.setText(Trinkspielfragen[num2]);
}
}
DinoWahl
public class DinoWahl {
private String mDinoName;
private int mDinoWahl;
public DinoWahl(String Dinoname,int dinoBild) {
mDinoName = Dinoname;
mDinoWahl = dinoBild;
}
public String getmDinoName() {
return mDinoName;
}
public int getDinoWahl(){
return mDinoWahl;
}
}
DinoAdapter
public class DinoAdapter extends ArrayAdapter <DinoWahl>{
public DinoAdapter(Context context, ArrayList<DinoWahl> DinoListe) {
super(context, 0, DinoListe);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return initView(position, convertView, parent);
}
#Override
public View getDropDownView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
return initView(position, convertView, parent);
}
private View initView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
convertView = LayoutInflater.from(getContext()).inflate(
R.layout.dino_spinner, parent, false
);
}
ImageView imageViewDino = convertView.findViewById(R.id.alkoholdino);
TextView textViewName = convertView.findViewById(R.id.Dinoname);
DinoWahl curentItem = getItem(position);
if (curentItem != null) {
imageViewDino.setImageResource(curentItem.getDinoWahl());
textViewName.setText(curentItem.getmDinoName());
}
return convertView;
}
}
Constants
package com.example.die_trinkspielapp;
public class Constants {
public static final String EXTRA_NAME1 = "com.example.die_trinkspielapp.EXTRA_NAME1";
public static final String EXTRA_NAME2 = "com.example.die_trinkspielapp.EXTRA_NAME2";
public static final String EXTRA_NAME3 = "com.example.die_trinkspielapp.EXTRA_NAME3";
public static final String EXTRA_NAME4 = "com.example.die_trinkspielapp.EXTRA_NAME4";
public static final String EXTRA_NAME5 = "com.example.die_trinkspielapp.EXTRA_NAME5";
public static final String EXTRA_NAME6 = "com.example.die_trinkspielapp.EXTRA_NAME6";
public static final String EXTRA_NAME7 = "com.example.die_trinkspielapp.EXTRA_NAME7";
public static final String EXTRA_NAME8 = "com.example.die_trinkspielapp.EXTRA_NAME8";
public static final String EXTRA_NAME9 = "com.example.die_trinkspielapp.EXTRA_NAME9";
public static final String Dinonametest1 = "com.example.die_trinkspielapp.DinoSpieler1";
public static final String Dinonametest2 = "com.example.die_trinkspielapp.DinoSpieler2";
public static final String Dinonametest3 = "com.example.die_trinkspielapp.DinoSpieler3";
public static final String Dinonametest4 = "com.example.die_trinkspielapp.DinoSpieler4";
public static final String Dinonametest5 = "com.example.die_trinkspielapp.DinoSpieler5";
public static final String Dinonametest6 = "com.example.die_trinkspielapp.DinoSpieler6";
public static final String Dinonametest7 = "com.example.die_trinkspielapp.DinoSpieler7";
public static final String Dinonametest8 = "com.example.die_trinkspielapp.DinoSpieler8";
public static final String Dinonametest9 = "com.example.die_trinkspielapp.DinoSpieler9";
}
If you could help me here I will name one of the Drawables(Dinos) the player can choose after you if you want
In your "starteaktivity" method you already have the answer, you just have to pass the selected value through extra to the intent.
Edit: To be more accurate
Hi #MarcStumpp
I already tried that but the value wont go to the startactivity. It won't recognize it if I set it in the Spinner function as a String Value.Do you know how I could fix this?
I think your code is not complete in this case.
First you should declare your spinner as property variables of your Activity
public class Nameeingabespieler2 extends AppCompatActivity {
private TextInputLayout namespieler1;
private TextInputLayout namespieler2;
private Spinner dinospinner;
private Spinner dinospinner2;
private ArrayList<DinoWahl> mDinoWahl;
private DinoAdapter mAdapter;
...
Then in your "starteaktivity" method you can get the value of the spinners to pass it as extra of your intent:
if(name1.equals(name2)) {
Toast.makeText(Nameeingabespieler2.this, "bitte unterschiedliche Namen eingeben",Toast.LENGTH_LONG).show();
} else {
Intent intent = new Intent(this, Trinkspiel2spieler.class);
intent.putExtra(EXTRA_NAME1, name1);
intent.putExtra(EXTRA_NAME2, name2);
intent.putExtra(EXTRA_NAME3, ((DinoWahl) dinospinner.getSelectedItem()).getmDinoName());
...
startActivity(intent);
}
Retrieve the value in your "Trinkspiel2spieler" activity :
public class Trinkspiel2spieler extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trinkspiel2spieler);
String firstSpinnerVal = getIntent().getStringExtra(Constants.EXTRA_NAME3);
...
}
}
Advice
I recommend you to create a Constants class for your extra like that for example:
public class Constants {
public static final String EXTRA_NAME1 = "com.example.die_trinkspielapp.EXTRA_NAME1";
public static final String EXTRA_NAME2 = "com.example.die_trinkspielapp.EXTRA_NAME2";
public static final String EXTRA_NAME3 = "com.example.die_trinkspielapp.EXTRA_NAME3";
...
public static final String Dinonametest1 = "com.example.die_trinkspielapp.DinoSpieler1";
}
So like this you can use the same extra key across your activity and reduce risk of typo.
I don't have the line number on SO, the best is to copy and paste the lines that you think are an issue. Or take screenshot for example. Anyway, I copy the code in my IDE.
About the edited part:
My Problem Now is, that I just wont get the Value transfered, even if I type(line: 162) everything as you said. If I add (line 26 & 27) these Spinner declarations, they wont be used and if I remove (line: 41 & 42) then the app crashes.
It's normal let's see what's android studio code inspector said:
You shouldn't keep you static key here as they are already in your Constant class now. If you keep double reference you will increase the risk of mistakes.
Pay attention to the color of your variable name, dinospinner and dinospinner2 are in grey why? The IDE can give you the answers(just over one of them) :
Android Studio tells you that the value is never assigned ! To understand we should have a look at the line 41 and 42 you mentioned:
Here you are assigned the spinner value to a whole new variable, because of the Spinner at the beginning of the line. Once again, pay attention to the color of the variables dinospinner and dinospinner2. There are in white that mean there are local to the current function (OnCreate in this case). So you will not be able to call them outside of the onCreate.
We can see at line 162 the dinospinner is purple:
It's purple because you are refer to the property one but it's not assigned so when the code will be executed it will crash because of a NullPointerException because it was never assigned.
To make it work you should remove Spinner at lines 41 and 42
But even with this version now, the next Activity (Trinkspiel2spieler)
won't open. I really don't know what to do now. I am really sorry to
bother you this much but I would be really really thankfull if you can
help me.
In the next activity, I don't see a update about your extras. If you want your first spinner value you should at least get it with the key "EXTRA_DINO1" if I update my anwser:
String firstSpinnerVal = getIntent().getStringExtra(Constants.EXTRA_DINO1);
Please note that "EXTRA_DINO1" should be define in Constant and not in your activity.
On my side I was able to launch the next activity without any issue. Can you be more accurate? Whats really happens? Nothing? Did you have some leading logs?
Anyway, I think your original question is answered. If you need more help I suggest you for exemple upload the code to a repository and to share it with me. It will be way easier to review your code and provide help.
Since you seems to start on android, I recommend you to use codelab to improve your skills:
https://developer.android.com/courses/fundamentals-training/toc-v2?authuser=1
Please have a look at this:
https://www.tutorialspoint.com/what-is-a-variable-field-property-in-java
Related
Main activity.java
public class activity_3 extends AppCompatActivity {
TextView question,option_1,option_2,option_3,description,winnner;
NumberProgressBar option_progress1, option_progress2,option_progress3;
int val_1;
int val_2;
int val_3;
DatabaseReference Polldata_3;
String optionOne;
String optionTwo;
String optionThree;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_3);
final String que = getIntent().getExtras().getString("que");
final String des = getIntent().getExtras().getString("des");
optionOne = getIntent().getExtras().getString("option1");
optionTwo = getIntent().getExtras().getString("option2");
optionThree = getIntent().getExtras().getString("option3");
final String id_user = getIntent().getExtras().getString("id");
val_1 = getIntent().getExtras().getInt("val1");
val_2 = getIntent().getExtras().getInt("val2");
val_2 = getIntent().getExtras().getInt("val3");
option_progress1 = (NumberProgressBar) findViewById(R.id.option1_progressbar);
option_progress2 = (NumberProgressBar) findViewById(R.id.option2_progressbar);
option_progress3 = (NumberProgressBar) findViewById(R.id.option3_progressbar);
Polldata_3 = FirebaseDatabase.getInstance().getReference("POll").child("poll_3");
final DatabaseReference answsersave = Polldata_3.child(id_user);
question = (TextView) findViewById(R.id.question_showpoll);
option_1 = (TextView) findViewById(R.id.option_1);
option_2 = (TextView) findViewById(R.id.option_2);
option_3 = (TextView) findViewById(R.id.option_3);
description = (TextView) findViewById(R.id.description_user_3);
winnner = (TextView) findViewById(R.id.winner);
option_1.setText(optionOne);
option_2.setText(optionTwo);
option_3.setText(optionThree);
question.setText(que);
description.setText(des);
option_progress1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
option_progress1.setProgress(val_1+1);
option_progress1.setEnabled(false);
option_progress2.setEnabled(false);
option_progress3.setEnabled(false);
val_1++;
answsersave.child("option_1_value").setValue(val_1);
//winnerdeclare();
}
});
option_progress2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
option_progress2.setProgress(val_2+1);
option_progress1.setEnabled(false);
option_progress2.setEnabled(false);
option_progress3.setEnabled(false);
val_2++;
answsersave.child("option_2_value").setValue(val_2);
// winnerdeclare();
}
});
option_progress3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
option_progress3.setProgress(val_3+1);
option_progress1.setEnabled(false);
option_progress2.setEnabled(false);
option_progress3.setEnabled(false);
val_3++;
// winnerdeclare();
answsersave.child("option_3_value").setValue(val_3);
}
});
}
}
ADAPTER CLASS
public class listview_3 extends AppCompatActivity {
ListView listviewpoll3;
private DatabaseReference Poll_data_3;
List<addpoll_3> addpoll_3List;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview_3);
listviewpoll3 = (ListView) findViewById(R.id.poll_listview_3);
Poll_data_3 = FirebaseDatabase.getInstance().getReference("POll").child("poll_3");
addpoll_3List = new ArrayList<>();
listviewpoll3.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
Intent intent = new Intent(listview_3.this, activity_3.class);
addpoll_3 poll = addpoll_3List.get(position);
final String optionone = poll.getOption_1();
final String optiontwo = poll.getOption_2();
final String optionthree = poll.getOption_3();
final String id_user = poll.getId();
final int value_1 = poll.getOption_1_value();
final int value_2 = poll.getOption_2_value();
final int value_3 = poll.getOption_3_value();
final String question = poll.getQuestion();
final String desp = poll.getDescription();
intent.putExtra("option1",optionone);
intent.putExtra("option2",optiontwo);
intent.putExtra("option3",optionthree);
intent.putExtra("id",id_user);
intent.putExtra("val1",value_1);
intent.putExtra("val2",value_2);
intent.putExtra("val3",value_3);
intent.putExtra("que",question);
intent.putExtra("descp",desp);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
Poll_data_3.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
addpoll_3List.clear();
for(DataSnapshot pollSnapshot: dataSnapshot.getChildren())
{
addpoll_3 poll = pollSnapshot.getValue(addpoll_3.class);
addpoll_3List.add(poll);
}
poll_list_3 adapter = new poll_list_3(listview_3.this,addpoll_3List);
listviewpoll3.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
list class
public class poll_list_3 extends ArrayAdapter<addpoll_3> {
private Activity context;
private List<addpoll_3> addpoll_3List;
public poll_list_3(Activity context, List<addpoll_3> addpoll_3List) {
super(context, R.layout.list_layout, addpoll_3List);
this.context = context;
this.addpoll_3List = addpoll_3List;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View viewitem = inflater.inflate(R.layout.list_layout,null);
TextView textViewName = (TextView) viewitem.findViewById(R.id.tv);
TextView textViewDesp = (TextView) viewitem.findViewById(R.id.tv1);
final addpoll_3 poll1 = addpoll_3List.get(position);
textViewName.setText(poll1.getQuestion());
textViewDesp.setText(poll1.getDescription());
return viewitem;
}
}
I am making a polling app where user can create a poll which is then stored in the firebase database and retrieved into listview of the app
when the user clicks on the list view he is directed to the the activity where there are number of progressbars
i have added a ON-click listener o the progress bar, So when user clicks on the progressbar the val of that option gets incremented in the database. so when a different user vote on the same poll the value from the database is fetched and value of the current user is added displaying the winner,but problem is the value of the progressbar1 gets the value from the database but the other two keep progress bar values start from 0 every time user clicks on the other two progress bar (ie 2 and 3).
please help
addpoll_3.java
public class addpoll_3 {
String id;
String question;
String description;
String option_1;
String option_2;
String option_3;
int option_1_value;
int option_2_value;
int option_3_value;
public addpoll_3(){}
public addpoll_3(String id, String question, String description, String option_1, String option_2, String option_3, int option_1_value, int option_2_value, int option_3_value) {
this.id = id;
this.question = question;
this.description = description;
this.option_1 = option_1;
this.option_2 = option_2;
this.option_3 = option_3;
this.option_1_value = option_1_value;
this.option_2_value = option_2_value;
this.option_3_value = option_3_value;
}
public String getId() {
return id;
}
public String getQuestion() {
return question;
}
public String getDescription() {
return description;
}
public String getOption_1() {
return option_1;
}
public String getOption_2() {
return option_2;
}
public String getOption_3() {
return option_3;
}
public int getOption_1_value() {
return option_1_value;
}
public int getOption_2_value() {
return option_2_value;
}
public int getOption_3_value() {
return option_3_value;
}
}
code:
Activity_3.java
val_1 = getIntent().getExtras().getInt("val1");
val_2 = getIntent().getExtras().getInt("val2");
val_3 = getIntent().getExtras().getInt("val3");
These were changes to be made
//Read from the database
myRef.addValueEventListener(new ValueEventListener()
{
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// This method is called once with the initial value and again
// whenever data at this location is updated.
String value = dataSnapshot.getValue(String.class);
Log.d(TAG, "Value is: " + value);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
recently I been reading about the mvp pattern on Internet and to be honest, it has been a little bit confusing.
I'm trying to re-write an app using the mvp pattern but I reached a point using AsyncTask where I can't figure out how to pass the Object in the Interactor back to the View.
Here'e the code:
View:
public class DetailsActivity extends BaseActivity {
private DetailsPresenter presenter;
private Pet pet;
private TextView name, description, breed, lostAt, age;
private int idList;
#Override
protected void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.details_layout);
DetailsPresenter presenter = new DetailsPresenter();
Typeface font0 = Typeface.createFromAsset(getAssets(), "fonts/CaviarDreams.ttf");
Typeface font1 = Typeface.createFromAsset(getAssets(), "fonts/CaviarDreams_Bold.ttf");
TextView txtDescription = findViewById(R.id.textView8);
TextView txt1 = findViewById(R.id.textView6); //Age, Type
TextView txt2 = findViewById(R.id.textView9); //LostAt
Button btnContact = findViewById(R.id.button6);
description = findViewById(R.id.details);
menuRes = R.menu.details_menu;
name = findViewById(R.id.textView10);
breed = findViewById(R.id.breed);
lostAt = findViewById(R.id.lostAt);
age = findViewById(R.id.age);
name.setTypeface(font1);
breed.setTypeface(font0);
description.setTypeface(font0);
lostAt.setTypeface(font0);
txtDescription.setTypeface(font1);
txt2.setTypeface(font1);
txt1.setTypeface(font1);
btnContact.setTypeface(font0);
idList = getIntent().getExtras().getInt("TAG_LIST");
id = getIntent().getExtras().getInt("TAG_ID");
if(idList == 0){
txt1.setText(R.string.type);
txt2.setText(R.string.txt2);
} else{
txt1.setText(R.string.txt0);
txt2.setText(null);
}
btnContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), ChatFragment.class);
startActivity(intent);
}
});
// Get pet details from database on background
pet = presenter.getPet(idList, id);
}
#Override
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
if(idList == 0){
name.setText(pet.getName());
breed.setText("(" + pet.getBreed() + ")");
description.setText(pet.getDescription());
lostAt.setText(pet.getLocation());
}else{
name.setText(pet.getBreed());
description.setText(pet.getDescription());
lostAt.setText(pet.getGender());
age.setText(pet.getAge());
}
}
}
Presenter:
public class DetailsPresenter {
private DetailsInteractor interactor;
public Pet getPet(int idList, int id) {
interactor = new DetailsInteractor(idList, id);
interactor.execute();
return interactor.pet;
}
}
Interactor:
public class DetailsInteractor extends AsyncTask<String, String, Pet> {
public Pet pet;
private int idList;
private int id;
private DBAction database;
public DetailsInteractor (int idList, int id) {
this.idList = idList;
this.id = id;
database = new DBAction();
}
#Override
protected Pet doInBackground(String... strings) {
pet = database.requestItem(idList, id);
return pet;
}
I need that after getting the data from the database, it updates the View, using object Pet.
Any answers and suggestions will be welcomed, Thanks!
When You create/initialize a presenter in Activity(This is your view) you should pass the view to the presenter. Something like this.
DetailsPresenter presenter = new DetailsPresenter(View view);
View can be any object with which you can update the UI or can call the methods in the activity.
Moreover, you have to go through few more good site to learn about MVP.
http://valokafor.com/learn-android-mvp-pattern-example/ this is really nice one.
I have this app that in an activity creates a list of players and displays them in a listview. When I create a player I use the populatePlayerList method and it works fine. But when I save the list in a parcel and try to restore it, it doesn't populate the listview. Can't figure out why this happens. Below is some code:
public class PlayerManager extends AppCompatActivity {
EditText playerName, playerNumber, playerPosition;
ArrayList<Player> players = new ArrayList<Player>();
ListView playerListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_manager);
playerName = (EditText) findViewById(R.id.etPlayerName);
playerNumber = (EditText) findViewById(R.id.etPlayerNumber);
playerPosition = (EditText) findViewById(R.id.etPlayerPosition);
playerListView = (ListView) findViewById(R.id.playerList);
if(savedInstanceState!=null){
players = savedInstanceState.getParcelableArrayList("savedList");
populatePlayerList();
}
final Button addPlayerBtn = (Button) findViewById(R.id.bAddPlayer);
addPlayerBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addPlayer(playerName.getText().toString(), playerNumber.getText().toString(), playerPosition.getText().toString());
populatePlayerList();
Toast.makeText(getApplicationContext(), playerName.getText().toString() + " added!", Toast.LENGTH_SHORT).show();
}
});
private void populatePlayerList(){
ArrayAdapter<Player> adapter = new PlayerListAdapter();
playerListView.setAdapter(adapter);
}
private void addPlayer(String name, String number, String position){
players.add(new Player(name, number, position));
}
private class PlayerListAdapter extends ArrayAdapter<Player> {
public PlayerListAdapter(){
super(PlayerManager.this, R.layout.player_list, players);
}
#Override
public View getView(int position, View view, ViewGroup parent){
if (view == null)
view = getLayoutInflater().inflate(R.layout.player_list, parent, false);
Player currentPlayer = players.get(position);
TextView name = (TextView) view.findViewById(R.id.playerName);
name.setText(currentPlayer.get_name());
TextView number = (TextView) view.findViewById(R.id.playerNumber);
number.setText(currentPlayer.get_number());
TextView playerPosition = (TextView) view.findViewById(R.id.playerPosition);
playerPosition.setText(currentPlayer.get_position());
return view;
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelableArrayList("savedList", players);
}
Here is my Player Class:
public class Player implements Parcelable{
private String name, position,number;
public Player (String name, String number, String position) {
this.name = name;
this.number = number;
this.position = position;
}
protected Player(Parcel in) {
name = in.readString();
position = in.readString();
number = in.readString();
}
public static final Parcelable.Creator<Player> CREATOR = new Parcelable.Creator<Player>() {
#Override
public Player createFromParcel(Parcel in) {
return new Player(in);
}
#Override
public Player[] newArray(int size) {
return new Player[size];
}
};
public String get_name() {
return name;
}
public String get_position() {
return position;
}
public String get_number(){
return number;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeString(position);
dest.writeString(number);
}
}
I checked the players list when i try to restore it and its empty. So i guess its never saved in outState. Any ideas why?
I fixed my problem by adding android:launchMode="singleInstance" in the PlayerManager activity in Android Manifest.xml file. And I override the onBackPressed to sent me back to a previous activity so the onDestroy method isn't called. That way I get to keep the same instance in the PlayerManager activity.
It's not duplicate. I saw all answers is Stack.
My problem: I have CommentActivity, where I get Cursor. In CommentCursorAdapter I get values from Database.
In adapter I have two images: Like and Dislike. When I click Like - in database rating incremented.
TextView rating should show a new rating after pressing. How to do it correctly?
CommentActivity
public class CommentActivity extends AppCompatActivity {
private String idComment;
private ListView listComments;
private CommentCursorAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_comment);
listComments = (ListView) findViewById(R.id.list_comments);
idComment = getIntent().getStringExtra(MainActivity.ID_KEY);
getCursorData();
}
private void getCursorData() {
adapter = new CommentCursorAdapter(this, new CursorLoader(App.getInstance(), idComment).loadInBackground(), 0);
listComments.setAdapter(adapter);
}
private static class CursorLoader extends SimpleCursorAdapter {
private String idComment;
public CursorLoader(Context context, String idComment) {
super(context);
this.idComment = idComment;
}
#Override
public Cursor loadInBackground() {
return App.getInstance().getDb().rawQuery(
"SELECT comment._id AS _id, comment.text AS text, user.email AS email, comment.rate FROM comment JOIN user ON comment.userId = user._id WHERE comment.postId = ? ORDER BY _id ASC", new String[]{
idComment
});
}
}
}
CommentCursorAdapter
public class CommentCursorAdapter extends CursorAdapter {
private TextView commentEmail;
private TextView commentText;
private TextView ratingText;
private ImageView imageViewLike;
private ImageView imageViewDislike;
private static final String ID = "_id";
private static final String EMAIL = "email";
private static final String TEXT = "text";
private static final String RATE = "rate";
public CommentCursorAdapter(Context context, Cursor c, int flags) {
super(context, c, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup viewGroup) {
return LayoutInflater.from(context).inflate(R.layout.adapter_comment, viewGroup, false);
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
commentEmail = (TextView) view.findViewById(R.id.comment_email);
commentText = (TextView) view.findViewById(R.id.comment_text);
ratingText = (TextView) view.findViewById(R.id.rating_text);
imageViewLike = (ImageView) view.findViewById(R.id.image_like);
imageViewDislike = (ImageView) view.findViewById(R.id.image_dislike);
imageViewLike.setTag(cursor.getString(cursor.getColumnIndexOrThrow(ID)));
imageViewDislike.setTag(cursor.getString(cursor.getColumnIndexOrThrow(ID)));
String email = cursor.getString(cursor.getColumnIndexOrThrow(EMAIL));
String text = cursor.getString(cursor.getColumnIndexOrThrow(TEXT));
String rating = cursor.getString(cursor.getColumnIndexOrThrow(RATE));
commentEmail.setText(email);
commentText.setText(text);
ratingText.setText(rating);
imageViewLike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("like", "click");
SQLiteStatement statement = App.getInstance().getDb().compileStatement(
"UPDATE comment SET rate = rate + 1 WHERE comment._id = ?"
);
statement.bindString(1, (String) view.getTag());
try {
statement.execute();
} finally {
statement.close();
}
}
});
imageViewDislike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.e("dislike", "click");
SQLiteStatement statement = App.getInstance().getDb().compileStatement(
"UPDATE comment SET rate = rate - 1 WHERE comment._id = ?"
);
statement.bindString(1, (String) view.getTag());
try {
statement.execute();
} finally {
statement.close();
}
//swapCursor(cursor);
//notifyDataSetChanged();
}
});
}
}
There are a some options you can choose from:
After updating the rating in the database, you can just reload all data using your loader.
You can migrate your database logic to using a ContentProvider. If you do it correctly, the provider can notify all loaders that their underlying data has been changed, so they are automatically reloaded.
In your CustomAdapter, you need to put this.notifyDataSetChanged(); where you are performing operation of the LIKE and COMMENT.
It's great that you have used CursorAdapter - that listens for update notifications and reloads the content automatically.
Hope it will help you.
I would like to get the clicked index/position of a listview and then pass it over to a new activity. Bellow is my code of what i have done but I keep getting errors when i ran my code. Thank you in advance for the help.
MainAcitivity.Java
public static int hymnIndex;
private void setUpList() {
setListAdapter(new ArrayAdapter<HymnClass>(this, android.R.layout.simple_list_item_1, HymnArrayTitle));
listView = getListView();
//Let’s set a message shown upon tapping an item
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
hymnIndex = position;
Toast.makeText(getApplicationContext(),
((TextView) view).getText().toString(),
Toast.LENGTH_SHORT).show();
Intent selectedItem = new Intent(MainActivity.this, Content.class);
startActivity(selectedItem);
}
});
}
**Content.Java********************************
public class Content extends Activity{
private SQLiteDatabase database;
private static final String DB_NAME = "Akan_DB.db";
private static final String TABLE_NAME = "Hymn";
private static final String HYMN_ID = "_id";
private static final String HYMN_NUMBER = "Hymn_number";
private static final String TITLE = "Title";
private static final String Content = "Content";
private static final String Author = "Author";
private ArrayList<HymnClass> HymnArray;
TextView title_textview;
TextView Content_texview;
TextView author_textview;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hymn_content);
setHymnTitle();
public class HymnClass {
int hymnId;
String hymnNumber;
String title;
String content;
String Author;
#Override
public String toString(){
return this.hymnNumber + " " + this.title;
}
}
private void setHymnTitle() {
String[] whereClause = {String.valueOf(MainActivity.hymnIndex)}; ///converted the int into a string because the where clause only accepts strings
HymnArray = new ArrayList<HymnClass>();
Cursor ListCursor = database.query(TABLE_NAME,
new String[]{HYMN_ID,HYMN_NUMBER,TITLE,Content,Author},
"HYMN_ID = ?",
whereClause,
null,
null,
TITLE);
ListCursor.moveToFirst();
if(!ListCursor.isAfterLast()) {
do {
HymnClass HymnData = new HymnClass();
HymnData.hymnNumber = ListCursor.getString(1);
HymnData.title = ListCursor.getString(2);
HymnData.content = ListCursor.getString(3);
HymnData.Author = ListCursor.getString(4);
HymnArray.add(HymnData);
// title_textview.setText(TITLE);
} while (ListCursor.moveToNext());
}
ListCursor.close();
}
}
//Let’s set a message shown upon tapping an item
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Intent selectedItem = new Intent(MainActivity.this, Content.class);
selectedItem.putExtart("MySelectedPOS",position);
startActivity(selectedItem);
}
});
in your second Activity , in the create method
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hymn_content);
Bundel lBundel=getIntent().getExtrat();
if(lBundel!=null){
// get your passed value
int lSelectedPosition=lBundel.getInt("MySelectedPOS");
}
.
.
.
}