Android - Save Game - Text File - java

My question is, how do I make a save file using a text file. I want to be able to save the game and to load even after the phone has been restarted.
So what I'm asking is how to make a save file using text file.
public class MainActivity extends AppCompatActivity {
ImageButton Button,Button2,Button3,Button4,Button5,Button6,Button7,Button8,Button9,Button10;
long count = 0;
MediaPlayer mp, mp_pilla,mp_slua;
#Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView textview = (TextView) findViewById(R.id.textView);
mp = MediaPlayer.create(MainActivity.this, R.raw.nyaaw);
mp_pilla = MediaPlayer.create(MainActivity.this, R.raw.pillabli);
mp_slua = MediaPlayer.create(MainActivity.this, R.raw.slua);
Button = (ImageButton) findViewById(R.id.myButton);
Button2 = (ImageButton) findViewById(R.id.myButton2);
Button3 = (ImageButton) findViewById(R.id.myButton3);
Button4 = (ImageButton) findViewById(R.id.myButton4);
Button5 = (ImageButton) findViewById(R.id.myButton5);
Button6 = (ImageButton) findViewById(R.id.myButton6);
Button7 = (ImageButton) findViewById(R.id.myButton7);
Button8 = (ImageButton) findViewById(R.id.myButton8);
Button9 = (ImageButton) findViewById(R.id.myButton9);
Button10 = (ImageButton) findViewById(R.id.myButton10);
textview.setText("0");
ImageButton buttonsak = (ImageButton) findViewById(R.id.myButton);
ImageButton buttonsak2 = (ImageButton) findViewById(R.id.myButton2);
ImageButton buttonsak3 = (ImageButton) findViewById(R.id.myButton3);
ImageButton buttonsak4 = (ImageButton) findViewById(R.id.myButton4);
ImageButton buttonsak5 = (ImageButton) findViewById(R.id.myButton5);
ImageButton buttonsak6 = (ImageButton) findViewById(R.id.myButton6);
ImageButton buttonsak7 = (ImageButton) findViewById(R.id.myButton7);
ImageButton buttonsak8 = (ImageButton) findViewById(R.id.myButton8);
ImageButton buttonsak9 = (ImageButton) findViewById(R.id.myButton9);
ImageButton buttonsak10 = (ImageButton) findViewById(R.id.myButton10);
View.OnClickListener clicker = new View.OnClickListener() {
public void onClick(View v) {
switch (v.getId()) {
case R.id.myButton:
count++;
mp.start();
textview.setText("" + count);
break;
case R.id.myButton2:
if (count >= 50) {
count += 5;
mp_slua.start();
textview.setText("" + count);
}
break;
case R.id.myButton3:
if (count >= 100) {
count += 10;
mp_pilla.start();
textview.setText("" + count);
}
break;
case R.id.myButton4:
if (count >= 500) {
count += 20;
mp_slua.start();
textview.setText("" + count);
}
break;
case R.id.myButton5:
if (count >= 2000) {
count += 50;
mp_slua.start();
textview.setText("" + count);
}
break;
case R.id.myButton6:
if (count >= 5000) {
count += 100;
mp.start();
textview.setText("" + count);
}
break;
case R.id.myButton7:
if (count >= 10000) {
count += 200;
mp_slua.start();
textview.setText("" + count);
}
break;
case R.id.myButton8:
if (count >= 30000) {
count += 500;
mp_pilla.start();
textview.setText("" + count);
}
break;
case R.id.myButton9:
if (count >= 100000) {
count += 1000;
mp.start();
textview.setText("" + count);
}
break;
case R.id.myButton10:
if (count >= 250000) {
count += 2500;
mp_pilla.start();
textview.setText("" + count);
}
break;
default:
break;
}
}
};
buttonsak.setOnClickListener(clicker);
buttonsak2.setOnClickListener(clicker);
buttonsak3.setOnClickListener(clicker);
buttonsak4.setOnClickListener(clicker);
buttonsak5.setOnClickListener(clicker);
buttonsak6.setOnClickListener(clicker);
buttonsak7.setOnClickListener(clicker);
buttonsak8.setOnClickListener(clicker);
buttonsak9.setOnClickListener(clicker);
buttonsak10.setOnClickListener(clicker);
}

