Hide/remove random string? - android

I have used this question here on stackoverflow to create a random string without problem :D
( Show random string)
Some times the same string shows up and that's annoying.
So I want the string to only show one time per session, I have already a Quit Session button that kills the class. So lets say I have numbers from 1-3. Number 2 shows up first, then 1, becuase there's only one number left only 3 can be shown.
My button code for the "next button". Currently it kills the class and starts it again! How can I change it so it just displays a new string?
private void onButtonClick(Button clickedButton) {
Intent startIntent = null;
if (clickedButton.getId() == R.id.quit) {
startIntent = new Intent(this, mainmenu.class);
finish();
}
else if (clickedButton.getId() == R.id.next) {
startIntent = new Intent(this, play.class);
startActivity(startIntent);
finish();
}
if (startIntent != null) {
startIntent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivityIfNeeded(startIntent, 0);
}
}
private void setupbutton() {
View.OnClickListener onClickHandler = new View.OnClickListener() {
public void onClick(View v) {
onButtonClick((Button)v);
}
};
Button button = (Button)findViewById(R.id.quit);
button.setOnClickListener(onClickHandler);
button = (Button)findViewById(R.id.next);
button.setOnClickListener(onClickHandler);

The same string is appearing because the random number generator generates random numbers! It could generate the same number multiple times in a row.
There are many possibilities, to name two:
Put all strings in an array and shuffle it. Then take the elements out one by one starting with index one:
List strings = new ArrayList<String>(getResources().getStringArray(R.array.myArray));
Collections.shuffle(list);
Put all strings in an array, select a string with a random index and remove the string:
Random rgenerator = new Random();
ArrayList<String> strings = new ArrayList<String>(getResources().getStringArray(R.array.myArray));
int index = rgenerator.nextInt(strings.size());
String randomString = strings.get(index);
strings.remove(index);
EDIT:
Ok, I see...
You have to remember which strings have not been used already. Store the strings in a List and make the list static, so you can save state between the creation of different instances of the Activityplay:
private static ArrayList<String> myString;
Then change your constructor a bit:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
setupbutton();
if (myString == null || myString.size() == 0) {
Resources res = getResources();
myString = new ArrayList(Arrays.asList(res.getStringArray(R.array.myArray)));
}
// get a random string
int rand = rgenerator.nextInt(myString.size());
String q = myString.get(rand);
// remove the last used string from the list
myString.remove(rand);
TextView tv = (TextView) findViewById(R.id.text1);
tv.setText(q);
}

Make a random permutation of the indexes and then use it to pick the next string in the sequence.

Related

How to save and retrieve value of radiobutton to SharedPreferences from a multiple choice question

I'm working on a quiz application. There are 10 questions, each question has 4 choices (radio button). Technically, user choose a radio button from the first question then press the "next" button to move on to second question. I want to save the user's answers of every question so it can be showed in another activity in a recyclerview, and user can review their answers. I'm confused regarding how to save the value and show it in another activity in a recyclerview, so what should I do? Please help me, thanks in advance.
Here's some code of my activity :
private ArrayList<Task> tasks;
//some declaration
TextView task_question, task_header, timer, count;
RadioGroup choices_group;
RadioButton choice_A, choice_B, choice_C, choice_D;
Button next, previous;
ProgressDialog loading;
Token auth = PreferencesConfig.getInstance(this).getToken();
String token = "Bearer " + auth.getToken();
int score;
private int currentTaskId = 0;
String task_answer;
//onCreate method
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_banksoal_test);
final Intent intent = getIntent();
String judul = intent.getStringExtra("task_title");
task_header = findViewById(R.id.task_header);
task_header.setText(judul);
timer = findViewById(R.id.time);
task_question = findViewById(R.id.pertanyaan);
choices_group = findViewById(R.id.rg_question);
choice_A = findViewById(R.id.option_A);
choice_B = findViewById(R.id.option_B);
choice_C = findViewById(R.id.option_C);
choice_D = findViewById(R.id.option_D);
count = findViewById(R.id.count);
next = findViewById(R.id.bNext);
previous = findViewById(R.id.bPrevious);
}
//.....
//this is function to retrieve the question
public void showQuestion(){
Task task = tasks.get(currentTaskId);
task_question.setText(task.getSoal());
choice_A.setText(task.getOption_A());
choice_B.setText(task.getOption_B());
choice_C.setText(task.getOption_C());
choice_D.setText(task.getOption_D());
task_answer = task.getJawaban();
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = choices_group.getCheckedRadioButtonId();
RadioButton selectedRB = findViewById(selectedId);
if (selectedRB.getText().toString().equals(task_answer)){
score+=10;
}
if (currentTaskId < tasks.size() - 1){
currentTaskId++;
showQuestion();
selectedRB.setChecked(false);
choices_group.clearCheck();
}else {
Intent intent = new Intent(TaskActivity.this, ResultActivity.class);
intent.putExtra("score", score);
startActivity(intent);
}
}
});
Using SharedPreferences you can do this:
int answer_number = 4;
String answer = "the answer of the user";
//Your id is the identifier and location of your SharedPreferences because you can have
//multiple instances of SharedPrefernces.
String id = "quiz-application";
SharedPreferences sharedPref = getActivity().getSharedPreferences(id, Context.MODE_PRIVATE);
//The editor
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString(String.valueOf(answer_number), answer);
editor.apply();
By doing this you can save in your "quiz_application".sharedpreferences file your answers and later access them by doing this:
SharedPreferences sharedPref = getActivity().getSharedPreferences(id, Context.MODE_PRIVATE);
String answer = sharedRef.getString("1", "no answer found");
//The 1 being the answer number while the second parameter being a fail-safe,
//if there isn't anything there it would return "no answer found".
Bear in mind you still need the id and the answer number to get the information back. The answer number, in this case, is simple, it can only take these values: {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}. What you need to take care of is the id.

