How to fix this bug in random array [duplicate] - java

This question already has answers here:
Java generating non-repeating random numbers
(12 answers)
Closed 1 year ago.
I'm currently working on this simple application to create a quiz of ten questions and make it random. This is my progress so far, the questions are random which is what I need, but the problem is the questions are repeating and I only need them to show once. Please help me to fix this bug.
activity_quiz.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="8dp"
android:layout_marginBottom="40dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Score"
android:textSize="20sp"
android:layout_alignParentLeft="true"
android:id="#+id/score_text"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/score"
android:layout_alignParentRight="true"
android:text="0"
android:textSize="20sp"/>
</RelativeLayout>
<TextView
android:id="#+id/question"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="40dp"
android:padding="80dp"
android:text="Question"
android:textSize="15sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choice 1"
android:padding="8dp"
android:layout_marginBottom="24dp"
android:id="#+id/choice1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choice 2"
android:padding="8dp"
android:layout_marginBottom="24dp"
android:id="#+id/choice2" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choice 3"
android:padding="8dp"
android:layout_marginBottom="24dp"
android:id="#+id/choice3" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Choice 4"
android:padding="8dp"
android:layout_marginBottom="24dp"
android:id="#+id/choice4" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/backQuiz"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginBottom="100dp"
android:text="Back to Table of Content"
/>
</RelativeLayout>
</LinearLayout>```
QuestionsLibrary.java:
public class QuestionsLibrary {
public String mQuestions [] = {
"Moses remains on the peak of Mt. Sinai for 40 days and 40 nights, then returns to the Israelites carrying what?",
"From the burning bush, how does God reply to Moses when Moses asks for his name?",
"Who was appointed as the first hereditary high priest of the Israelites??",
"God and Moses make two new tablets. The third Commandment states that one should remember what?",
"With the help of God and his staff, Moses leads the escape of the Israelites and parts which body of water?",
"What river was Moses sent down by his mother?",
"Where did Moses receive the Ten Commandments from God?",
"How many plagues did God send to Egypt?",
"Who is the Father of the Israelites?",
"Which of the following was NOT one of the 10 plagues on Egypt?"
};
private String mChoices [] [] = {
{"Donkey", "The Ten Commandments", "Food", "Laptop"},
{"Time is Gold", "I think; therefore I am", "I Am that I Am", "Revive me Jett"},
{"Matthew", "Aaron", "Joshua", "Polo"},
{"The Sabbath day", "Valentine Day", "Holy Day", "Judgement Day"},
{"Red Sea", "Pacific Ocean", "Nile lake", "Caribbean Sea"},
{"The Nile", "The Jordan", "The Euphrates", "The Tigris"},
{"Mt. Olympus", "Mt. Diablo", "Mt. Nebo", "Mt. Sinai"},
{"12", "13", "8", "10"},
{"Joshua", "Moses", "Abraham", "Jesus"},
{"Frogs", "Flies", "Darkness", "Floods"}
};
private String mCorrectAnswers [] = {"The Ten Commandments", "I Am that I Am", "Aaron", "The Sabbath day", "Red Sea","The Nile","Mt. Sinai","10","Abraham","Floods"};
public String getQuestion(int a) {
String question = mQuestions[a];
return question;
}
public String getChoice1(int a) {
String choice0 = mChoices[a] [0];
return choice0;
}
public String getChoice2(int a) {
String choice1 = mChoices[a] [1];
return choice1;
}
public String getChoice3(int a) {
String choice2 = mChoices[a] [2];
return choice2;
}
public String getChoice4(int a) {
String choice3 = mChoices[a] [3];
return choice3;
}
public String getCorrectAnswer(int a) {
String answer = mCorrectAnswers[a];
return answer;
}
}
QuizActivity.java:
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Random;
public class QuizActivity extends AppCompatActivity {
TextView mScoreView,mQuestionView;
Button mButtonChoice1,mButtonChoice2,mButtonChoice3,mButtonChoice4,backQuiz;
private QuestionsLibrary mQuestions = new QuestionsLibrary();
private String mAnswer;
private int mScore = 0;
private int num = 0;
private int mQuestionsLenght = mQuestions.mQuestions.length;
Random r;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_quiz);
r = new Random ();
mScoreView = (TextView) findViewById (R.id.score);
mQuestionView = (TextView) findViewById (R.id.question);
mButtonChoice1 = (Button) findViewById (R.id.choice1);
mButtonChoice2 = (Button) findViewById (R.id.choice2);
mButtonChoice3 = (Button) findViewById (R.id.choice3);
mButtonChoice4 = (Button) findViewById (R.id.choice4);
backQuiz = (Button) findViewById (R.id.backQuiz);
mScoreView.setText ("Score:" + mScore);
updateQuestion (1+r.nextInt(mQuestionsLenght));
mButtonChoice1.setOnClickListener (new View.OnClickListener (){
#Override
public void onClick(View v) {
if (mButtonChoice1.getText () == mAnswer){
mScore = mScore + 1;
mScoreView.setText ("Score:" + mScore);
updateScore(mScore);
updateQuestion (r.nextInt (mQuestionsLenght));
Toast.makeText (QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show ();
}else {
Toast.makeText (QuizActivity.this, "Wrong", Toast.LENGTH_SHORT).show ();
updateQuestion (r.nextInt (mQuestionsLenght));
}
}
});
mButtonChoice2.setOnClickListener (new View.OnClickListener (){
#Override
public void onClick(View v) {
if (mButtonChoice2.getText () == mAnswer){
mScore = mScore + 1;
mScoreView.setText ("Score:" + mScore);
updateScore(mScore);
updateQuestion (r.nextInt (mQuestionsLenght));
Toast.makeText (QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show ();
}else {
Toast.makeText (QuizActivity.this, "Wrong", Toast.LENGTH_SHORT).show ();
updateQuestion (r.nextInt (mQuestionsLenght));
}
}
});
mButtonChoice3.setOnClickListener (new View.OnClickListener (){
#Override
public void onClick(View v) {
if (mButtonChoice3.getText () == mAnswer){
mScore = mScore + 1;
mScoreView.setText ("Score:" + mScore);
updateScore(mScore);
updateQuestion (r.nextInt (mQuestionsLenght));
Toast.makeText (QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show ();
}else {
Toast.makeText (QuizActivity.this, "Wrong", Toast.LENGTH_SHORT).show ();
updateQuestion (r.nextInt (mQuestionsLenght));
}
}
});
mButtonChoice4.setOnClickListener (new View.OnClickListener (){
#Override
public void onClick(View v) {
if (mButtonChoice4.getText () == mAnswer){
mScore = mScore + 1;
mScoreView.setText ("Score:" + mScore);
updateScore(mScore);
updateQuestion (r.nextInt (mQuestionsLenght));
Toast.makeText (QuizActivity.this, "Correct", Toast.LENGTH_SHORT).show ();
}else {
Toast.makeText (QuizActivity.this, "Wrong", Toast.LENGTH_SHORT).show ();
updateQuestion (r.nextInt (mQuestionsLenght));
}
}
});
backQuiz.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(QuizActivity.this, tableofcontentActivity2.class);
startActivity(i);
}
});
}
private void updateQuestion(int num){
mQuestionView.setText (mQuestions.getQuestion (num));
mButtonChoice1.setText (mQuestions.getChoice1 (num));
mButtonChoice2.setText (mQuestions.getChoice2 (num));
mButtonChoice3.setText (mQuestions.getChoice3 (num));
mButtonChoice4.setText (mQuestions.getChoice4 (num));
mAnswer = mQuestions.getCorrectAnswer (num);
}
private void updateScore(int point) {
mScoreView.setText ("" + mScore);
}

Eager initialization
Create a shuffled list of questions
Iteratively use the questions based on the shuffled order
Shuffle
List<Integer> shuffledQuestions = IntStream.range(0, mQuestionsLenght)
.boxed().collect(Collectors.toList());
Collections.shuffle(shuffledQuestions);
Replace random.nextInt with iterative index
Instead of Random r, use currentIndex = 0
Instead of r.nextInt(mQuestionsLenght), use mQuestions.getQuestion(currentIndex++)
Lazy invalidation
Maintain a set of seen questions
Repeatedly generate r.nextInt if it is already in seen
use the generated question and mark as seen(add to set)

Related

Is there any other option rather that switch case statement?

I am making one simple bank transfer Android application with Google voice input. So, basically, in my app I have created one method layoutclicked() for number of clicks on the layout. I have initialized numberOfclicks as 0 initially, so when user taps on the screen it increments. It will start voice input as well.
public void layoutClicked(View view)
{
if(IsInitialVoiceFinshed) {
numberOfClicks++;
listen();
}
}
I have created switch case statement for filling the input field, so like when case is 1, i.e user tap on the screen one time, then it will start voice input and user tell the details. It will set that text to that input field. And, again, in case 2 it will do another task.
If the user does not say anything in the first case, the field will be empty. And in case 2, they will go to another field. I want to fill that first input field. Can we achieve this by using for loop?
Here is my complete Java code
package org.tensorflow.lite.examples.detection;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Locale;
public class Banktransfer extends AppCompatActivity {
private TextToSpeech tts;
private TextView status;
private TextView To;
private TextView Subject;
private TextView To1;
private int numberOfClicks;
static String to;
float x1,x2;
private boolean IsInitialVoiceFinshed;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bank_transfer);
IsInitialVoiceFinshed = false ;
tts = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.UK);
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
}
tts.speak("Welcome to Bank transfer. tap on the screen , Tell me the IFSC code of bank",TextToSpeech.QUEUE_FLUSH,null);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
IsInitialVoiceFinshed=true;
}
}, 8500);
} else {
Log.e("TTS", "Initilization Failed!");
}
}
});
status = (TextView)findViewById(R.id.status);
To = (TextView) findViewById(R.id.to);
Subject = findViewById(R.id.subject);
To1 = (TextView) findViewById(R.id.to1);
numberOfClicks = 0;
}
#Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void layoutClicked(View view)
{
if(IsInitialVoiceFinshed) {
numberOfClicks++;
listen();
}
}
private void listen(){
Intent i = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
i.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say something");
try {
startActivityForResult(i, 100);
} catch (ActivityNotFoundException a) {
Toast.makeText(Banktransfer.this, "Your device doesn't support Speech Recognition", Toast.LENGTH_SHORT).show();
}
}
#SuppressLint("SetTextI18n")
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 100&& IsInitialVoiceFinshed){
IsInitialVoiceFinshed = false;
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if(result.get(0).contains("cancel"))
{
tts.speak("Transaction Cancelled!",TextToSpeech.QUEUE_FLUSH,null);
}
else {
switch (numberOfClicks) {
case 1:
To1.setText("");
String ifsc;
ifsc = result.get(0).replace(" ","");
char[] str=ifsc.toCharArray();
for(int i=0;i< str.length;i++){
To1.append(str[i]+"");
Toast.makeText(getApplicationContext(), To1.getText().toString(), Toast.LENGTH_SHORT).show();
}
if(!To1.getText().toString().isEmpty()) {
tts.speak("tap on the screen & say, account number to whom you want to transfer money? ",TextToSpeech.QUEUE_FLUSH,null);
}
break;
case 2:
to = result.get(0).replaceAll("[^\\d.]", "");
To.setText(to);
if(!to.isEmpty()) {
tts.speak("tap on the screen & say, how much money you want to transfer",TextToSpeech.QUEUE_FLUSH,null);
}
break;
case 3:
String amount;
amount = result.get(0).replaceAll("[^\\d.]", "");
Subject.setText(amount);
status.setText("confirm");
if(!amount.isEmpty()) {
tts.speak("Please Confirm the details , IFSC code is "+To1.getText().toString()+",Account number is: " + Arrays.toString(To.getText().toString().split("(?!^)")) + ". And Money that you want to transfer is ,: " + Subject.getText().toString() +"rupees"+ ",Tap on the screen and Speak Yes to confirm",TextToSpeech.QUEUE_FLUSH,null);
tts.speak(",swipe left to listen again, or say Yes to confirm or no to cancel the transaction",TextToSpeech.QUEUE_ADD,null);
}
break;
default:
if(result.get(0).equals("yes")) {
if (To.getText().toString().equals("")) {
if (Subject.getText().toString().equals("")) {
tts.speak("Details may be incorrect or incomplete, canceling the transaction",TextToSpeech.QUEUE_FLUSH,null);
final Handler h = new Handler(Looper.getMainLooper());
h.postDelayed(new Runnable() {
#Override
public void run() {
Intent i = new Intent(Banktransfer.this,MainActivity.class);
startActivity(i);
}
},8000);
}
} else {
status.setText("transferring money ");
tts.speak("transferring money please wait",TextToSpeech.QUEUE_FLUSH,null);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
status.setText("Amount transferred successfully.");
tts.speak("Amount transferred successfully.",TextToSpeech.QUEUE_FLUSH,null);
}
}, 6000);
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
finish();
Intent intent = new Intent(Banktransfer.this, MainActivity.class);
startActivity(intent);
tts.speak("you are in main menu. just swipe right and say what you want", TextToSpeech.QUEUE_FLUSH, null);
}
}, 9000);
}
}
else if(result.get(0).contains("no")){
tts.speak("transaction cancelled",TextToSpeech.QUEUE_FLUSH,null);
To.setText("");
Subject.setText("");
IsInitialVoiceFinshed=true;
final Handler handler1 = new Handler();
handler1.postDelayed(new Runnable() {
#Override
public void run() {
finish();
Intent intent = new Intent(Banktransfer.this,MainActivity.class);
startActivity(intent);
}
},3000);
}
}
}
}
else {
switch (numberOfClicks) {
case 1:
break;
case 2:
break;
default:
tts.speak("say yes to proceed the transaction or no to cancel the transaction",TextToSpeech.QUEUE_FLUSH,null);
break;
}
numberOfClicks--;
}
}
IsInitialVoiceFinshed=true;
}
public boolean onTouchEvent(MotionEvent touchEvent) {
switch (touchEvent.getAction()) {
case MotionEvent.ACTION_DOWN:
x1 = touchEvent.getX();
break;
case MotionEvent.ACTION_UP:
x2 = touchEvent.getX();
if (x1 < x2) {
tts.speak("Please Confirm the details , IFSC code is "+To1.getText().toString()+"Account number is: " + Arrays.toString(To.getText().toString().split("(?!^)")) + ". And Money that you want to transfer is ,: " + Subject.getText().toString() +"rupees"+ ",Tap on the screen and Speak Yes to confirm",TextToSpeech.QUEUE_FLUSH,null);
tts.speak("swipe left to listen again, and say Yes to confirm or no to cancel the transaction",TextToSpeech.QUEUE_ADD,null);
break;
}
if (x1 > x2) {
break;
}
break;
}
return false;
}
public void onPause() {
if (tts != null) {
tts.stop();
}
super.onPause();
}
}
bank_transfer.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#faa519"
android:orientation="vertical"
android:onClick = "layoutClicked"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="48dp"
android:background="#e8e8e7"
android:orientation="horizontal">
<TextView
android:id="#+id/status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal|center_vertical"
android:layout_marginLeft="25dp"
android:text="Bank transfer"
android:textColor="#2582C5"
android:textSize="18sp"
android:textStyle="bold" />
</RelativeLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="30dp"
android:orientation="vertical">
<ImageView
android:layout_width="161dp"
android:layout_height="77dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="15dp"
android:src="#drawable/bank" />
<TextView
android:id="#+id/to1"
android:layout_width="fill_parent"
android:layout_height="85dp"
android:layout_marginTop="70dp"
android:background="#f3f3f3"
android:paddingLeft="7dp"
android:paddingTop="7dp"
android:text="IFSC Code"
android:textColor="#4C4D4F" />
<TextView
android:id="#+id/to"
android:layout_width="fill_parent"
android:layout_height="85dp"
android:layout_marginTop="80dp"
android:background="#f3f3f3"
android:paddingLeft="7dp"
android:paddingTop="7dp"
android:text="Acc. no"
android:textColor="#4C4D4F" />
<TextView
android:id="#+id/subject"
android:layout_width="fill_parent"
android:layout_height="95dp"
android:layout_marginTop="95dp"
android:background="#f3f3f3"
android:text="Transfer money:- "
android:textColor="#4C4D4F" />
</LinearLayout>
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
</LinearLayout>
</LinearLayout>
Instead of using switch statement You can use the codes below:
if(//){
}else if(//){
}else if(//){
}else if(//){
}else{
//
}
but switch statement, it's simpler and readable than the if and else if

Issue With Button setOnClickListener Function Call

I have a problem with my setOnClickListener method for one of the buttons in my code. What basically happens is that I call a typeFinder inside the setOnClickListener method, but the first time I press the button the values do not get updated. I have used the debugger and from my understanding what happens is that even though the function is called, the program does not actually go through the function until after setOnClickListener, which means when I press the button the second time it has the right values to show from the previous button press. I have tried using TypesTask as well (as seen in commented part at the bottom of the page), but doing so resulted in the same outcome.
Here is the code for the class:
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private DatabaseReference myRef;
private ArrayList<String> recipesList = new ArrayList<String>();
private String[] types = {"pizza", "ice cream", "sandwich", "salad", "steak"};
private void typeFinder(String type) {
myRef.orderByChild("type").equalTo(type).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 word = "";
boolean wordAdded = false;
String value = dataSnapshot.getValue().toString();
for (int i = 0; i < value.length(); i++) {
if (wordAdded == false) {
if (value.charAt(i) == '=') {
recipesList.add(word);
wordAdded = true;
word = "";
} else if (value.charAt(i) != '{' && value.charAt(i) != ',') {
if (word.length() == 0 && value.charAt(i) == ' ') {
} else {
word = word + value.charAt(i);
}
}
}
if (value.charAt(i) == '}')
if (i + 2 == value.length()) {
wordAdded = false;
break;
} else
wordAdded = false;
}
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
myRef = FirebaseDatabase.getInstance().getReference();
Button saladsB = (Button) findViewById(R.id.saladButton);
Button pizzaB = (Button) findViewById(R.id.pizzaButton);
Button iceCreamB = (Button) findViewById(R.id.iceCreamButton);
Button steakB = (Button) findViewById(R.id.steakButton);
Button sandwichB = (Button) findViewById(R.id.sandwichButton);
final TextView testTextView = (TextView) findViewById(R.id.test_text_view);
testTextView.setText(Integer.toString(recipesList.size()));
super.onCreate(savedInstanceState);
saladsB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// recipesList.clear();
// t.typeFinder("salad")
typeFinder("salad");
// new TypesTask().execute("salad");
String recipes = "";
for (int i = 0; i < recipesList.size(); i++) {
recipes = recipes + recipesList.get(i) + "\n";
}
testTextView.setText(recipes);
// Intent intent = new Intent(MainActivity.this, ListviewActivity.class);
// intent.putStringArrayListExtra("FOOD_LIST", recipesList);
// startActivity(intent);
}
});
}
/*
public class TypesTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
myRef = FirebaseDatabase.getInstance().getReference();
}
#Override
protected Void doInBackground(String... params) {
typeFinder(params[0]);
return null;
}
}
*/
}
Here is the xml for the page
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.thevash.recipes.MainActivity">
<LinearLayout
android:layout_width="0dp"
android:layout_height="810dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="458dp"
android:orientation="horizontal"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:layout_constraintLeft_creator="1"
tools:layout_constraintRight_creator="1"
tools:layout_constraintTop_creator="1">
<TextView
android:id="#+id/test_text_view"
android:layout_width="585dp"
android:layout_height="248dp"
android:layout_weight="1"
android:text="TextView"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="-377dp" />
</LinearLayout>
<Button
android:id="#+id/saladButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="Salads"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="5dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/pizzaButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="Pizzas"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="parent"
android:layout_marginTop="52dp"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/iceCreamButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="ice cream"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="#+id/pizzaButton"
app:layout_constraintTop_toBottomOf="#+id/pizzaButton"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="#+id/pizzaButton" />
<Button
android:id="#+id/steakButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="steaks"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="#+id/iceCreamButton"
app:layout_constraintTop_toBottomOf="#+id/iceCreamButton"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="#+id/iceCreamButton" />
<Button
android:id="#+id/sandwichButton"
android:layout_width="0dp"
android:layout_height="48dp"
android:text="sandwiches"
tools:layout_constraintTop_creator="1"
tools:layout_constraintRight_creator="1"
app:layout_constraintRight_toRightOf="#+id/steakButton"
app:layout_constraintTop_toBottomOf="#+id/steakButton"
tools:layout_constraintLeft_creator="1"
app:layout_constraintLeft_toLeftOf="#+id/steakButton" />
</android.support.constraint.ConstraintLayout>
you can do this using TypesTask but you need to modify TypesTask class like below
public class TypesTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
myRef = FirebaseDatabase.getInstance().getReference();
}
#Override
protected Void doInBackground(String... params) {
typeFinder(params[0]);
return null;
}
#Override
onPostExecute(Void result){
String recipes = "";
for (int i = 0; i < recipesList.size(); i++) {
recipes = recipes + recipesList.get(i) + "\n";
}
testTextView.setText(recipes);
}
}
and your onClick should be like this
saladsB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new TypesTask().execute("salad");
}
});
As mentioned in the comments both of the answers provided work. I either had to add the UI update to the typeFinder function itself, or use AsyncTask to update the UI inside onPostExecute method. For the latter I had to put the program to sleep for one second after the line typeFinder(params[0]) to give it enough time to update the variables.
Your method in which you are building the reciepeList is an asynchronous call. You need to update the changes to Ui after the OnSuccess() call of EventListener. Relocate the Ui updation code to OnDataChange See the code below :
private void typeFinder(String type) {
myRef.orderByChild("type").equalTo(type).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 word = "";
boolean wordAdded = false;
String value = dataSnapshot.getValue().toString();
for (int i = 0; i < value.length(); i++) {
if (wordAdded == false) {
if (value.charAt(i) == '=') {
recipesList.add(word);
wordAdded = true;
word = "";
} else if (value.charAt(i) != '{' && value.charAt(i) != ',') {
if (word.length() == 0 && value.charAt(i) == ' ') {
} else {
word = word + value.charAt(i);
}
}
}
if (value.charAt(i) == '}')
if (i + 2 == value.length()) {
wordAdded = false;
break;
} else
wordAdded = false;
}
// Update the Ui Here
String recipes = "";
for (int i = 0; i < recipesList.size(); i++) {
recipes = recipes + recipesList.get(i) + "\n";
}
this.testTextView.setText(recipes);
}
#Override
public void onCancelled(DatabaseError error) {
// Failed to read value
Log.w(TAG, "Failed to read value.", error.toException());
}
});
}

Android TextView is not showing data on setText even if data is present

I'm working on a small project where a user is shown his result after he tries to login and he already taken the quiz on my app.
So i'm using a page like this to display result.
But i cannot display my score. This page also has an option to share your score which is working fine and displaying score.Share option containing result.
I'm attaching my XML and Java Code kindly please help me solve the issue that'll be great help.
Thanks & Regards
BugAdder
XML Code:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center|top">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:padding="20dp"
android:textAlignment="center"
android:textSize="25sp"
android:textStyle="bold"
android:text="#string/login_score_title"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:padding="20dp"
android:textSize="25sp"
android:textStyle="bold"
android:text="#string/score_result"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:textStyle="bold"
android:id="#+id/login_score_text"/>
<Button
android:padding="20dp"
android:layout_marginTop="75dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/login_share_button"
android:text="#string/share_button"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="20dp"
android:text="#string/exit_button"
android:drawableEnd="#drawable/arrow_right"
android:drawableRight="#drawable/arrow_right"
android:id="#+id/login_exit_button"/>
</LinearLayout>
</ScrollView>
Java Code:
public class QuizLoginScore extends AppCompatActivity {
private List<ScoreItem> mScoreItems = new ArrayList<>();
private ProgressDialog mProgressDialog;
private String mScore;
private TextView mScoreTextView;
private Button mShareButton;
private Button mExitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.score_login_quiz);
mScoreTextView = (TextView)findViewById(R.id.login_score_text);
mShareButton = (Button)findViewById(R.id.login_share_button);
mExitButton = (Button)findViewById(R.id.login_exit_button);
new FetchScoresTask().execute();
mScoreTextView.setText(mScore);
mExitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >= 21){
finishAndRemoveTask();
}else{
finishAffinity();
System.exit(0);
}
}
});
mShareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT,getScoreShareReport(mScore));
i.putExtra(Intent.EXTRA_SUBJECT,getString(R.string.score_report_subject));
i = Intent.createChooser(i,getString(R.string.send_report));
startActivity(i);
}
});
}
public String getScoreShareReport(String score){
String result;
StringBuilder sb = new StringBuilder();
sb.append("QuizApp!").
append("\n\n").
append("I Just Scored").
append(" \' ").
append(score).
append(" \' ").
append("marks out of \' 100 \' in Latest Quiz on QuizApp!\nWhats your Score Huh?");
result = sb.toString();
return result;
}
private class FetchScoresTask extends AsyncTask<Void, Void, List<ScoreItem>> {
#Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(QuizLoginScore.this);
mProgressDialog.setTitle("Downloading Score");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setMessage("Please wait while the score is being downloaded!");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected List<ScoreItem> doInBackground(Void... params) {
return new ScoreFetcher().fetchScoreItems();
}
#Override
protected void onPostExecute(List<ScoreItem> scoreItems) {
mScoreItems = scoreItems;
for(int i = 0; i < mScoreItems.size(); i++){
if(mScoreItems.get(i).getUserId().equals(QuizLogin.mUserIdString)){
mScore = String.valueOf(mScoreItems.get(i).getScore());
break;
}
}
mProgressDialog.dismiss();
}
}
}
mScore is set in a async task. so you must set text in onPostExecute. try following code:
public class QuizLoginScore extends AppCompatActivity {
private List<ScoreItem> mScoreItems = new ArrayList<>();
private ProgressDialog mProgressDialog;
private String mScore;
private TextView mScoreTextView;
private Button mShareButton;
private Button mExitButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.score_login_quiz);
mScoreTextView = (TextView)findViewById(R.id.login_score_text);
mShareButton = (Button)findViewById(R.id.login_share_button);
mExitButton = (Button)findViewById(R.id.login_exit_button);
new FetchScoresTask().execute();
mScoreTextView.setText(mScore);
mExitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(Build.VERSION.SDK_INT >= 21){
finishAndRemoveTask();
}else{
finishAffinity();
System.exit(0);
}
}
});
mShareButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT,getScoreShareReport(mScore));
i.putExtra(Intent.EXTRA_SUBJECT,getString(R.string.score_report_subject));
i = Intent.createChooser(i,getString(R.string.send_report));
startActivity(i);
}
});
}
public String getScoreShareReport(String score){
String result;
StringBuilder sb = new StringBuilder();
sb.append("QuizApp!").
append("\n\n").
append("I Just Scored").
append(" \' ").
append(score).
append(" \' ").
append("marks out of \' 100 \' in Latest Quiz on QuizApp!\nWhats your Score Huh?");
result = sb.toString();
return result;
}
private class FetchScoresTask extends AsyncTask<Void, Void, List<ScoreItem>> {
#Override
protected void onPreExecute() {
mProgressDialog = new ProgressDialog(QuizLoginScore.this);
mProgressDialog.setTitle("Downloading Score");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setMessage("Please wait while the score is being downloaded!");
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected List<ScoreItem> doInBackground(Void... params) {
return new ScoreFetcher().fetchScoreItems();
}
#Override
protected void onPostExecute(List<ScoreItem> scoreItems) {
mScoreItems = scoreItems;
for(int i = 0; i < mScoreItems.size(); i++){
if(mScoreItems.get(i).getUserId().equals(QuizLogin.mUserIdString)){
mScore = String.valueOf(mScoreItems.get(i).getScore());
mScoreTextView.setText(mScore);
break;
}
}
mProgressDialog.dismiss();
}
}
}
Put your mScore string in log to see if you are getting the data in logcat. Also try changing the color of your textview. Also put your textview.settext() in onpostexecute(); method
Set text from onPostExecute():
#Override
protected void onPostExecute(List<ScoreItem> scoreItems) {
mScoreItems = scoreItems;
for(int i = 0; i < mScoreItems.size(); i++){
if(mScoreItems.get(i).getUserId().equals(QuizLogin.mUserIdString)){
mScore = String.valueOf(mScoreItems.get(i).getScore());
mScoreTextView.setText(mScore);
break;
}
}
mProgressDialog.dismiss();
}

[Android-Java]Learning android, layout work only once

I am learning how to make an android app, as my first project I'm trying to build a stupid game haha.
when I get to my second activity, The game runs as it has to (picture down)
http://i.imgur.com/BBllAJU.png?1
Than nothing changes, the score, the numbers, but all the toasts still coming.
package com.example.moshik.whatisbigger;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.DynamicLayout;
import android.text.Layout;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Random;
public class NormalModeActivity1 extends AppCompatActivity {
int Score = 0;
boolean AnswerBig = false;
boolean AnswerEqual = false;
boolean AnswerSmall = false;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_normal_mode1);
Random rnd = new Random();
while (counter < 5) {
int Number1 = rnd.nextInt(99) + 1;
TextView X = (TextView) findViewById(R.id.XNumber);
String Xstring = String.valueOf(Number1);
X.setText(Xstring);
int Number2 = rnd.nextInt(99) + 1;
TextView Y = (TextView) findViewById(R.id.YNumber);
String Ystring = String.valueOf(Number2);
Y.setText(Ystring);
if (Number1 > Number2) {
AnswerBig = true;
}
if (Number1 == Number2) {
AnswerEqual = true;
}
if (Number1 < Number2) {
AnswerSmall = true;
}
findViewById(R.id.Bigger).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerBig) {
Toast.makeText(NormalModeActivity1.this, "(BIG)You are RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
AnswerBig = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(BIG)You were WRONG!", Toast.LENGTH_SHORT).show();
}
}
});
findViewById(R.id.Equal).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerEqual) {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
AnswerEqual = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were WRONG!", Toast.LENGTH_SHORT).show();
}
}
});
findViewById(R.id.Smaller).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerSmall)
{
Toast.makeText(NormalModeActivity1.this, "(Small)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
AnswerSmall = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Small)You were WRONG!", Toast.LENGTH_SHORT).show();
}
}
});
TextView score = (TextView) findViewById(R.id.ScoreDisplay);
String ScoreShow;
ScoreShow = String.valueOf(Score);
score.setText("Your Score Is: " + ScoreShow);
counter++;
if (counter > 5)
{
score.setText("ItsOver!!!");
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.moshik.whatisbigger.NormalModeActivity1">
<include layout="#layout/content_normal_mode1" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="30sp"
android:id="#+id/ScoreDisplay"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/XNumber"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/ScoreDisplay"
android:layout_toStartOf="#+id/ScoreDisplay"
android:textSize="20sp">
</TextView>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/YNumber"
android:layout_alignTop="#+id/XNumber"
android:layout_toRightOf="#+id/ScoreDisplay"
android:layout_toEndOf="#+id/ScoreDisplay"
android:textSize="20sp">
</TextView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Bigger"
android:layout_marginTop="121dp"
android:hint="#string/BIG"
android:layout_below="#+id/XNumber"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Equal"
android:layout_alignTop="#+id/Bigger"
android:layout_centerHorizontal="true"
android:hint="#string/EQUAL">
</Button>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Smaller"
android:hint="#string/SMALL"
android:layout_alignTop="#+id/Equal"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true">
</Button>
Here is the layout and the activity itself.
Can you find what the problem here or what I miss?, thank you very much :)
You are never updating your score TextView. Change it to a class field first so it is easier to access in your callbacks.
private TextView score;
and then in your onCreate method:
score = (TextView) findViewById(R.id.ScoreDisplay);
Then update the text in each callback click listener after incrementing Score:
Score++;
score.setText("Your Score Is: " + Score);
Also, I would update your variable names to be more different as using Score for an int and score for a TextView is confusing.
Update Showing class field:
public class NormalModeActivity1 extends AppCompatActivity {
int Score = 0;
boolean AnswerBig = false;
boolean AnswerEqual = false;
boolean AnswerSmall = false;
int counter = 0;
TextView X;
TextView Y;
TextView score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_normal_mode1);
// set class fields
X = (TextView) findViewById(R.id.XNumber);
Y = (TextView) findViewById(R.id.YNumber);
score = (TextView) findViewById(R.id.ScoreDisplay);
Random rnd = new Random();
int Number1 = rnd.nextInt(99) + 1;
String Xstring = String.valueOf(Number1);
X.setText(Xstring);
int Number2 = rnd.nextInt(99) + 1;
String Ystring = String.valueOf(Number2);
Y.setText(Ystring);
if (Number1 > Number2) {
AnswerBig = true;
}
if (Number1 == Number2) {
AnswerEqual = true;
}
if (Number1 < Number2) {
AnswerSmall = true;
}
findViewById(R.id.Bigger).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerBig) {
Toast.makeText(NormalModeActivity1.this, "(BIG)You are RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
score.setText("Your Score Is: " + Score);
AnswerBig = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(BIG)You were WRONG!", Toast.LENGTH_SHORT).show();
}
incrementAndCheckCounter();
}
});
findViewById(R.id.Equal).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerEqual) {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
score.setText("Your Score Is: " + Score);
AnswerEqual = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Equal)You were WRONG!", Toast.LENGTH_SHORT).show();
}
incrementAndCheckCounter();
}
});
findViewById(R.id.Smaller).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (AnswerSmall)
{
Toast.makeText(NormalModeActivity1.this, "(Small)You were RIGHT!", Toast.LENGTH_SHORT).show();
Score++;
score.setText("Your Score Is: " + Score);
AnswerSmall = false;
} else {
Toast.makeText(NormalModeActivity1.this, "(Small)You were WRONG!", Toast.LENGTH_SHORT).show();
}
incrementAndCheckCounter();
}
});
String ScoreShow;
ScoreShow = String.valueOf(Score);
score.setText("Your Score Is: " + ScoreShow);
}
private void incrementAndCheckCounter() {
counter++;
if (counter > 5)
{
score.setText("ItsOver!!!");
}
}
}

Why does adding buttons to grid view causes text-view to change?

My android activity workout view displays a grid view. Each object of grid view either displays the name of an exercise and two buttons or it displays a exercise set and two buttons.This is what it looks like when I don't add buttons to each set.
Once I enable buttons to each set by commenting out deleteBtn.setVisibility(View.GONE); the activity displays this. changing the 3rd to last object to display an exercise instead of a set. (Scrolled down)
getLocation(int i) determines if an grid object is going to be an Exercise or set. location[0] determines the exercise and location1 if == 0 refers to exercise and location1 > 0 refers to an exercise set.
private int[] getLocation(int i) {
db = new DatabaseHelper(context);
int temp[] = {-1, -1};
int count = -1;
for (int we = 0; we < WE_TABLE.size(); we++) {
for (int s = 0; s < db.getSetCountByWEID(WE_TABLE.get(we).getID()) + 1; s++) {
count++;
if (count == i) {
//Log.e("Test","WE: " + we+ " S: " + s + " For: " + i);
temp[0] = we;
temp[1] = s;
db.closeDB();
return temp;
}
}
}
db.closeDB();
return temp;
}
public View getView(int position, View convertView, ViewGroup parent) {
int temp_p = position;
TextView tv;
View view = convertView;
if (view == null) {
totalObj++;
Obj = totalObj;
int[] location = getLocation(Obj - 1);
db = new DatabaseHelper(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.activity_workout_view_gridview, null);
tv = new TextView(context);
tv.setLayoutParams(new GridView.LayoutParams(GridView.LayoutParams.FILL_PARENT, GridView.LayoutParams.WRAP_CONTENT));
Button deleteBtn = (Button) view.findViewById(R.id.delete_btn);
Button addBtn = (Button) view.findViewById(R.id.add_btn);
tv = (TextView) view.findViewById(R.id.list_item_string);
String Exercises = (Obj + " " + location[0] + "," + location[1]);
Log.e("Test", "Location: " + location[0] + " , " + location[1] + " Number " + Obj);
if (location[1] == -1) {
} else if (location[1] == 0) {
WorkoutExercise WE = WE_TABLE.get(location[0]);
Exercises = WE.getExerciseName();
// addBtn.setVisibility(View.GONE);
//deleteBtn.setVisibility(View.GONE);
} else {
S_TABLE = db.getSets(WE_TABLE.get(location[0]).getID() + "");
Exercises = S_TABLE.get(location[1] - 1).getWeight() + "lbs " + S_TABLE.get(location[1] - 1).getReps() + " Reps";
addBtn.setVisibility(View.GONE);
//deleteBtn.setVisibility(View.GONE);
}
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do something
}
});
tv.setText(Exercises);
db.closeDB();
}
return view;
}
And My XML for each row is:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="0dp"
android:text="Dele" />
<Button
android:id="#+id/add_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/delete_btn"
android:layout_centerVertical="true"
android:layout_marginRight="0dp"
android:text="Add" />
</RelativeLayout>
I lowered the height to match the text and It is working properly, thanks to talex

Categories