Use SharePreference to save data like this:
SharedPreferences.Editor editor = getSharedPreferences(SAVE_GAME, MODE_PRIVATE).edit();
editor.putString("game", "saved");
editor.commit();
and get the info like this:
SharedPreferences prefs = getSharedPreferences(SAVE_GAME, MODE_PRIVATE);
String restoredText = prefs.getString("game", null);
if (restoredText != null) {
String name = prefs.getString("game", "state");// "state" is the default value.
}

As #Mariano said: SharedPreferences is a good place to save things. The advantage of SharedPreferences is that it doesn't require any additional permissions.
There are other choices though, depending on your needs. You can write to external storage (which requires the WRITE_EXTERNAL) permission and perhaps much more interesting for you is using the service that Google provides for saving game state. There are some nice examples on there for you to follow.

Related

My EditText won't add a point to my score. android quiz app

Why my program isn't adding a point to my score when I submit the correct answer.
Please help.
Here are my variables:
public class MainActivity extends AppCompatActivity {
int mscore =0 ;
String q5R = "ripken";
String q5CR = "cal ripken";
String q5Cal = "cal";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void checkResult(View v) {
//Access the RadioGroup view and save it to a variable.
RadioGroup radioGroup = (RadioGroup) findViewById(R.id.q1RadioBox);
//Get the id of the RadioButton that is checked and save it
//as an integer variable.
int solutionId = radioGroup.getCheckedRadioButtonId();
//Use if statements to respond based on whether
//it is the id of the correct answer.
if (solutionId == R.id.answer1) {
mscore = mscore +1;
} else {
mscore = mscore + 0;
}
//Access the RadioGroup2 view and save it to a variable.
RadioGroup radioGroup2 = (RadioGroup) findViewById(R.id.q2RadioBox);
//Get the id of the RadioButton that is checked and save it
//as an integer variable.
int solutionId2 = radioGroup2.getCheckedRadioButtonId();
//Use if statements to respond based on whether
//it is the id of the correct answer.
if (solutionId2 == R.id.answer2) {
mscore = mscore +1;
} else {
mscore = mscore + 0;
}
CheckBox ws1966 = (CheckBox) findViewById(R.id.checkbox_1966);
CheckBox ws1983 = (CheckBox) findViewById(R.id.checkbox_1983);
CheckBox ws1970 = (CheckBox) findViewById(R.id.checkbox_1970);
CheckBox ws1984 = (CheckBox) findViewById(R.id.checkbox_1984);
CheckBox ws1961 = (CheckBox) findViewById(R.id.checkbox_1961);
// Check for Required Answers
if (ws1966.isChecked() && ws1983.isChecked() && ws1970.isChecked() && !ws1984.isChecked() && !ws1961.isChecked()) {
mscore = mscore + 3;
}
EditText questionFive = (EditText) findViewById(R.id.question_5);
String questionFiveAnswer = questionFive.getText().toString();
if (questionFiveAnswer.equalsIgnoreCase(q5R) || questionFiveAnswer.equalsIgnoreCase(q5CR) || questionFiveAnswer.equalsIgnoreCase(q5Cal) ){
mscore = mscore + 1;
}
EditText enterName = (EditText) findViewById(R.id.name_entry);
String name = enterName.getText().toString();
Context context = getApplicationContext();
CharSequence text = name + " your score is: " + mscore + " points out of a possible 6 points";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
Make a Button in layout file like:
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"
android:onClick="calcScore"
android:id="#+id/button"/>
Now write your code in calcScore method in main activity like:
public void calcScore(View v)
{
int mscore ;
String q5R = "ripken";
String q5CR = "cal ripken";
String q5Cal = "cal";
EditText questionFive = (EditText) findViewById(R.id.question_5);
String questionFiveAnswer = questionFive.getText().toString();
if (questionFiveAnswer.equalsIgnoreCase(q5R) || questionFiveAnswer.equalsIgnoreCase(q5CR) || questionFiveAnswer.equalsIgnoreCase(q5Cal) ){
mscore = mscore + 1;
}
}
You need to initialized int mscore first.
// initialize
int mscore = 0;
// than add it
mscore += 1;
I am not sure what was wrong. But it seems to be working just fine now. I appreciate everybody for taking their time to help.

Equal function is not working in my java code

I have 2 textviews, 1 editbox and 1 button in my xml.
In my code, this line is not working:
if(c.equals(str)){
Toast.makeText(GameActivity.this, "Alright",Toast.LENGTH_LONG).show();
}
But next line (else statement) is working and In both cases (if & else statement) it shows else function toast ("Wrong").
Here is my code:
public class GameActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.game);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
Random r = new Random();
int i = r.nextInt(10 - 2) + 2;
tv.setText(i +"");
Random r1 = new Random();
int j = r1.nextInt((9 - 2) + 1) + 2;
tv2.setText(j +"");
int a = Integer.parseInt(tv.getText().toString());
int b = Integer.parseInt(tv2.getText().toString());
int result = a*b;
String str = String.valueOf(result);
EditText txt4 = (EditText) findViewById(R.id.editText1);
String c = txt4.getText().toString();
if(TextUtils.isEmpty(txt4.getText().toString())) {
txt4.setError("Please enter your answer");
return;
}
if(c.equals(str)){
Toast.makeText(GameActivity.this, "Alright",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(GameActivity.this, "wrong",Toast.LENGTH_LONG).show();
}
txt4.setText("");
}
});
}
Try this,
I got result
public class Test extends AppCompatActivity {
Button b1;
TextView t1,t2;
EditText e1;
int a,b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
b1 = (Button) findViewById(R.id.button2);
t1=(TextView) findViewById(R.id.textView4);
t2=(TextView) findViewById(R.id.textView5);
e1=(EditText) findViewById(R.id.editText);
Random r = new Random();
int i = r.nextInt(10 - 2) + 2;
t1.setText(i +"");
Random r1 = new Random();
int j = r1.nextInt((9 - 2) + 1) + 2;
t2.setText(j +"");
a = Integer.parseInt(t1.getText().toString());
b = Integer.parseInt(t2.getText().toString());
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int result = a*b;
String str = String.valueOf(result);
String c = e1.getText().toString();
if(TextUtils.isEmpty(c)) {
e1.setError("Please enter your answer");
return;
}
if(c.equals(str)){
Toast.makeText(Test.this, "Alright",Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(Test.this, "wrong",Toast.LENGTH_LONG).show();
}
e1.setText("");
}
});
}}
Instead of
String str = String.valueOf(result);
you should use
String str = Integer.toString(result);