How do I pass a variable from one Class to another in Android

How do I assign user input (from a TextView) into a variable then call that variable in another class?
From my MainActivity, I have the followingn where user input is taken:
Button confirm;
EditText inputField;
String typedChar;
char[] cars = typedChar.toCharArray();
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
confirm = (Button)findViewById(R.id.btConfirmInput);
inputField = (EditText) findViewById(R.id.etInputChars);
confirm.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
typedChar = inputField.getText().toString();
}
}
);
I'm trying to store the input and convert it to char
String typedChar;
char[] cars = typedChar.toCharArray();
Now I want to use cars in another class in the following method which print to a custom view:
private void drawText() {
for (int i = 0; i < txtPosByColumn.length; i++) {
canvas.drawText("" + cars[RANDOM.nextInt(cars.length)], i * fontSize, txtPosByColumn[i] * fontSize, paintTxt);
if (txtPosByColumn[i] * fontSize > height && Math.random() > 0.975) {
txtPosByColumn[i] = 0;
}
txtPosByColumn[i]++;
}
I'm however able to assign hardcoded value to cars like bellow:
private char[] chars = "010101".toCharArray();
but I want it come from user input
Anyone please kindly advice, guide. I know I'm doing things wrong but can't figure out...
PS: Noob here
You put your variable in an Intent like this:
confirm.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
typedChar = inputField.getText().toString();
char[] chars = typedChar.toCharArray();
Intent intent = new Intent(MyCurrentActivity.this, MySecondActivity.class);
intent.putExtra("somethingWithARelevantName", chars);
startActivity(intent);
}
}
);
And you get it in your second activity like this:
Intent intent = getIntent();
char[] chars = intent.getExtras().getCharArray("somethingWithARelevantName");
edit: if want your variable in a class that is not an activity, you can pass it in the constructor:
class MyClass{
char[] chars;
MyClass(char[] chars){
this.chars = chars;
}
}
You should specified what is the type of that other class.
If it is a simple Java class you can pass it as a field to your drawText(char[] array);
If however you are dealing with activities the :
In your first activity, before launching the other activity, use Extra intent to send data between activities as the answer show before.

Android: Dealing with blank/invalid entry?

