EDIT*: FOR hovanessyan
private String getWheelValue(int id) {
WheelView wheel = getWheel(R.id.passw_1);
int index = wheel.getCurrentItem();
((ArrayWheelAdapter<String>) wheel.getViewAdapter()).getItemText(index).toString();
final String values = getWheelValue(R.id.passw_1) + " " + getWheelValue(R.id.passw_2) + " " + getWheelValue(R.id.passw_3);
First, your code will not compile because of :
initWheel(R.id.passw_2, new String[] { "Are", "Going", ""Went });
initWheel(R.id.passw_3, new String[] { "There", "Here", ""Away });
Your button is not clicking, because in the presented code, you never call getWheelValue()
You should get reference to your button and attach onClickListener, in your onCreate() method.
You should start your changes with something like...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.passw_layout);
initWheel(R.id.passw_1, new String[] { "You", "Me", "Us" });
initWheel(R.id.passw_2, new String[] { "Are", "Going", "Went" });
initWheel(R.id.passw_3, new String[] { "There", "Here", "Away" });
Button mix = (Button) findViewById(R.id.btn_mix);
mix.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mixWheel(R.id.passw_1);
mixWheel(R.id.passw_2);
mixWheel(R.id.passw_3);
}
});
Button share = (Button) findViewById(R.id.btn_share);
share.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// call some other methods before that I guess...
String values = getAllWheelValues();
startActivity(createEmailIntent(values));
}
});
}
private Intent createEmailIntent(String values) {
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("text/plain");
emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, getResources().getString(R.string.Subject));
emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, values);
return emailIntent;
}
EDIT:
I think you should have something like, and call getAllWheelValues() in the onClick() of share button:
private String getAllWheelValues() {
String val1 = getWheelValue(R.id.passw_1);
String val2 = getWheelValue(R.id.passw_2);
String val3 = getWheelValue(R.id.passw_3);
return val1+" "+val2+" "+val3;
}
private String getWheelValue(int id) {
WheelView wheel = getWheel(id);
int index = wheel.getCurrentItem();
return ((ArrayWheelAdapter<String>) wheel.getViewAdapter()).getItemText(index).toString();
}
Related
I'm making a truth or dare app and i need a code that show the user input one by one every time i hit a button
I try somethink i watch in youtube.
So here's the activity that the user input names for the players playing.
public class NameInput1Activity extends AppCompatActivity {
Button SBtn;
Button RTMBtn;
EditText PN1;
EditText PN2;
EditText PN3;
EditText PN4;
EditText PN5;
EditText PN6;
EditText PN7;
EditText PN8;
EditText PN9;
EditText PN10;
String PI1;
String PI2;
String PI3;
String PI4;
String PI5;
String PI6;
String PI7;
String PI8;
String PI9;
String PI10;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_name_input1);
SBtn = findViewById(R.id.SBtn);
RTMBtn = findViewById(R.id.RTMBtn);
PN1 = findViewById(R.id.player1NameInput);
PN2 = findViewById(R.id.player2NameInput);
PN3 = findViewById(R.id.player3NameInput);
PN4 = findViewById(R.id.player4NameInput);
PN5 = findViewById(R.id.player5NameInput);
PN6 = findViewById(R.id.player6NameInput);
PN7 = findViewById(R.id.player7NameInput);
PN8 = findViewById(R.id.player8NameInput);
PN9 = findViewById(R.id.player9NameInput);
PN10 = findViewById(R.id.player10NameInput);
SBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent PlayConf = new Intent(NameInput1Activity.this,PlayConf.class);
PI1 = PN1.getText().toString();
PI2 = PN2.getText().toString();
PI3 = PN3.getText().toString();
PI4 = PN4.getText().toString();
PI5 = PN5.getText().toString();
PI6 = PN6.getText().toString();
PI7 = PN7.getText().toString();
PI8 = PN8.getText().toString();
PI9 = PN9.getText().toString();
PI10 = PN10.getText().toString();
PlayConf.putExtra("Player1",PI1);
PlayConf.putExtra("Player2",PI2);
PlayConf.putExtra("Player3",PI3);
PlayConf.putExtra("Player4",PI4);
PlayConf.putExtra("Player5",PI5);
PlayConf.putExtra("Player6",PI6);
PlayConf.putExtra("Player7",PI7);
PlayConf.putExtra("Player8",PI8);
PlayConf.putExtra("Player9",PI9);
PlayConf.putExtra("Player10",PI10);
startActivity(PlayConf);
}
});
RTMBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent RTMBtn = new Intent(NameInput1Activity.this, MainActivity.class);
PN1.setText("");
PN1.setHint("Enter a name");
PN2.setText("");
PN2.setHint("Enter a name");
PN3.setText("");
PN3.setHint("Enter a name");
PN4.setText("");
PN4.setHint("Enter a name");
PN5.setText("");
PN5.setHint("Enter a hint");
PN6.setText("");
PN6.setHint("Enter a hint");
PN7.setText("");
PN7.setHint("Enter a hint");
PN8.setText("");
PN8.setHint("Enter a hint");
PN9.setText("");
PN9.setHint("Enter a hint");
PN10.setText("");
PN10.setHint("Enter a hint");
startActivity(RTMBtn);
}
});
}
}
So i have some 'edittext' that the player input the names and a 'OnClickListener' that passe's the input to 'PlayConf' Activity.
That's the 'PlayConf' Activity:
public class PlayConf extends AppCompatActivity {
Button AddMoreBtn;
Button MoveToToD;
Button RTMBtn;
String PI1;
String PI2;
String PI3;
String PI4;
String PI5;
String PI6;
String PI7;
String PI8;
String PI9;
String PI10;
TextView PTV1;
TextView PTV2;
TextView PTV3;
TextView PTV4;
TextView PTV5;
TextView PTV6;
TextView PTV7;
TextView PTV8;
TextView PTV9;
TextView PTV10;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(com.example.myapplication.R.layout.activity_play_conf);
AddMoreBtn = findViewById(R.id.AddMoreBtn);
MoveToToD = findViewById(R.id.MoveToToD);
RTMBtn =findViewById(R.id.RTMBtn);
PTV1 = findViewById(R.id.Player1NameConf);
PTV2 = findViewById(R.id.Player2NameConf);
PTV3 = findViewById(R.id.Player3NameConf);
PTV4 = findViewById(R.id.Player4NameConf);
PTV5 = findViewById(R.id.Player5NameConf);
PTV6 = findViewById(R.id.Player6NameConf);
PTV7 = findViewById(R.id.Player7NameConf);
PTV8 = findViewById(R.id.Player8NameConf);
PTV9 = findViewById(R.id.Player9NameConf);
PTV10 = findViewById(R.id.Player10NameConf);
PI1 = getIntent().getExtras().getString("Player1");
PI2 = getIntent().getExtras().getString("Player2");
PI3 = getIntent().getExtras().getString("Player3");
PI4 = getIntent().getExtras().getString("Player4");
PI5 = getIntent().getExtras().getString("Player5");
PI6 = getIntent().getExtras().getString("Player6");
PI7 = getIntent().getExtras().getString("Player7");
PI8 = getIntent().getExtras().getString("Player8");
PI9 = getIntent().getExtras().getString("Player9");
PI10 = getIntent().getExtras().getString("Player10");
PTV1.setText(PI1);
PTV2.setText(PI2);
PTV3.setText(PI3);
PTV4.setText(PI4);
PTV5.setText(PI5);
PTV6.setText(PI6);
PTV7.setText(PI7);
PTV8.setText(PI8);
PTV9.setText(PI9);
PTV10.setText(PI10);
AddMoreBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent AddMore = new Intent(PlayConf.this,
NameInput1Activity.class);
startActivity(AddMore);
}
});
RTMBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent RTMBtn = new Intent(PlayConf.this, MainActivity.class);
PTV1.setText("");
PTV2.setText("");
PTV3.setText("");
PTV4.setText("");
PTV5.setText("");
PTV6.setText("");
PTV7.setText("");
PTV8.setText("");
PTV9.setText("");
PTV10.setText("");
startActivity(RTMBtn);
}
});
MoveToToD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent MoveToToD = new Intent(PlayConf.this, TruthOrDare.class);
MoveToToD.putExtra("Player1",PI1);
MoveToToD.putExtra("Player1",PI2);
MoveToToD.putExtra("Player1",PI3);
MoveToToD.putExtra("Player1",PI4);
MoveToToD.putExtra("Player1",PI5);
MoveToToD.putExtra("Player1",PI6);
MoveToToD.putExtra("Player1",PI7);
MoveToToD.putExtra("Player1",PI8);
MoveToToD.putExtra("Player1",PI9);
MoveToToD.putExtra("Player1",PI10);
startActivity(MoveToToD);
}
});
}
}
That's the 'PlayConf' Activity, it shows the input so the user see all the input's he enter.So i get the input from the previous Activity 'NameInput1Activity' and make another String from the input 'PI1'.Then i pass the input to the 'TruthOrDare' Activity with the Button 'MoveToToD'.
So that's where i have the problem the 'Truth or Dare' Activity:
public class TruthOrDare extends AppCompatActivity {
String PI1;
String PI2;
String PI3;
String PI4;
String PI5;
String PI6;
String PI7;
String PI8;
String PI9;
String PI10;
TextView PlayerView;
Integer TurnCount = 1;
Button RTMBtn;
Button Darebtn;
Button Truthbtn;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_truth_or_dare);
PI1 = getIntent().getExtras().getString("Player1");
PI2 = getIntent().getExtras().getString("Player2");
PI3 = getIntent().getExtras().getString("Player3");
PI4 = getIntent().getExtras().getString("Player4");
PI5 = getIntent().getExtras().getString("Player5");
PI6 = getIntent().getExtras().getString("Player6");
PI7 = getIntent().getExtras().getString("Player7");
PI8 = getIntent().getExtras().getString("Player8");
PI9 = getIntent().getExtras().getString("Player9");
PI10 = getIntent().getExtras().getString("Player10");
PlayerView = findViewById(R.id.PlayerNameTextView);
RTMBtn = findViewById(R.id.RTMBtn);
RTMBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent RTMBtn = new Intent(TruthOrDare.this, MainActivity.class);
startActivity(RTMBtn);
}
});
Truthbtn = findViewById(R.id.TruthBtn);
Darebtn = findViewById(R.id.Darebtn);
Truthbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent Truth = new Intent(TruthOrDare.this, TruthActivity.class);
TurnCount++;
startActivity(Truth);
}
});
Darebtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TurnCount++;
}
});
}
public void ResetCount(View view) {
TurnCount = 1;
}
public void TurnCountIfElse(View view) {
if (TurnCount == 1) {
PlayerView.setText(PI1);
} else if (TurnCount == 2) {
PlayerView.setText(PI2);
} else if (TurnCount == 3) {
PlayerView.setText(PI3);
} else if (TurnCount == 4) {
PlayerView.setText(PI4);
} else if (TurnCount == 5) {
PlayerView.setText(PI5);
} else if (TurnCount == 6) {
PlayerView.setText(PI6);
} else if (TurnCount == 7) {
PlayerView.setText(PI7);
} else if (TurnCount == 8) {
PlayerView.setText(PI8);
} else if (TurnCount == 9) {
PlayerView.setText(PI9);
} else if (TurnCount == 10) {
PlayerView.setText(PI10);
}
else {
TurnCount = 1;
}
}
}
So what i do here is i make an 'onclicklistener' for the 'Truthbtn'
that add 1 to 'TurnCount' so the when i click the 'TurnCount' Value equals 2
so is set the textview to 'PI2' but instead of that it goes to the last 'else if' and set textview text to 'PI10'
IF YOU NEED ANY OTHER INFO LIKE XML'S JUST SAY IT PLS.
Dear Friend You made minor mistake during implementation. You send Same key value During intent on MoveToToD Button Click.
You use Same key Value Player1 for all player list value.That's the actual problem.So kindly Change Your MoveToToD click method and Write Below Code.
MoveToToD.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent MoveToToD = new Intent(PlayConf.this, TruthOrDare.class);
MoveToToD.putExtra("Player1",PI1);
MoveToToD.putExtra("Player2",PI2);
MoveToToD.putExtra("Player3",PI3);
MoveToToD.putExtra("Player4",PI4);
MoveToToD.putExtra("Player5",PI5);
MoveToToD.putExtra("Player6",PI6);
MoveToToD.putExtra("Player7",PI7);
MoveToToD.putExtra("Player8",PI8);
MoveToToD.putExtra("Player9",PI9);
MoveToToD.putExtra("Player10",PI10);
startActivity(MoveToToD);
}
});
I am making a math quiz where a mathematical question will be asked in the form of a formula. I put my questions in an ArrayList:
public class DEasy extends AppCompatActivity {
private TextView countLabel;
private TextView questionLabel;
private Button answerBtn1;
private Button answerBtn2;
private Button answerBtn3;
private Button answerBtn4;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
static final private int QUIZ_COUNT = 10;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
{"x", "1", "0", "x", "-1"},
{"x²", "2x", "x", "2/x²", "2x²"},
{"64", "0", "1", "64", "8"},
{"x² + 5x", "2x + 5", "7x", "2x", "½x + 5"},
{"19x", "19", "x", "0", "x + 19"},
{"642", "34", "97", "5x-2", "1"}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deasy);
countLabel = (TextView) findViewById(R.id.countLabel);
questionLabel = (TextView) findViewById(R.id.questionLabel);
answerBtn1 = (Button) findViewById(R.id.answerBtn1);
answerBtn2 = (Button) findViewById(R.id.answerBtn2);
answerBtn3 = (Button) findViewById(R.id.answerBtn3);
answerBtn4 = (Button) findViewById(R.id.answerBtn4);
for (int i = 0; i < quizData.length; i++) {
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]);
tmpArray.add(quizData[i][1]);
tmpArray.add(quizData[i][2]);
tmpArray.add(quizData[i][3]);
tmpArray.add(quizData[i][4]);
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz() {
countLabel.setText( getString(R.string.question) + " " + quizCount + ".");
Random random = new Random();
int randomNum = random.nextInt(quizArray.size());
ArrayList<String> quiz = quizArray.get(randomNum);
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
quiz.remove(0);
Collections.shuffle(quiz);
answerBtn1.setText(quiz.get(0));
answerBtn2.setText(quiz.get(1));
answerBtn3.setText(quiz.get(2));
answerBtn4.setText(quiz.get(3));
quizArray.remove(randomNum);
}
public void checkAnswer(View view){
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
if (btnText.equals(rightAnswer)){
alertTitle = "Correct";
rightAnswerCount++;
}
else {
alertTitle = "Wrong";
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage("Answer: " + rightAnswer);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (quizCount == QUIZ_COUNT){
Intent intent = new Intent(getApplicationContext(), DResult.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
}
else{
quizCount++;
showNextQuiz();
}
}
});
builder.setCancelable(false);
builder.show();
}
}
As you can see I tried to make the formula x^2, this wil not be shown as x with a small exponent 2 but as x^2. This x^2 is not what I want. How can I used for example html in this arraylist to achieve this goal. Or is there another way?
Thanks aton!
Here in replacement of "^" we can use this: "∧".
So now replace code at where you accessing this string array in Adapter as:
Html.fromHtml(quizArray[][])
Thanks and happy coding
EDITED:
Here change it as:
questionLabel.setText(Htm.fromHtml(quiz.get(0)));
Just it will work
I am working on a simple Grading app project with 3 activities, the first one is storing some data in a database and i am replicating that data in both the first activity and the third activity.
The second activity is doing an average calculation and showing the results on that same page, but i want that result to also be shown on the third page. I tried using intents but when i click the button to go to the third page it forces close. What am i doing wrong.
I am trying to show this results in a textview
This is the Second Activity code:
public class AverageActivity extends AppCompatActivity {
EditText editmanner, editinstances, editshortstance, editstrikes, editboxingskills, editknocks, editkicks, editResults;
Button btnResults, btnnewresults;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.average_page);
editmanner = (EditText) findViewById(R.id.editText8);
editinstances = (EditText) findViewById(R.id.editText9);
editshortstance = (EditText) findViewById(R.id.editText10);
editstrikes = (EditText) findViewById(R.id.editText11);
editboxingskills = (EditText) findViewById(R.id.editText12);
editknocks = (EditText) findViewById(R.id.editText13);
editkicks = (EditText) findViewById(R.id.editText14);
editResults = (EditText) findViewById(R.id.editText15);
btnResults = (Button) findViewById(R.id.button10);
btnnewresults = (Button) findViewById(R.id.botonresultnuevo);
btnResults.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int first;
if (editmanner.getText().toString().equals("")) {
first = 0;
} else {
first = Integer.valueOf(editmanner.getText().toString());
}
int second;
if (editinstances.getText().toString().equals("")) {
second = 0;
} else {
second = Integer.valueOf(editinstances.getText().toString());
}
int third;
if (editshortstance.getText().toString().equals("")) {
third = 0;
} else {
third = Integer.valueOf(editshortstance.getText().toString());
}
int fourth;
if (editstrikes.getText().toString().equals("")) {
fourth = 0;
} else {
fourth = Integer.valueOf(editstrikes.getText().toString());
}
int fifth;
if (editboxingskills.getText().toString().equals("")) {
fifth = 0;
} else {
fifth = Integer.valueOf(editboxingskills.getText().toString());
}
int sixth;
if (editknocks.getText().toString().equals("")) {
sixth = 0;
} else {
sixth = Integer.valueOf(editknocks.getText().toString());
}
int seventh;
if (editkicks.getText().toString().equals("")) {
seventh = 0;
} else {
seventh = Integer.valueOf(editkicks.getText().toString());
}
int results;
first = Integer.parseInt(editmanner.getText().toString());
second = Integer.parseInt(editinstances.getText().toString());
third = Integer.parseInt(editshortstance.getText().toString());
fourth = Integer.parseInt(editstrikes.getText().toString());
fifth = Integer.parseInt(editboxingskills.getText().toString());
sixth = Integer.parseInt(editknocks.getText().toString());
seventh = Integer.parseInt(editkicks.getText().toString());
results = (first + second + third + fourth + fifth + sixth + seventh) / 7;
editResults.setText(String.valueOf(results));
}
});
}
public void knowtheresults(View view) {
switch (view.getId()) {
case R.id.botonresultnuevo:
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
Bundle miBundle = new Bundle();
miBundle.putString("nombre", editResults.getText().toString());
miintent.putExtras(miBundle);
startActivity(miintent);
break;
}
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Summary")) {
Intent intent = new Intent(this, ResultActivity.class);
startActivity(intent);
}
}
}
And This is the Third activity code:
public class ResultActivity extends Activity {
TextView texto;
DatabaseHelper mDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_page);
texto = (TextView) findViewById(R.id.editText15);
Bundle mibundle=this.getIntent().getExtras();
if(mibundle!=null){
String dato = mibundle.getString("nombre");
texto.setText(dato);
}
mDatabaseHelper = new DatabaseHelper(this);
displayDatabaseInfo();
}
private void displayDatabaseInfo() {
// To access our database, we instantiate our subclass of SQLiteOpenHelper
// and pass the context, which is the current activity.
DatabaseHelper mDbHelper = new DatabaseHelper(this);
// Create and/or open a database to read from it
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Perform this raw SQL query "SELECT * FROM pets"
// to get a Cursor that contains all rows from the pets table.
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
TextView displayView = findViewById(R.id.textViewR1);
try {
displayView.setText("The Student...\n\n");
displayView.append(COL1 + "--" +
COL2 + "--" +
COL4 +
"\n");
// Figure out the index
int idColumnIndex = cursor.getColumnIndex(COL1);
int nameColumnIndex = cursor.getColumnIndex(COL2);
int rankColumnIndex = cursor.getColumnIndex(COL4);
while (cursor.moveToNext()) {
int currentID = cursor.getInt(idColumnIndex);
String currentName = cursor.getString(nameColumnIndex);
String currenRank = cursor.getString(rankColumnIndex);
displayView.append(currentID + "--" +
currentName + "--" +
currenRank + "\n");
}
} finally {
// Always close the cursor when you're done reading from it. This releases all its
// resources and makes it invalid.
cursor.close();
}
}
public void knowtheresults(View view) {
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Start Page")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (button_text.equals("Back...")) {
Intent intent = new Intent(this, AverageActivity.class);
startActivity(intent);
}
}
}
Remove Bundle from your code and use following code
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
miintent.putString("nombre", editResults.getText().toString());
startActivity(miintent);
In you third Activity
String number = getIntent().getStringExtra("nombre");
I am trying to save and store data in an android app using java. At the moment the data will not save and it causes my app to crash. Can anyone make any suggestions to my code? Part of my page includes a total budget and I am difficulty storing and saving the total budget.
public class Summary extends Activity implements TextWatcher, View.OnClickListener
{
DecimalFormat df = new DecimalFormat("£0.00");
int noOfGifts, giftsPurchased;
double cost;
EditText budgetEntered;
double savedBudget = 0;
String budgetString;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.summary);
budgetEntered = (EditText) findViewById(R.id.s2TotalBudget);
budgetEntered.addTextChangedListener(this);
Button saveBudget = (Button) findViewById(R.id.s2ViewList);
saveBudget.setOnClickListener(saveButtonListener);
if(savedBudget != 0)
{
saveBudget.setText(budgetString);
}
Bundle passedInfo = getIntent().getExtras();
if (passedInfo != null)
{
cost = passedInfo.getDouble("cost");
noOfGifts = passedInfo.getInt("noOfGifts");
giftsPurchased = passedInfo.getInt("giftsPurchased");
}
Button logoutButton = (Button) findViewById(R.id.s2LogoutButton);
logoutButton.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, MainActivity.class);
startActivity(myIntent);
}
});
Button viewList = (Button) findViewById(R.id.s2ViewList);
viewList.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent myIntent = new Intent(Summary.this, GiftList.class);
startActivity(myIntent);
}
});
String [][] summary = {{"Number of Presents to buy: ", (noOfGifts + "")},
{"Number of Presents bought:", (giftsPurchased + "")},
{"Cost: £", (cost + "")},
{"Budget: £", "50"}};
String passedBudget=null;
//convert totalPresents to double from String
String tempPresents = summary[0][1];
int presents = Integer.parseInt(tempPresents);
//convert presentsBought to double from String
String tempBought = summary[1][1];
int presentsToBuy = Integer.parseInt(tempBought);
//Number of presents
TextView s2PresentResult = (TextView) findViewById(R.id.s2PresentsResult);
s2PresentResult.setText(summary[0][1]);
//Number of presents to buy
TextView s2PresentsBuyResult = (TextView) findViewById(R.id.s2PresntsBuyResult);
s2PresentsBuyResult.setText((noOfGifts - giftsPurchased) + "");
Bundle passedId = getIntent().getExtras();
if (passedId != null)
{
passedBudget = passedId.getString("Enter Budget");
}
//EditText s2TotalBudget = (EditText) findViewById(R.id.s2TotalBudget);
//s2TotalBudget .addTextChangedListener((android.text.TextWatcher) this);
//s2TotalBudget .setText(passedBudget, TextView.BufferType.EDITABLE);
//Number of people
//TextView s2TotalBudget = (TextView) findViewById(R.id.s2TotalBudget);
//s2TotalBudget.setText("Enter budget");
//Number of people
TextView s2TotalCost = (TextView) findViewById(R.id.s2TotalCost);
s2TotalCost.setText(df.format(Double.parseDouble(summary[2][1])));
//Output if over or under budget
TextView s2CalculateOverBudget = (TextView) findViewById(R.id.s2CalculateOverBudget);
//convert totalCost to double from String
String temp = summary[2][1];
double totalCost = Double.parseDouble(temp);
//convert totalBudget to double from String
String tempTwo = "14";
double totalBudget = Double.parseDouble(tempTwo);
if((totalCost>totalBudget)&&(totalBudget!=0))
{
s2CalculateOverBudget.setTextColor(Color.rgb(209,0,0));
s2CalculateOverBudget.setText("You are over budget");
}
else if(totalBudget==0){
s2CalculateOverBudget.setText("");
}
else {
s2CalculateOverBudget.setText("You are within budget");
}
}
public View.OnClickListener saveButtonListener = new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if(budgetEntered.getText().length()>0)
{
budgetString = budgetEntered.getText().toString();
}
}
};
public void onClick(View v)
{
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
}
#Override
public void afterTextChanged(Editable s)
{
this it the best way to store and load value in Android:
save values: (put this where you want to save the values, for example in the onStop or onPause method. Or, in your case, in the onClick method)
SharedPreferences settings = getSharedPreferences("MyPref", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("testValue", value);
editor.commit();
load values:
SharedPreferences settings = getSharedPreferences("MyPref", 0);
value = settings.getInt("testValue", defValue);
I have written a class inside one activity to display a hh:mm:ss timer in my activity:
This is code of the class designed to show the timer:
//class to display on screen timer
class ShowTimer
{
long mMilliseconds = 120000;
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("HH:mm:ss");
CountDownTimer mCountDownTimer = new CountDownTimer(mMilliseconds, 1000) {
#Override
public void onFinish() {
mTextView.setText(mSimpleDateFormat.format(0));
}
public void onTick(long millisUntilFinished) {
mTextView.setText(mSimpleDateFormat.format(millisUntilFinished));
}
};
}
This is how I am trying to access the class:
mSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
mTextView = (TextView) findViewById(R.id.timer_textView);
mCountDownTimer.start();
I am getting an error like this:
mCountDownTimer cannot be resolved
The full activity is here:
public class SpeedTestExamActivity extends Activity {
String xmlContent=null;
String duration=null;
//strings for use
String answer_str, option1_str,option2_str,option3_str,option4_str;
//text views for quiz layout
TextView question_view;
TextView question_sr_no;
RadioButton option1;
RadioButton option2;
RadioButton option3;
RadioButton option4;
int counter=0;
int loop_checker=0;
int i;
//buttons on UI
Button prevQuestion;
Button nextQuestion;
Button resetQuestion;
Button endTest;
// XML node keys
static final String KEY_LIST = "List"; // parent node
static final String KEY_SR_NO = "SRNo";
static final String KEY_EXAM_SET_ID="ExamSetId";
static final String KEY_Q_ID="QId";
static final String KEY_QT_ID="QTId";
static final String KEY_QUESTION = "Question";
static final String KEY_MARKS = "Marks";
static final String KEY_NEGATIVE_MARKS = "NegativeMark";
static final String KEY_ATTEMPTED_TIME = "AttemtedTime";
static final String KEY_IDLE_TIME = "IdleTime";
static final String KEY_ELAPSED_TIME = "ElapsedTime";
static final String KEY_LAST_Q_INDEX = "LastQIndex";
static final String KEY_SUBJECT_NAME = "SubjectName";
static final String KEY_OPTION1 = "Option1";
static final String KEY_OPTION2 = "Option2";
static final String KEY_OPTION3 = "Option3";
static final String KEY_OPTION4 = "Option4";
static final String KEY_CORRECT = "Correct";
//variables to run the timer
int test_duration;
//object of the handler class
Handler handler;
//textview for timer
TextView mTextView;
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("HH:mm:ss");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_speed_test_exam);
//getting previously received content as xml
xmlContent=getFromPreference("SpeedTestContent");
//getting previously saved exam duration from preference
duration=getFromPreference("exam_duration");
//setting time for timer to finish activity after test duration is over
test_duration=Integer.parseInt(duration.toString())*60000;
//makeAToast("Test duration is ms: "+test_duration);
mSimpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
mTextView = (TextView) findViewById(R.id.timer_textView);
mCountDownTimer.start();
//starting timer
runTimer();
//assigning objects to layouts
question_view=(TextView)findViewById(R.id.question_textView);
question_sr_no=(TextView)findViewById(R.id.question_id_textView);
option1=(RadioButton)findViewById(R.id.option1_radioButton);
option2=(RadioButton)findViewById(R.id.option2_radioButton);
option3=(RadioButton)findViewById(R.id.option3_radioButton);
option4=(RadioButton)findViewById(R.id.option4_radioButton);
//calling function to populate ui
populating_textview(counter);
//onclick opt 1
option1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
option2.setChecked(false);
option3.setChecked(false);
option4.setChecked(false);
//getting text from TextView and checking whether it is equal to ans
option1_str=option1.getText().toString();
if (answer_str.equalsIgnoreCase(option1_str))
{
//makeAToast("Correct!");
//calling function to populate ui with next question
// counter++;
// if (counter<=loop_checker)
// {
// populating_textview(counter);
// }
// else
// {
// makeAToast("Game Over!");
// }
}
else
{
//makeAToast("Wrong answer!");
}
}
});
//onclick opt 2
option2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
option1.setChecked(false);
option3.setChecked(false);
option4.setChecked(false);
//getting text from TextView and checking whether it is equal to ans
option2_str=option2.getText().toString();
String answer=answer_str;
if (answer.equalsIgnoreCase(option2_str))
{
//calling function to populate ui with next question
//makeAToast("Correct!");
// counter++;
// if (counter<=loop_checker)
// {
// populating_textview(counter);
// }
// else
// {
// makeAToast("Game Over!");
// }
}
else
{
//makeAToast("Wrong answer!");
}
}
});
//onclick opt 3
option3.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
option1.setChecked(false);
option2.setChecked(false);
option4.setChecked(false);
//getting text from TextView and checking whether it is equal to ans
option3_str=option3.getText().toString();
String answer1=answer_str;
if (answer1.equalsIgnoreCase(option3_str))
{
//calling function to populate ui with next question
//makeAToast("Correct!");
// counter++;
// if (counter<=loop_checker)
// {
// populating_textview(counter);
// }
// else
// {
// makeAToast("Game Over!");
// }
}
else
{
//makeAToast("Wrong answer!");
}
}
});
//onclick opt 4
option4.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
option1.setChecked(false);
option2.setChecked(false);
option3.setChecked(false);
//getting text from TextView and checking whether it is equal to ans
option4_str=option4.getText().toString();
String answer2=answer_str;
if (answer2.equalsIgnoreCase(option4_str))
{
//calling function to populate ui with next question
//makeAToast("Correct!");
// counter++;
// if (counter<=loop_checker)
// {
// populating_textview(counter);
// }
// else
// {
// makeAToast("Game Over!");
// }
}
else
{
//makeAToast("Wrong answer!");
}
}
});
//onclick next button
nextQuestion = (Button) findViewById(R.id.next_question_button);
nextQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
option1.setChecked(false);
option2.setChecked(false);
option3.setChecked(false);
option4.setChecked(false);
counter++;
if (counter<=loop_checker)
{
populating_textview(counter);
}
else
{
makeAToast("Game Over!");
}
}
});
//onclick previous button
prevQuestion = (Button) findViewById(R.id.previous_question_button);
prevQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(counter!=0)
{
counter--;
}
if (counter<loop_checker)
{
populating_textview(counter);
}
if(counter==loop_checker)
{
counter--;
populating_textview(counter);
}
if(counter==0)
{
makeAToast("No more questions!");
}
}
});
//onclick reset button
resetQuestion = (Button) findViewById(R.id.reset_question_button);
resetQuestion.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
option1.setChecked(false);
option2.setChecked(false);
option3.setChecked(false);
option4.setChecked(false);
}
});
//onclick end test button
endTest = (Button) findViewById(R.id.end_test_button);
endTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//deactivating timer before finishing activity
handler.removeCallbacksAndMessages(null);
finish();
Intent intent = new Intent(SpeedTestExamActivity.this, RateUsActivity.class);
SpeedTestExamActivity.this.startActivity(intent);
}
});
}
//deactivating back button
#Override
public void onBackPressed() {
}
//getting content from preferences
public String getFromPreference(String variable_name)
{
String get_content;
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
get_content = preferences.getString(variable_name,"");
return get_content;
// makeAToast(xmlContent);
}
// function to populate ui with question counter
void populating_textview(int count_questions)
{
ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
XMLParser parser = new XMLParser();
//String xml = parser.getXmlFromUrl(URL); // getting XML
Document doc = parser.getDomElement(xmlContent); // getting DOM element
//count_questions=2;
NodeList nl = doc.getElementsByTagName(KEY_LIST);
// looping through all item nodes <item>
for ( i = 0; i < nl.getLength();i++) {
loop_checker=i;
// while(counter< nl.getLength())
// {
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element) nl.item(count_questions);
// adding each child node to HashMap key => value
map.put(KEY_LIST, parser.getValue(e, KEY_LIST));
map.put(KEY_SR_NO, parser.getValue(e, KEY_SR_NO));
question_sr_no.setText(parser.getValue(e, KEY_SR_NO)+".");
map.put(KEY_QUESTION, parser.getValue(e, KEY_QUESTION));
question_view.setText(parser.getValue(e, KEY_QUESTION));
map.put(KEY_OPTION1, parser.getValue(e, KEY_OPTION1));
//option1_str =parser.getValue(e, KEY_OPTION1);
option1.setText(parser.getValue(e, KEY_OPTION1));
map.put(KEY_OPTION2, parser.getValue(e, KEY_OPTION2));
option2.setText(parser.getValue(e, KEY_OPTION2));
//option2_str =parser.getValue(e, KEY_OPTION2);
map.put(KEY_OPTION3, parser.getValue(e, KEY_OPTION3));
option3.setText(parser.getValue(e, KEY_OPTION3));
//option3_str =parser.getValue(e, KEY_OPTION3);
map.put(KEY_OPTION4, parser.getValue(e, KEY_OPTION4));
option4.setText(parser.getValue(e, KEY_OPTION4));
//option4_str =parser.getValue(e, KEY_OPTION4);
map.put(KEY_CORRECT, parser.getValue(e, KEY_CORRECT));
// makeAToast(parser.getValue(e, KEY_ANSWER));
answer_str =parser.getValue(e, KEY_CORRECT);
// adding HashList to ArrayList
menuItems.add(map);
}
}
//method to run timer
public void runTimer()
{
handler = new Handler();
// run a thread after a particular time seconds to start the home screen
handler.postDelayed(new Runnable() {
#Override
public void run() {
makeAToast("Your time is up!");
Intent intent = new Intent(SpeedTestExamActivity.this, RateUsActivity.class);
finish();
SpeedTestExamActivity.this.startActivity(intent);
}
}, test_duration); // time in milliseconds (1 second = 1000 milliseconds) until the run() method will be called
}
//method to show toast
public void makeAToast(String str) {
//yet to implement
Toast toast = Toast.makeText(this,str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
//class to display on screen timer
class ShowTimer
{
long mMilliseconds = 120000;
SimpleDateFormat mSimpleDateFormat = new SimpleDateFormat("HH:mm:ss");
CountDownTimer mCountDownTimer = new CountDownTimer(mMilliseconds, 1000) {
#Override
public void onFinish() {
mTextView.setText(mSimpleDateFormat.format(0));
}
public void onTick(long millisUntilFinished) {
mTextView.setText(mSimpleDateFormat.format(millisUntilFinished));
}
};
}
}
The problem is that, I already have the time in ms, I cannot use any hard coded values.
I had followed the tutorial in here.
Where am I going wrong? What should I do to implement the timer?
Thanks in advance
Try this:
ShowTimer showTimer = new ShowTimer();
showTimer.mCountDownTimer.start();
Or better use an accessor in ShowTimer:
showTimer.getCountDownTimer().start();
The getCountDownTimer returns mCountDownTimer:
public CountDownTimer getCountDownTimer() {
return mCountDownTimer;
}
You have mCountDownTimer declared in the inner class rather than the main class. If you move it up into your SpeedTestExamActivity class you'll be able to access it.
mCountDownTime is an instance field so therefore you need an instance of ShowTimer on which to access the field.