How to disable all the buttons in the layout for a certain amount of time, java.NullPointerException

secondScreen.java
public class secondScreen extends Activity implements View.OnClickListener {
//drawables
int res[] = new int[] {R.drawable.brownbars,R.drawable.centeredorangedot, R.drawable.dots, R.drawable.greenlines, R.drawable.lightbulb, R.drawable.orangedots, R.drawable.orangelines, R.drawable.tree, R.drawable.yellow, R.drawable.yellowwithred, R.drawable.brownbars,R.drawable.centeredorangedot,
R.drawable.dots, R.drawable.greenlines, R.drawable.lightbulb, R.drawable.orangedots, R.drawable.orangelines, R.drawable.tree, R.drawable.yellow, R.drawable.yellowwithred};
int lay1, lay2, shuffleCount = 0, gameCount = 0;
ImageButton first, second;
LinearLayout layout;
ImageButton b1;
ImageButton b2;
ImageButton b3;
ImageButton b4;
ImageButton b5;
ImageButton b6;
ImageButton b7;
ImageButton b8;
ImageButton b9;
ImageButton b10;
ImageButton b11;
ImageButton b12;
ImageButton b13;
ImageButton b14;
ImageButton b15;
ImageButton b16;
ImageButton b17;
ImageButton b18;
ImageButton b19;
ImageButton b20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
Intent activityThatCalled = getIntent();
//initialize all buttons in game
b1 = (ImageButton) findViewById(R.id.b1);
b2 = (ImageButton) findViewById(R.id.b2);
b3 = (ImageButton) findViewById(R.id.b3);
b4 = (ImageButton) findViewById(R.id.b4);
b5 = (ImageButton) findViewById(R.id.b5);
b6 = (ImageButton) findViewById(R.id.b6);
b7 = (ImageButton) findViewById(R.id.b7);
b8 = (ImageButton) findViewById(R.id.b8);
b9 = (ImageButton) findViewById(R.id.b9);
b10 = (ImageButton) findViewById(R.id.b10);
b11 = (ImageButton) findViewById(R.id.b11);
b12 = (ImageButton) findViewById(R.id.b12);
b13 = (ImageButton) findViewById(R.id.b13);
b14 = (ImageButton) findViewById(R.id.b14);
b15 = (ImageButton) findViewById(R.id.b15);
b16 = (ImageButton) findViewById(R.id.b16);
b17 = (ImageButton) findViewById(R.id.b17);
b18 = (ImageButton) findViewById(R.id.b18);
b19 = (ImageButton) findViewById(R.id.b19);
b20 = (ImageButton) findViewById(R.id.b20);
iconRandomizer();
};
public void randomCheck(ImageButton btn, int image) {
if (gameCount < 2) {
gameCount++;
if (gameCount == 1) {
first = btn;
lay1 = image;
} else {
second = btn;
lay2 = image;
if (lay1 != lay2) {
ArrayList<View> touchables = layout.getTouchables();
for(View touchable : touchables) {
if (touchable instanceof Button)
((Button) touchable).setEnabled(false);
}
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
first.setImageResource(R.color.material_blue_grey_800);
second.setImageResource(R.color.material_blue_grey_800);
first.setEnabled(true);
second.setEnabled(true);
}
}, 1000);
}
gameCount = 0;
}
}
}
static void shuffleArray(int[] ar)
{
Random rnd = new Random();
for (int i = ar.length - 1; i > 0; i--)
{
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
public void iconRandomizer() {
for (int i = 0; i < 10; i++)
System.out.println(res[i]);
shuffleArray(res);
for (int i = 0; i < 10; i++)
System.out.println(res[i]);
b1.setOnClickListener(this);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
b4.setOnClickListener(this);
b5.setOnClickListener(this);
b6.setOnClickListener(this);
b7.setOnClickListener(this);
b8.setOnClickListener(this);
b9.setOnClickListener(this);
b10.setOnClickListener(this);
b11.setOnClickListener(this);
b12.setOnClickListener(this);
b13.setOnClickListener(this);
b14.setOnClickListener(this);
b15.setOnClickListener(this);
b16.setOnClickListener(this);
b17.setOnClickListener(this);
b18.setOnClickListener(this);
b19.setOnClickListener(this);
b20.setOnClickListener(this);
}
public void onClick(View v){
switch (v.getId()){
case R.id.b1:
b1.setImageResource(res[0]);
b1.setEnabled(false);
randomCheck(b1, res[0]);
break;
case R.id.b2:
b2.setImageResource(res[1]);
b2.setEnabled(false);
randomCheck(b2,res[1]);
break;
case R.id.b3:
b3.setImageResource(res[2]);
b3.setEnabled(false);
randomCheck(b3, res[2]);
break;
case R.id.b4:
b4.setImageResource(res[3]);
b4.setEnabled(false);
randomCheck(b4, res[3]);
break;
case R.id.b5:
b5.setImageResource(res[4]);
b5.setEnabled(false);
randomCheck(b5, res[4]);
break;
case R.id.b6:
b6.setImageResource(res[5]);
b6.setEnabled(false);
randomCheck(b6, res[5]);
break;
case R.id.b7:
b7.setImageResource(res[6]);
b7.setEnabled(false);
randomCheck(b7, res[6]);
break;
case R.id.b8:
b8.setImageResource(res[7]);
b8.setEnabled(false);
randomCheck(b8, res[7]);
break;
case R.id.b9:
b9.setImageResource(res[8]);
b9.setEnabled(false);
randomCheck(b9, res[8]);
break;
case R.id.b10:
b10.setImageResource(res[9]);
b10.setEnabled(false);
randomCheck(b10, res[9]);
break;
case R.id.b11:
b11.setImageResource(res[10]);
b11.setEnabled(false);
randomCheck(b11, res[10]);
break;
case R.id.b12:
b12.setImageResource(res[11]);
b12.setEnabled(false);
randomCheck(b12, res[11]);
case R.id.b13:
b13.setImageResource(res[12]);
b13.setEnabled(false);
randomCheck(b13, res[12]);
break;
case R.id.b14:
b14.setImageResource(res[13]);
b14.setEnabled(false);
randomCheck(b14, res[13]);
case R.id.b15:
b15.setImageResource(res[14]);
b15.setEnabled(false);
randomCheck(b15, res[14]);
break;
case R.id.b16:
b16.setImageResource(res[15]);
b16.setEnabled(false);
randomCheck(b16, res[15]);
break;
case R.id.b17:
b17.setImageResource(res[16]);
b17.setEnabled(false);
randomCheck(b17, res[16]);
break;
case R.id.b18:
b18.setImageResource(res[17]);
b18.setEnabled(false);
randomCheck(b18, res[17]);
break;
case R.id.b19:
b19.setImageResource(res[18]);
b19.setEnabled(false);
randomCheck(b19, res[18]);
break;
case R.id.b20:
b20.setImageResource(res[19]);
b20.setEnabled(false);
randomCheck(b20, res[19]);
break;
}
}
//}
}
error log:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.util.ArrayList android.widget.LinearLayout.getTouchables()' on a null object reference
at eagle.abhishekravi.abhishek.eagle.secondScreen.randomCheck(secondScreen.java:111)
at eagle.abhishekravi.abhishek.eagle.secondScreen.onClick(secondScreen.java:232)
at android.view.View.performClick(View.java:4780)
at android.view.View$PerformClick.run(View.java:19866)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
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:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
I am making a memory match game, and I need to disable all buttons after the second Button is tapped. Then after the check is complete, it will resume normally. I have got the checks to work but still need the buttons disabled in this case where user taps another Button between the 1 second pause.Let me know if you need more information. Thanks!!
Based on the information provided by the error message, it looks like layout is null. If you're still having trouble, the code where layout is being set would be very helpful.
Your layout should be accessed via R.layout.my_layout.

Timer in Java program, countdown

I want to implement a java countdown timer for my Android program but I don't know how should I do it. It should count the time from let's say 60 to 0 and at the end the program should end but the user needs to see how much time is left, so the timer should be visible all time. I managed to implement a "timer" for how long the game is accepting input but I don't understand how should I make a count down system. Here is my source file for the program that I made. Hope you guys can help me thanks in advance,
package com.example.mathcalcplus;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class PlayGame extends Activity implements OnClickListener {
ImageView image;
TextView question, answer, score, timeLeft;
int difLevel, operator1, operator2, finalAnswer=0, operation, scoreCount = 0, userAnswer=0;
final private int add = 0, sub = 1, div = 3, mul = 2;
String[] getOperation = { "+", "-", "*", "/"};
Button btn1, btn2, btn3, btn4, btn5, btn6, btn7, btn8, btn9, btn0, btnClear, btnEnter;
Random rand;
String getQuestion, userInput;
long start;
long end;
boolean running = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.play_game);
btn1 = (Button) findViewById(R.id.btn1);
btn2 = (Button) findViewById(R.id.btn2);
btn3 = (Button) findViewById(R.id.btn3);
btn4 = (Button) findViewById(R.id.btn4);
btn5 = (Button) findViewById(R.id.btn5);
btn6 = (Button) findViewById(R.id.btn6);
btn7 = (Button) findViewById(R.id.btn7);
btn8 = (Button) findViewById(R.id.btn8);
btn9 = (Button) findViewById(R.id.btn9);
btn0 = (Button) findViewById(R.id.btn0);
btnClear = (Button) findViewById(R.id.clear);
btnEnter = (Button) findViewById(R.id.enter);
question = (TextView) findViewById(R.id.question);
answer = (TextView) findViewById(R.id.answer);
score = (TextView) findViewById(R.id.score);
image = (ImageView) findViewById(R.id.response);
timeLeft = (TextView) findViewById(R.id.timeLeft);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
btn7.setOnClickListener(this);
btn8.setOnClickListener(this);
btn9.setOnClickListener(this);
btn0.setOnClickListener(this);
btnClear.setOnClickListener(this);
btnEnter.setOnClickListener(this);
rand = new Random();
Bundle extras = getIntent().getExtras();
if(extras != null)
{
int passedLevel = extras.getInt("level", -1);
if(passedLevel>=0) difLevel = passedLevel;
}
image.setVisibility(View.INVISIBLE);
choseQuestion();
start = System.currentTimeMillis();
end = start + 30*1000;
}
public void run(){
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.enter:
String getUserAnswer = answer.getText().toString();
if (!getUserAnswer.endsWith("?")){
userAnswer = Integer.parseInt(getUserAnswer.substring(1));
if (userAnswer == finalAnswer){
scoreCount++;
score.setText("Score=" + " " + scoreCount);
image.setImageResource(R.drawable.tick);
image.setVisibility(View.VISIBLE);
}
else{
scoreCount = 0;
score.setText("Score=" + " " + scoreCount);
image.setImageResource(R.drawable.cross);
image.setVisibility(View.VISIBLE);
}
finalAnswer =0;
choseQuestion();
getUserAnswer = "";
userAnswer = 0;
break;
}
else{
break;
}
case R.id.clear:
answer.setText("=?");
break;
default:
if (System.currentTimeMillis() < end){
int enteredNum = Integer.parseInt(v.getTag().toString());
if(answer.getText().toString().endsWith("?"))
answer.setText("="+enteredNum);
else
answer.append(""+enteredNum);
}
}
}
private void choseQuestion() {
answer.setText("=?");
operation = rand.nextInt(getOperation.length);
operator1 = getNumbers();
operator2 = getNumbers();
if (operation == sub){
while (operator2 > operator1){
operator1 = getNumbers();
operator2 = getNumbers();
}
}
if (operation == div){
while((double)operator1%(double)operator2 > 0 || (operator2 > operator1)){
operator1 = getNumbers();
operator2 = getNumbers();
}
}
switch(operation){
case add:
finalAnswer = operator1 + operator2;
break;
case sub:
finalAnswer = operator1 - operator2;
break;
case div:
finalAnswer = operator1 / operator2;
break;
case mul:
finalAnswer = operator1 * operator2;
break;
}
question.setText(operator1 + getOperation[operation] +operator2);
timeLeft.setText("Time :" + end);
}
private int getNumbers(){
int n = rand.nextInt(100) + 1;`enter code here`
return n;
}
}
Declare your CountDownTimer and you set the time range in miliseconds.
Call countDown method and your CountDownTimer is ready to go!
private final static int time = 10000;
private CountDownTimer timerCount;
public void countDown(){
countDown = (TextView) findViewById(R.id.countdown);
timerCount = new CountDownTimer(time, 1000) {
public void onTick(long millisUntilFinished) {
long tmp = millisUntilFinished / 1000;
countDown.setText(tmp + "");
}
public void onFinish() {
// Do your stuff
countDown.setText("0");
}
}.start();
}
And your .xml file
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/questionList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/menu"
android:orientation="vertical"
android:weightSum="4" >
<TextView
android:id="#+id/title"
android:layout_gravity="center"
android:layout_width="wrap_content"
android:textSize="14sp"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/countdown"
android:layout_gravity="right"
android:layout_width="30dp"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="numberDecimal" >
<requestFocus />
</TextView>
new CountDownTimer(60000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
//here you can have your logic to set text to edittext
}
public void onFinish() {
mTextField.setText("done!");
}
}.start();
Here is the example.
Refer to this link for countdowntimer.