In the Following code I am taking an answer from a user for a mathematical question. When the answer is entered the question then updates to a new one.
How would I add validation so that when a user enters letters or hits submit without entering an answer, the question just stays the same and allows the user to enter again. At the minute, when that happens the app crashes. (note: Main functionality I am refering to occurs in onClick).
public class PracticeTest extends Activity implements View.OnClickListener{
//declare vars
int multiplier;
int[] results=new int[12];
int numberPassed;
TextView question;
EditText answer;
int score;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.practicetest);
// This declares and int variable, assigns it an int value from the
// calling Intent if its not there it is defaulted to 0
numberPassed = getIntent().getIntExtra("convertedNumber2", 0);
//setting up vars(possibly do this in different method?
Button submit = (Button) findViewById(R.id.btnGoPractice2); //declared here as it is only used once
answer = (EditText) findViewById(R.id.etEnterNumberPractice2);
question = (TextView) findViewById(R.id.tvTopPractice2);
//setting listeners
submit.setOnClickListener(this);
updateQuestion();
}
public void onClick(View view) {
// sets text view equal to whats typed in in editText
final String entry = answer.getText().toString();
// convert from string value to int
int a = Integer.parseInt(entry); //note: maybe change name
results[multiplier-1]=a;
score++;//Irrelevant?
if(multiplier<12){
//called after an answer is given
updateQuestion();
} else{
//System.out.println(score);
Intent intent = new Intent(this, Results.class);
intent.putExtra("results", results);
intent.putExtra("numberPassed", numberPassed);
this.startActivity(intent);
}
}
public void updateQuestion(){
multiplier++;
//string to hold quest
String q= numberPassed + "x" + multiplier + "=";
question.setText(q);
answer.setText("");
}
}
So entry is the answer you get? Maybe try regex, you can use this code after submitting the answer or you could check this when a user edits the EditText. The last thing can be done with a TextWatcher, but that would make it a bit more complicated than necessary.
if(entry.matches("[0-9]+") {
// new question
} else {
// warning no valid answer
}
If you want your users only have the option to input numbers. You should set in your EditText:
android:inputType="number"

Passing a counter from one Activity to another

I have an class Voice, which extends Activity, and contains a counter. When the user answers correctly, the counter adds one via counter++;
public class Voice extends Activity implements OnClickListener{
ListView lv;
static final int check = 111;
int counter_score;
TextView txView;
MediaPlayer ourSong;
ImageView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.letter_a);
initialize();
}
private void initialize() {
lv = (ListView)findViewById(R.id.lvVoiceReturn);
Button b = (Button)findViewById(R.id.imageButtonSelector);
txView = (TextView)findViewById(R.id.counter);
b.setOnClickListener(this);
counter_score=0;
}
This score, is bundled and passed on to the next activity "What" within a string "your score is 1".
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == check && resultCode == RESULT_OK) {
ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
lv.setAdapter( new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, results));
if(results.contains("hey") || results.contains("a") || results.contains("ay")) {
//toast referenced to xml the after 400ms
counter_score++;
txView.setText("Your Score is" + " " + counter_score);
AlertDialog dialogBuilder = new AlertDialog.Builder(this).create();
dialogBuilder.setTitle("AWSOME");
dialogBuilder.setMessage("¡Your current score is" + counter_score);
dialogBuilder.setIcon(R.drawable.ic_mark);
dialogBuilder.show();
ourSong = MediaPlayer.create(Voice.this, R.raw.rightsound2);
ourSong.start();
Thread timer = new Thread() {
public void run(){
try {
sleep(2500);
}catch (InterruptedException e){
e.printStackTrace();
} finally {
String score = txView.getText().toString();
Bundle keeper = new Bundle();
keeper.putString("key", score);
Intent putScore = new Intent(Voice.this, What.class);
putScore.putExtras(keeper);
startActivity(putScore);
}
}
};
timer.start();
}
}
The next Activity, What, gets this Bundle and displays it fine using setText(gotScore)
public class What extends Activity implements OnClickListener {
ListView lv;
static final int check = 111;
private int counter_score;
TextView txView;
MediaPlayer ourSong;
ImageView display;
String gotScore;
String classes[] = {"What", "Pagina", "What", "example3", "example4", "example5",
"example6"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.letter_b);
initialize();
Bundle gotKeeper = getIntent().getExtras();
gotScore = gotKeeper.getString("key");
txView.setText(gotScore);
}
private void initialize() {
// TODO Auto-generated method stub
lv = (ListView)findViewById(R.id.lvVoiceReturn);
Button b = (Button)findViewById(R.id.imageButtonSelector);
txView = (TextView)findViewById(R.id.counter);
b.setOnClickListener(this);
..this is when things go bad :(
On What I have another question tied to a counter as well. When the user answers correctly the counter adds one via counter++; and it does. However, it changes the txview string to "your score is 1". I can't get it to add 1 to the counter result passed from the previous activity within the string, so that the counter on What reads "your score is 2". This gets passes to the next activity in Bundle keeper, which holds the aggregate score.
I've read a few tutorials on passing an int verses a string, but some of the code they use like getInt is not recognized. I'm stumped.
What you're bundling and passing to the What activity is not the counter but the string "Your score is 1". If you want to increment that number in the next activity then you should be sending just the integer value and constructing whatever string you need there instead.
I ve read a few tuts on passing an int vs a string..but some of the code they use like getInt is not recognized..anywho Im stumped..
I'm not too sure I know what you mean by getInt() is not recognized. In any case, make things easier for yourself when passing counter from one activity to another. If it is an int and you plan on manipulating like an int in the receiving activity then add it to the bundle as an int. For example:
Bundle keeper = new Bundle();
keeper.putInt("key", counter_score);
And retrieve it from the bundle with:
Bundle gotKeeper = getIntent().getExtras();
int score = gotKeeper.getInt("key");
What if you make a "global" class to be shared across the different activities, and use it to keep the variables used "in sync"?
For example - Globals.java:
public class Globals {
public int counter_score;
}
And then reference that variable using Globals.counter_score
You can of course also use that shared class for other variables and functions as well - for example common operations.
Update
As the commenters pointed out, this method isn't particularily good - I forgot that the code is simply referenced, and doesn't "live" on its own to keep information for the other activities (thanks for correcting me on that one, I'm still learning...)
Something that COULD work better, though, is to pass the current state of the counter_score variable in the intent when you launch your second activity - for example:
IntentToLaunchTheOtherActivity( counter_score );
And then maybe pass the variable back to the previous activity if it's changed afterwards...
I got it work. Essentially I needed to what what TJ Third suggested converting keeper.putString("key", counter_score); to keeper.putInt("key", counter_score);, I also needed to convert the bundle being received to an int within the "What" activity. Within "What" activity I renamed int counter_score; and int gotKeeper;(this was String gotKeeper) then instead of calling counter_score =0; now that the bundle passed is an int,I called counter_score = gotKeeper; under initialize(); so the counter score equals the result generated from the previous activity "Voice".
Now when the user answers correctly, counter++; adds one to the existing counter_score and bundles it and send it to the next activity, and rinse a repeat.
static final int check = 111;
int counter_score;
TextView txView;
MediaPlayer ourSong;
ImageView display;
int gotKeeper;
String classes[] = {"What", "Pagina", "What", "example3", "example4", "example5",
"example6"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.letter_b);
initialize();
Bundle gotKeeper = getIntent().getExtras();
gotKeeper = gotScore.getInt("key");
counter_score = gotKeeper;
Again thnx to everyone for your suggestions and insight.Huge help to a newbie.

Passing data through Intents from a class to another class and can't catch it?

I've two String Arrays like that ,
String[] htmlArray = {
"file:///android_asset/Pinocchio/OPS/chapter-001.xml",
"file:///android_asset/Pinocchio/OPS/chapter-002.xml",
"file:///android_asset/Pinocchio/OPS/chapter-035.xml",
"file:///android_asset/Pinocchio/OPS/chapter-035.xml"
};
String[] htmlArray1 = {
"file:///android_asset/Harry_Potter/OEBPS/part1.xhtml",
"file:///android_asset/Harry_Potter/OEBPS/part2_split_000.xhtml",
"file:///android_asset/Harry_Potter/OEBPS/part18_split_000.xhtml",
"file:///android_asset/Harry_Potter/OEBPS/part18_split_001.xhtml",
};
then, I put two ImageView in another class,
private void init() {
pino_cover = (ImageView) findViewById(R.id.pino_cover);
pino_cover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reader=new Intent(instance,ReaderScreen.class);
reader.putExtra("pino",true);
startActivity(reader);
}
});
harry_cover=(ImageView) findViewById(R.id.harry_cover);
harry_cover.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent reader=new Intent(instance,ReaderScreen.class);
reader.putExtra("harry",true);
startActivity(reader);
}
});
}
Then, if I click the Pino Image, I could get the data through htmlArray .
Intent i=getIntent();
Bundle b = i.getExtras();
String newText = b.
String setext=b.getString("harry");
if (newText=="pino")
pages = htmlArray;
else
pages = htmlArray1;
but if I click the Harry Image, it'd been taken to get the data through the htmlArray too. I want to get htmlArray1.
How could I get ?
You are putting only a boolean to your intent, but you could use .putExtra(mStringArray, htmlArray1); as this method exists to pass arrays through intents...?
Plus, to compare two strings in java, you MUST NOT do == but .equals(""). In your case if(newText.equals("harry))...
EDIT
Ok, in an easier version, you have that :
Intent i=getIntent();
Bundle b = i.getExtras();
String newText = b.
String setext=b.getString("harry");
if (newText=="pino")
pages = htmlArray;
else
pages = htmlArray1;
replace it by that :
Intent i=getIntent();
Bundle b = i.getExtras();
String newText = b.
String setext=b.getString("harry");
if (newText.equals("pino"))
pages = htmlArray;
else
pages = htmlArray1;
This should logically work.
I think the error lies in your using "==" to compare 2 string as mentioned above.
Please use str1.equals(str2) instead of str1 == str2.
And the answer by Sephy suggests you pass the 2 html arrays to the called activity as well. If for some reasons, the called activity can still access the 2 arrays then you can just do as you have done.
Also, in the map you passed, if you use 2 different keys (one is "harry", and one is "pino"), it seems to defeat the purpose. I suggest sth like:
on harry event:
i.putExtra("data", harry_html_array)
on pino event:
i.putExtra("data", pino_html_array)
Inside the called activity:
array = extras.getStringArray("data");

Categories

Resources