i followed a YouTube tutorial about programming a quiz app using java android studio
in the tutorial you put the question in array list then you get randomly question from it
this can cause a problem of getting the same question many time.
How can i fix that? i thought about instead of using random i use a function to get the next item in the list but it didn't work for me.
Yhis is my code
package com.example.quiz20;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.google.android.material.bottomsheet.BottomSheetDialog;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
private TextView questionTV,questionNumberTV;
private Button option1Btn,option2Btn,option3Btn,option4Btn;
private ArrayList<QuizModel> quizModelArrayList;
Random random;
int currentScore = 0 , questionAttempted = 0, currentPos;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questionTV= findViewById(R.id.idTVQuestion);
questionNumberTV=findViewById(R.id.idTVQuestionAttempted);
option1Btn=findViewById(R.id.idBtnOption1);
option2Btn=findViewById(R.id.idBtnOption2);
option3Btn=findViewById(R.id.idBtnOption3);
option4Btn=findViewById(R.id.idBtnOption4);
quizModelArrayList = new ArrayList<>();
random = new Random();
getQuizQuestion(quizModelArrayList);
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
option1Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quizModelArrayList.get(currentPos).getAnswer().trim().toLowerCase().equals(option1Btn.getText().toString().trim().toLowerCase())){
currentScore++;
}
questionAttempted++;
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
}
});
option2Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quizModelArrayList.get(currentPos).getAnswer().trim().toLowerCase().equals(option2Btn.getText().toString().trim().toLowerCase())){
currentScore++;
}
questionAttempted++;
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
}
});
option3Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quizModelArrayList.get(currentPos).getAnswer().trim().toLowerCase().equals(option3Btn.getText().toString().trim().toLowerCase())){
currentScore++;
}
questionAttempted++;
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
}
});
option4Btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(quizModelArrayList.get(currentPos).getAnswer().trim().toLowerCase().equals(option4Btn.getText().toString().trim().toLowerCase())){
currentScore++;
}
questionAttempted++;
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
}
});
}
private void showBottomSheet(){
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog(MainActivity.this);
View bottomSheetView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.score_bottom_sheet,(LinearLayout)findViewById(R.id.idLLScore));
TextView scoreTV = bottomSheetView.findViewById(R.id.idTVScore);
Button restartQuizBtn = bottomSheetView.findViewById(R.id.idBtnRestart);
scoreTV.setText("you score is \n"+currentScore + "/4");
restartQuizBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
currentPos = random.nextInt(quizModelArrayList.size());
setDataToViews(currentPos);
questionAttempted = 0;
currentScore = 0;
bottomSheetDialog.dismiss();
}
});
bottomSheetDialog.setCancelable(false);
bottomSheetDialog.setContentView(bottomSheetView);
bottomSheetDialog.show();
}
private void setDataToViews(int currentPos){
questionNumberTV.setText("Question Attempted : "+questionAttempted + "/4");
if(questionAttempted == 4){
showBottomSheet();
}else {
questionTV.setText(quizModelArrayList.get(currentPos).getQuestion());
option1Btn.setText(quizModelArrayList.get(currentPos).getOption1());
option2Btn.setText(quizModelArrayList.get(currentPos).getOption2());
option3Btn.setText(quizModelArrayList.get(currentPos).getOption3());
option4Btn.setText(quizModelArrayList.get(currentPos).getOption4());
}
}
private void getQuizQuestion(ArrayList<QuizModel> quizModelArrayList) {
quizModelArrayList.add(new QuizModel("in which year google released?","1998","2000","2004","1995","1998"));
quizModelArrayList.add(new QuizModel("What does CPU stand for?","Core Processing Unit","Central Processing Unit","Command Processing Unit","Custom Processing Unit","Central Processing Unit"));
quizModelArrayList.add(new QuizModel("what is the name of the first internet search engine?","Google","Yahoo","AOL","Archie","Archie"));
quizModelArrayList.add(new QuizModel("Which Programming language is the most widely used?","JavaScript","JAVA","Python","PHP","JavaScript"));
}
}
To avoid getting the same selection multiple times, you may want to remove it from the list after it was chosen. The syntax could look something like this:
Random rand = new Random();
ArrayList <Type> list = new ArrayList<>();
int selection = rand.nextInt(list.size() + 1);
switch(selection)
{
case X:
do the X stuff;
list.remove(X);
break;
}
The ArrayList knows what index X is at, so calling it by name will remove the entry. Using the size of the ArrayList to create the bounds for Random numbers also helps keep it dynamic
NOTE this is NOT complete code
Information/examples about preserving contents of the ArrayList using list.clone()
https://www.tutorialspoint.com/clone-an-arraylist-in-java -- An ArrayList can be cloned using the java.util.ArrayList.clone() method. This method does not take any parameters but returns a shallow copy of the specified ArrayList instance. This means that the new ArrayList created using the ArrayList.clone() method refers to the same elements as the original ArrayList but it does not duplicate the elements.
If you want to maintain a list of questions, and then some method of identifying if those have been asked, there are multiple ways to do this.
You could add a boolean value inside QuizModel which holds whether the question has been asked or not in this round, and part of the process to starting a new round of the quiz would be to ensure they are all set to false. The value can be set to true when that question has been asked, and you'd check that value before deciding to use this question or getting another.
Alternatively, you could make the problem less specific to your usecase and more generalised. - for example, all you're really asking is how to get a random number, from a set of numbers, minimising the possibility of duplicates. This is a common software problem that has been solved many many times before.
see Creating random numbers with no duplicates for example. Then you could work this solution into your question selection code.
there are two ways to get the next item in the list:
Using the index:
list.get(list.indexOf(item)+1);
list - your list of questions
item - current question
use LinkedList and its methods
You can drop the question from the array list and make the random number 1 smaller each time. You have to make sure the list can be reset and is automatically reset when it gets to 0 if you do this.
Related
I have this file as an example of a Pet app for Android that showcases profiles of cats or dogs (courtesy of a Udemy course). this is the base file:
package com.delta.generics;
import android.app.Activity;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.Bundle;
import android.service.dreams.DreamService;
import android.util.StringBuilderPrinter;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class GenericsActivity extends Activity {
public TextView nameTextView = null;
public TextView descriptionTextView = null;
public RatingBar ratingView = null;
public ImageView portraitView = null;
public Button nextButton = null;
private int currentSelection = 0;
// CatAdapter catAdapter;
AdoptAdapter<Cat> catAdoptAdapter;
// AdoptAdapter<Dog> dogAdoptAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generics);
nameTextView = (TextView) findViewById(R.id.nameTextView);
descriptionTextView = (TextView) findViewById(R.id.descriptionTextView);
ratingView = (RatingBar) findViewById(R.id.ratingView);
portraitView = (ImageView) findViewById(R.id.portraitView);
nextButton = (Button) findViewById(R.id.nextButton);
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showNext();
}
});
// commenting this out in favour of AdoptAdapter objects
// catAdapter = new CatAdapter(this,nameTextView,descriptionTextView,ratingView,portraitView);
// catAdapter.set(AdoptData.mCatList.get(0));
catAdoptAdapter = new AdoptAdapter<Cat>(this, nameTextView, descriptionTextView, ratingView, portraitView);
// dogAdoptAdapter = new AdoptAdapter<Dog>(this, nameTextView, descriptionTextView, ratingView, portraitView);
catAdoptAdapter.set(AdoptData.mCatList.get(0));
// dogAdoptAdapter.set(AdoptData.mDogList.get(0));
// mCatList and mDogList is an object already exists in AdoptData.java
}
public void showNext(){
int random = currentSelection;
int animal_random = 0;
animal_random = (int )(Math.random() * 2;
while(random == currentSelection){
//avoid same selection twice.
random = (int )(Math.random() * AdoptData.mCatList.size());
random = (int )(Math.random() * AdoptData.mDogList.size());
}
currentSelection = random;
Cat c = AdoptData.mCatList.get(random);
// Dog d = AdoptData.mDogList.get(random);
// commenting in favour of AdoptAdapter object
// catAdapter.set(c);
catAdoptAdapter.set(c);
// dogAdoptAdapter.set(d);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.generics, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
The issue I see is that the way this is formatted, it can only either showcase Cat or Dog profiles, but not together, and I wanted to figure out a way of how to "mix" them so both Cats and Dogs shows up randomly when pressing the "Next" button. And so I figured within the context of Java and this file, I figured I can modify the showNext() method:
public void showNext(){
int random = currentSelection;
int animal_random = 0;
animal_random = (int )(Math.random() * 2);
Log.e("animal_random", String.valueOf(animal_random));
switch(animal_random){
case 0:
while(random == currentSelection){
//avoid same selection twice.
random = (int )(Math.random() * AdoptData.mCatList.size());
}
currentSelection = random;
Cat c = AdoptData.mCatList.get(random);
catAdoptAdapter.set(c);
break;
case 1:
while(random == currentSelection){
//avoid same selection twice.
random = (int )(Math.random() * AdoptData.mDogList.size());
}
currentSelection = random;
Dog d = AdoptData.mDogList.get(random);
dogAdoptAdapter.set(d);
break;
}
}
But I feel like there are way too many "repeated lines" here. If this were in Python I would probably utilize the getAttribute() method to determine which method to use in the object based on a string match. However when I tried to use the supposed Java equivalent getMethod() i keep getting a java.lang.NoSuchMethodException error when i try to use it.
Is there a better way to go about this in Java...? Or would it require a complete restructure for this specific example?
Once you've picked any of the two alternatives below, just update the rest of your code and you'll probably see less duplication across the board since the animals will have a common ground somewhere. :-)
The interface way
Create an Animal interface that gives you access to the common things for animals in your given case, and then implement the interface in both your Dog and your Cat class. Your code in question will probably mostly be talking about Animals instead, unless you explictly need to differentiate between a Dog or a Cat in some way.
One of the neat things about this approach is that while the interface will enforce a contract, it also gives you the wiggle room for if you example want the Dog class to be able to contain stuff that the Cat shouldn't. Maybe it already does?
The enum way
Consolidate your Dog and Cat classes into a single Animal class that carries an enum field called type or something like that. Less classes (hurray?), but with the caveat that the dogs, cats and whatever future animals you add kinda have to fit into the same data structure. Depending on how much weight and meaning the actual type of animal actually has, this may or may not be a really bad idea.
For my uni task I have to adapt a piece of code that we are given to create an app that adds up total costs of items and displays them in Java, and i'm very new to mobile development. We were given the code for everything other than the totalling up and displaying the cost. I added a few variables at the top and a total() method.
Currently, when the app runs it will grab all the prices from the items and add/subtract them as required, but the amounts it's adding and subtracting by are wrong, (everything adds and subtracts by 1.5 instead of the prices defined when the objects are created) and i'm not sure why. Any ideas?
Let me know if you need anymore info from the other classes.
Thanks
EDIT: What I am expecting to happen with the app is that it will have 4 rows, each contain an image associated with one of the Dessert objects, text to say which dessert it is, and then a button to increment and decrement the quantity. I also want to display a total cost of all of the currently selected desserts, e.g if a quantity of 1 donut was selected and a quantity of 2 cookies were selected, the expected total should display as £3.88. The total should update whenever another dessert is added or subtracted
The code I received had the functionality of the list and the increment and decrement functions, so I was tasked with adding prices to the objects, and to make them total up.
CODE:
Main-Acitvity.java
package com.example.annascott.buttondemo;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// quantity of desert
int desertNumber;
Dessert currentDessert;
double totalAmount = 0;
// Create an ArrayList of Dessert objects
final ArrayList<Dessert> desserts = new ArrayList<Dessert>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//CREATE THE DESSERT OBJECTS
desserts.add(new Dessert("Donut", 0, R.drawable.doughnut, 1.99));
desserts.add(new Dessert("Cookie", 0, R.drawable.cookie, 0.99));
desserts.add(new Dessert("PieceOfCake", 0, R.drawable.piece_of_cake, 2.99));
desserts.add(new Dessert("Pastry", 0, R.drawable.pastry, 1.50));
// Create an {#link DessertAdapter}, whose data source is a list of
// {#link Dessert}s. The adapter knows how to create list item views for each item
// in the list.
DesertAdapter flavorAdapter = new DesertAdapter(this, desserts);
// Get a reference to the ListView, and attach the adapter to the listView.
ListView listView = (ListView) findViewById(R.id.listview_dessert);
listView.setAdapter(flavorAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
switch (i) {
case 0:
Intent donut = new Intent(MainActivity.this, Donut.class);
startActivity(donut);
break;
case 1:
Intent cookie = new Intent(MainActivity.this, Cookie.class);
startActivity(cookie);
break;
case 2:
Intent pieceOfCake = new Intent(MainActivity.this, PieceOfCake.class);
startActivity(pieceOfCake);
break;
case 3:
Intent pastry = new Intent(MainActivity.this, Pastry.class);
startActivity(pastry);
break;
}
}
});
}
public void Decrement(View view) {
LinearLayout parentRow = (LinearLayout) view.getParent();
TextView quantityView = (TextView) parentRow.findViewById(R.id.dessert_number);
String quantityString = quantityView.getText().toString();
desertNumber = Integer.parseInt(quantityString);
desertNumber -= 1;
if (desertNumber < 0) {
desertNumber = 0;
Toast.makeText(MainActivity.this, "Can not be less than 0",
Toast.LENGTH_SHORT).show();
}
quantityView.setText(String.valueOf(desertNumber));
total(false);
}
public void Increment(View view) {
// Set the dessert amount to the text view
LinearLayout parentRow = (LinearLayout) view.getParent();
TextView quantityView = (TextView) parentRow.findViewById(R.id.dessert_number);
String quantityString = quantityView.getText().toString();
desertNumber = Integer.parseInt(quantityString);
desertNumber += 1;
quantityView.setText(String.valueOf(desertNumber));
total(true);
}
// Add the total cost of the items to be bought
public void total(boolean change) {
//get all of the desserts
for (int i = 0; i < desserts.size(); i++) {
currentDessert = desserts.get(i);
}
// if increment add price else subtract
TextView shoppingCartView = (TextView) findViewById(R.id.shopping_cart);
if (change) {
totalAmount += currentDessert.getMyPrice();
} else {
totalAmount -= currentDessert.getMyPrice();
}
shoppingCartView.setText(Double.toString(totalAmount));
}
}
Dessert.java
package com.example.annascott.buttondemo;
/**
* {#link Dessert} represents type of desert.
* Each object has 3 properties: name, number, and image resource ID.
*/
public class Dessert {
// Name of the desert
private String mDessertName;
// Number of desserts
private int mDessertNumber;
// Drawable resource ID
private int mImageResourceId;
// Price of desert
private double myPrice;
/*
* Create a new dessert object.
*
* #param vName is the name of the dessert
* #param vNumber is the corresponding number of desserts
* #param image is drawable reference ID that corresponds to the dessert
* */
public Dessert(String vName, int vNumber, int imageResourceId, double price)
{
mDessertName = vName;
mDessertNumber = vNumber;
mImageResourceId = imageResourceId;
myPrice = price;
}
/**
* Get the name of the dessert
*/
public String getDessertName() {
return mDessertName;
}
/**
* Get the number of desserts
*/
public int getDessertNumber() {
return mDessertNumber;
}
/**
* Get the image resource ID
*/
public int getImageResourceId() {
return mImageResourceId;
}
public double getMyPrice() {
return myPrice ;
}
}
Your error is probably in the total function.
//get all of the desserts
for (int i = 0; i < desserts.size(); i++) {
currentDessert = desserts.get(i);
}
you assign the last entry to the variable currentDessert, which is you Pastry with the value of 1.5
How about something like this:
// Add the total cost of the items to be bought
public void total(boolean change) {
//get all of the desserts
for (int i = 0; i < desserts.size(); i++) {
currentDessert = desserts.get(i);
if (change) {
totalAmount += currentDessert.getMyPrice();
} else {
totalAmount -= currentDessert.getMyPrice();
}
}
// if increment add price else subtract
TextView shoppingCartView = (TextView) findViewById(R.id.shopping_cart);
shoppingCartView.setText(Double.toString(totalAmount));
}
But i gotta be honest, i have no clue what you're trying to do here, and what's your problem, or expected output for a certain input.
And that being said, i have no idea what's wrong with your code, because i don't know what it should have done in the first place. If/when seeking debugging help, please put down some sample inputs and expected outputs for them.
you are searching through ALL the desserts in your total function.
So you need to somehow find a way of specifying which desert price you want to add the price off.
I would add a clicked boolean variable to each button in your switch case statement earlier in your code but this is not the only way.
I am making an app that consists of multiple choice questions. Each question has its own activity, for example QuestionTwoActivity. Every time the user clicks on a button, for example a button for answer A, it moves them to the next activity, for example from QuestionTwoActivity to QuestionThreeActivity. If the answer is correct, it increases their mark by 3. It has ten questions and a total possible mark of 30.
That part of my app worked well, but the problem started when I wanted to make a final preview that appears on the GradeActivity which initially only showed the final grade of the user. I wanted to add a list to the grade activity that showed the answer of the answer of the user for each question, and if the user answered correctly or not, so I made a custom arrayAdapter to populate the list, and then tried to use the onclick method of each answer to add an element to the arraylist of the arrayadapter based on the question answered, but it caused the app to crash
Here is the code for the gradeActivity which opens only after the tenth question is answered:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class Grade extends AppCompatActivity{
examark mExamGrade; // declaring an instance of the examark class to call getMark method
double mark; // an int object to store the exam mark in it
TextView mGradeTextView;
TextView mNameTextView;
ListView mPreviewListView;
static ArrayList<answers_preview_data> mPreviewArrayList;
PreviewAdapter mPreviewAdapter;
examark name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_grade);
int colorRed = getResources().getColor(R.color.colorRed);
int colorOrange = getResources().getColor(R.color.colorOrange);
int colorYellow = getResources().getColor(R.color.colorYellow);
int colorGreen = getResources().getColor(R.color.colorGreen);
mExamGrade = new examark();
name = new examark();
mark = mExamGrade.getExamMark();// storing the exam mark in the mark variable
mGradeTextView = (TextView) findViewById(R.id.grade); // initializing the view responsible for showing the final mark
mGradeTextView.setText(String.valueOf(mark));
mNameTextView = (TextView) findViewById(R.id.name_text_view);
String nameOfQuizzer = name.getNameOfQuizTaker();
mNameTextView.setText(nameOfQuizzer);
mPreviewArrayList = new ArrayList<answers_preview_data>();
mPreviewAdapter = new PreviewAdapter(this, mPreviewArrayList);
mPreviewListView = (ListView) findViewById(R.id.preview_list);
mPreviewListView.setAdapter(mPreviewAdapter);
// a conditional statement to change the color of the grade based on how good the preformence
if ( mark > 0.0 && mark < 10.0 ) {
mGradeTextView.setTextColor(colorRed);
} else if (mark > 10.0 && mark <= 15.0) {
mGradeTextView.setTextColor(colorOrange);
} else if (mark > 15.0 && mark < 20.0) {
mGradeTextView.setTextColor(colorYellow);
} else if (mark > 20.0) {
mGradeTextView.setTextColor(colorGreen);
}
}
}
Here is the code for one of the answers onclickListner:
mAnswerATextView.setText("A-Labour Party");
mAnswerATextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Grade.mPreviewArrayList.add(new answers_preview_data("1", "the answer of question A" , " the true answer of question 1", R.color.colorGreen, R.drawable.correct));
Intent openQuestion = new Intent(QuestionOne.this ,QuestionTwo.class);
startActivity(openQuestion);
mExamark.incrementMark();
}
});
Here is what the debugger menu says when the answer button is clicked:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.admin.xams, PID: 16254
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.ArrayList.add(java.lang.Object)' on a null object reference
at com.example.admin.xams.QuestionOne$1.onClick(QuestionOne.java:52)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20270)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5667)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:962)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
Is there a way to add an element to an arraylist from other activities before the activity that contains the arraylist is opened (set to onCreate)?
You can implement one of the following options:
Bad but quick - initialize the list inside your Activity's constructor instead of onCreate() method
Proper but slow - store your values in the Database and fetch once you need them
You could follow the Singleton pattern. In essence, you want to make one global list that you can access from anywhere. You could put this in a few places, I would suggest extending Application and putting it there for a good start.
You may have your own Application, but if not, you'll also need to register it in your manifest.
So, I created an app called MyApp, which extends from Application. This will contain the list of answers that we can access from anywhere.
public class MyApp extends Application {
// A public static list of answers
public static ArrayList<answers_preview_data> answers = new ArrayList<>();
#Override
public void onCreate() {
super.onCreate();
// do other app setup ...
}
}
Now, within your questions, we can easily add a new answer to this list.
public class QuestionOne extends AppCompatActivity implements View.OnClickListener {
#Override
public void onClick(View v) {
// Adding the new answer to your list.
MyApp.answers.add(new answers_preview_data());
}
}
And within your Grade class, we can fetch the list and use it locally.
public class Grade extends AppCompatActivity {
private ArrayList<answers_preview_data> mPreviewArrayList;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPreviewArrayList = MyApp.answers;
// use your list ...
}
}
i am new to development. i am creating an android calculator app with advanced functionality.The thing is i am using text view for taking and displaying inputs/outputs. My question is, how can i take Multiple inputs in multiple Textviews.
For example i have 3 text views,when user will enter 1st input in first textview(by default) and when user press the specific button it moves automatically to next textview . In some cases i want to take 2 inputs and in some cases i want to take 3 ,
How can i achieve this
Note: I dont want to use edit text , coz all buttons of already available in my app.Using Edit text will make softkeyboard to appear, and then for hiding the softkeyboard, i need to use hiding code lines in every class
You can do something like following:
private TextView[] textViews;
private TextView tvCurrentEditing;
private Button btnNext;
private Button btnPrev;
private Button btnSetText;
private int index = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
textViews = new TextView[3];
//Initialize all your textviews like textViews[0] = findViewById(<textview-id1>);
//textViews[1] = findViewById(<textview-id2>);
//textViews[2] = findViewById(<textview-id3>);
tvCurrentEditing = textViews[index];// I am assuming this is your first
//initialzie btnSettext
btnSettext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tvCurrentEditing.setText("<what ever you want");
}
});
//initialize next buton
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(index < textViews.length) {
index++;
}
tvCurrentEditing = textViews[index];
}
});
//Initialize previous button
btnPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(index > 0) {
index--;
}
tvCurrentEditing = textViews[index];
}
});
}
The names of the views could be different. The point is always use tvCurrentEditing whenever you want to change data of TextView. And update tvCurrentEditing whenever needed.
I have this code :
private ImageView d1;
private ArrayList<Integer> listaImagenes = new ArrayList<Integer>();
private ArrayList<String> listaFrases = new ArrayList<String>();
private Button button;
private Integer contador = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.rellenarImagenes();
setContentView(R.layout.imagentonas);
d1 = (ImageView) findViewById(R.id.imagenes01);
while (contador < listaImagenes.size()) {
d1.setImageResource(listaImagenes.get(contador));
button = (Button) findViewById(R.id.botoncillo);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
contador++;
}
});
}
}
private void rellenarImagenes() {
listaImagenes.add(R.drawable.a01);
listaImagenes.add(R.drawable.a02);
listaImagenes.add(R.drawable.a03)
}
I am trying do a loop that when I press the button , increment contador and d1 change image.
but it is not working, application background remains black and not working.
remove while loop and setimage in onclick method.
You are expecting that modifying the value of the variable contador would result in the array item to change.
Keep in mind that in the code line d1.setImageResource(listaImagenes.get(contador));, the get function receives an int. So at the time where it's called it receives a value, not a reference to an Integer. When you change the value of contador, the value that was used to obtain the index in the array is not changed.
And even if the value did change, d1 would still be using the same resource.
What you need to do in the onClickListener is add the code to set the image. Something along the lines of
public void onClick(View v) {
++contador;
if (contador >= listaImagenes.size())
{
contador=0;
}
//you'll probably need to modify the next line to be able to access the button variable.
//one way to do it is to use a final variable in the onCreate method that creates this OnClickListener
button.setImageResource(listaImagenes.get(contador));
}
The while loop is not needed. What your code is doing is setting the image to the 3 items of the array, one after the other, and adding a new click listener 3 times.
I will try to answer and point some of the flaws you have in the code.
wat if there were 100 drawable like R01 ,R02...? Instead you can use getting drawable using string.
why are you using while loop ? since you have the counter you can directly use that.
Let me try to write the code
int contador=1;
#Override
public void onCreate (Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.imagentonas);
context=this;
d1=(ImageView)findViewById(R.id.imagenes01);
button=(Button)findViewById(R.id.botoncillo);
button=(Button)findViewById(R.id.botoncillo);
button.setOnClickListener( new View . OnClickListener () {
public void onClick ( View v ) {
int id = context.getResources().getIdentifier("a"+contador,
"drawable", context.getPackageName());
d1.setImageResource(id);
contador++;
}
});
}
Notice : int id = context.getResources().getIdentifier("a"+contador,"drawable", context.getPackageName()); Here using the string you can access the drawable this solves the issue for any number of consecutive drawables.
Hope you get the concept...
Thanks