Programmatically scroll a ScrollView to focus on a Button or a view - Android

I have an Activity that has a ScrollView of 125 buttons. The 125 buttons are Levels in my game that slowly get unlocked (think of Candy Crush Saga). Right now if the user is on the level, let's say, 88 of 125 then the user has to manually scroll all the way down to button 88.
My question is, how would I make it so that when the Activity loads, it automatically scrolls down and centers the ScrollView on a certain button?
Below is my code of how the buttons are created and populated programmatically.
ScrollView scrollView;
#Override
public void onCreate(Bundle savedInstanceState) {
LinearLayout lay = (LinearLayout)findViewById(R.id.linearlayout);
for(int i = 0; i < 125; i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
params.weight = 1;
params.gravity = Gravity.CENTER;
if(i == 0) {
TextView textview = new TextView(this);
textview.setLayoutParams(params);
textview.setTextSize(15);
textview.setText(c.getResources().getString(R.string.l1to5));
TextView textview2 = new TextView(this);
textview2.setLayoutParams(params);
textview.setTextSize(15);
textview2.setText(c.getResources().getString(R.string.goal100));
TextView textview3 = new TextView(this);
textview3.setLayoutParams(params);
textview.setTextSize(15);
textview3.setText(c.getResources().getString(R.string.catRandom));
if((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_LARGE) {
textview.setTextSize(22);
textview2.setTextSize(22);
textview3.setTextSize(22);
} else if((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_XLARGE) {
textview.setTextSize(22);
textview2.setTextSize(22);
textview3.setTextSize(22);
}
lay.addView(textview);
lay.addView(textview2);
lay.addView(textview3);
View ruler = new View(this);
ruler.setBackgroundColor(0xFFC2BEBF);
lay.addView(ruler, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
}
if(i == 5) {
// ....
}
Button button = new Button(this);
int _id = getResources().getIdentifier("b" + (i + 1), "id", this.getPackageName());
button.setTag(_id);
button.setLayoutParams(params);
if((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_LARGE) {
button.setTextSize(22);
} else if((getResources().getConfiguration().screenLayout &
Configuration.SCREENLAYOUT_SIZE_MASK) ==
Configuration.SCREENLAYOUT_SIZE_XLARGE) {
button.setTextSize(22);
}
button.setText("Level " + (i + 1));
final int x = i + 1;
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
singleton.setLevelJustPlayed(x);
// ...
} else {
// ...
Intent intent = new Intent(Levels.this, Categories.class);
startActivity(intent);
}
}
});
lay.addView(button);
if(singleton.getLevel() >= (i + 1)) {
button.setEnabled(true);
} else {
button.setEnabled(false);
}
}
// end the onCreate() method
try
yourScrollView.scrollTo(0, (int) button.getY());
For Kotlin user
your_scrollview.post( { your_scrollview.scrollTo(0, your_view_inside_SV.getY().toInt()) })

Categories

Resources