how to remove force close error in android code - java

package com.example.app123;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
EditText input;
EditText output;
Button one;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
input = (EditText) findViewById(R.id.editText1);
output = (EditText) findViewById(R.id.editText2);
one = (Button) findViewById(R.id.button1);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (v == one) {
Context context1 = getApplicationContext();
CharSequence text1 = "Please enter a valid number";
int duration = Toast.LENGTH_SHORT;
final Toast toast = Toast.makeText(context1, text1,
duration);
toast.show();
int inputValue = Integer.parseInt(input.getText()
.toString());
int value = inputValue * inputValue;
output.setText(value);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it ispresent.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}

hi remove this condition in your button click code if(v==one) only use this like
input=(EditText)findViewById(R.id.editText1);
output = (EditText) findViewById(R.id.editText2);
one = (Button) findViewById(R.id.button1);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context1 = getApplicationContext();
CharSequence text1 = "Please enter a valid number";
int duration = Toast.LENGTH_SHORT;
final Toast toast = Toast.makeText(context1, text1,
duration);
toast.show();
int inputValue = Integer.parseInt(input.getText()
.toString());
int value = inputValue * inputValue;
output.setText(value);
}
});
i hope it's work for you.

If you have multiple buttons:
Button b1=(Button)findviewById(R.id.b1);
Button b2=(Button)findviewById(R.id.b2);
one.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(v.getid())
case R.id.b1:
CharSequence text1 = "Please enter a valid number";
int duration = Toast.LENGTH_SHORT;
final Toast toast = Toast.makeText(YourActivity.this, text1,
duration);
toast.show();
int inputValue = Integer.parseInt(input.getText()
.toString());
int value = inputValue * inputValue;
output.setText(value);
break;
case R.id.b1:
break;
}
});

Related

Android Studio keeps giving me nullpointerexception [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
Hi i am doing a project that is due wednesday and i have spent over 13 hours trying to get Android studio working again, first their was a problem with the gradle and now i keep getting a nullpointerexception even though it same code that was working before. here is the code, please help? because i am stuck and could be doing my project rather that trying to solve android studios problems. by the way there are no errors within the code it says but here is the code.
package ie.wit.fitnessmadeeasy;
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.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class LogActivity extends AppCompatActivity {
DataBaseHelper helper = new DataBaseHelper(this);
EditText uname = (EditText) findViewById(R.id.et_username);
String unstr = uname.getText().toString();
EditText pass = (EditText) findViewById(R.id.et_password);
String passstr = pass.getText().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
TextView registerLink = (TextView) findViewById(R.id.regHere); //register link creates a link between the two pages
registerLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent registerIntent = new Intent(LogActivity.this, RegisterActivity.class);
LogActivity.this.startActivity(registerIntent); //what this does it creates an intent that opens the registeravtivity then it tells the current activity to perform the intent and open the register page
}
});
}
// Button login = (Button) findViewById(R.id.login);
public void onLogClick(View view) {
if (view.getId() == R.id.login) {
String Password = helper.searchPassstr(unstr);
Log.v("pass", passstr);
Log.v("pass", Password);
if (passstr.equals(Password)) {
Intent i = new Intent(LogActivity.this, UserAreaActivity.class);
i.putExtra("username", unstr);
startActivity(i);
} else {
Toast temp = Toast.makeText(LogActivity.this, "Username and Password don't Match", Toast.LENGTH_SHORT);
temp.show();
}
}
}
}
package ie.wit.fitnessmadeeasy;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
//import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class RegisterActivity extends AppCompatActivity {
DataBaseHelper helper = new DataBaseHelper(this);
final EditText name = (EditText) findViewById(R.id.et_name);
final EditText username = (EditText) findViewById(R.id.et_username);
final EditText password1 = (EditText) findViewById(R.id.et_password);
final EditText password2 = (EditText) findViewById(R.id.et_password);
String namestr = name.getText().toString();
String usernamestr = username.getText().toString();
String password1str = password1.getText().toString();
String password2str = password2.getText().toString();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
// final EditText password2 = (EditText) findViewById(R.id.et_password);
name.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(name.getText().length()==0){
name.setError("Fill Out");
}
else if(username.getText().length()==0){
username.setError("Fill Out");
}
}
});
}
public void onRegClick(View v)
{
if(v.getId() == R.id.confirm)
{
// EditText age = (EditText) findViewById(R.id.et_age); //age is a final variable and is only assigned to activity_register as a view
// EditText name = (EditText) findViewById(R.id.et_name);
// EditText username = (EditText) findViewById(R.id.et_username);
// EditText password1 = (EditText) findViewById(R.id.et_password);
// EditText password2 = (EditText) findViewById(R.id.et_password2);
if(namestr.equals("")){
Toast pass = Toast.makeText(RegisterActivity.this, "Enter Name!", Toast.LENGTH_SHORT);
pass.show();
}
if(usernamestr.equals("")){
Toast pass = Toast.makeText(RegisterActivity.this, "Enter Username!", Toast.LENGTH_SHORT);
pass.show();
}
if(password1str.equals("")){
Toast pass = Toast.makeText(RegisterActivity.this, "Enter Password!", Toast.LENGTH_SHORT);
pass.show();
}
if(!password1str.equals(password2str))
{
//popup message
Toast pass = Toast.makeText(RegisterActivity.this, "Passwords don't match!", Toast.LENGTH_SHORT);
pass.show();
}
else{
// String namestr = name.getText().toString();
//insert details
RegRequest reg = new RegRequest();
reg.setEt_name(namestr);
reg.setEt_username(usernamestr);
reg.setEt_password(password1str);
// r.setEt_age(agestr);
Toast success = Toast.makeText(RegisterActivity.this, "Success", Toast.LENGTH_SHORT);
success.show();
Intent i = new Intent(RegisterActivity.this, LogActivity.class);
startActivity(i);
helper.insertUser(reg);
}
}
}
}
package ie.wit.fitnessmadeeasy;
public class RegRequest{
String et_name , et_username, et_password;
// int et_age;
public void setEt_name(String et_name)
{
this.et_name = et_name;
}
public String getEt_name()
{
return this.et_name;
}
public void setEt_username(String et_username)
{
this.et_username = et_username;
}
public String getEt_username()
{
return this.et_username;
}
public void setEt_password(String et_password)
{
this.et_password = et_password;
}
public String getEt_password()
{
return this.et_password;
}
}
at ie.wit.fitnessmadeeasy.LogActivity.<init>(LogActivity.java:17)
LogActivity.java
Only declare the fields like the following:
EditText uname, pass;
String unstr, passstr;
Initialize in onCreate() method.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_log);
uname = (EditText) findViewById(R.id.et_username);
unstr = uname.getText().toString();
pass = (EditText) findViewById(R.id.et_password);
passstr = pass.getText().toString();
}
And RegisterActivity.java
DataBaseHelper helper ;
EditText name, username,password1,password2;
String namestr,usernamestr,password1str,password2str;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
helper = new DataBaseHelper(this);
name = (EditText) findViewById(R.id.et_name);
username = (EditText) findViewById(R.id.et_username);
password1 = (EditText) findViewById(R.id.et_password);
password2 = (EditText) findViewById(R.id.et_password);
namestr = name.getText().toString();
usernamestr = username.getText().toString();
password1str = password1.getText().toString();
password2str = password2.getText().toString();
}

Android Studio Java code

I'm trying to replace a part of the text after clicking the bottom but I can't make it work. When I click the bottom without entering a name the message should say "Hello Username", and if I enter a name the "Username" should be replace by the name. Here is the code so far. Thanks
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
public class HelloAndroid extends AppCompatActivity implements OnClickListener {
private EditText name;
private TextView display;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_android);
name = (EditText) findViewById(R.id.name);
display = (TextView) findViewById(R.id.display);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_hello_android, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
if (button == view) {
String message = "Hello, Username " + name.getText().toString() + "!";
if (button == view) {
String username = "Hello " + name.getText().toString() + "";
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
display.setText(message);
}
}
}
}
You are enable to do this because may be you are not getting click here . Here is my code change it .
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class HelloAndroid extends AppCompatActivity implements View.OnClickListener {
private EditText name;
private TextView display;
private Button button;
String message ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dummy);
name = (EditText) findViewById(R.id.name);
display = (TextView) findViewById(R.id.display);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId())
{
case R.id.button :
if (name.getText().toString().isEmpty())
{
message = "Hello username" ;
}
else {
message = "Hello "+name.getText().toString() ;
}
Toast toast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
toast.show();
display.setText(message);
break;
}
}
}

Using shared preferences to store high score

It gives me a error cannot resolve symbol sharedpreferences, I'm trying to add a high score for every time the user take the quiz it records the high score of the quiz. I dont know what happen. Please help me with this one and I'll help you with ur reputation.
package com.example.quiz;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.logging.Handler;
public class CS_Assembly_Easy extends Activity{
TextView topscore;
public static final String mypreference = "mypref";
public static final String Topscore = "topKey";
ArrayList<Question> quesList;
ArrayList<Question> toSelectFrom; // <--- HERE
int score = 0;
int qid = 0;
int lives = 5;
int round = 1;
int timer;
Question currentQ;
TextView txtQuestion, times, scored, livess, rounds;
Button button1, button2, button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cs_assembly_easy);
CS_Assembly_QuizHelper db = new CS_Assembly_QuizHelper(this); // my question bank class
quesList = db.getAllQuestions();
toSelectFrom = new ArrayList<Question>(); // <--- HERE
toSelectFrom.addAll(quesList); // <--- HERE
Random random = new Random();// this will fetch all quetonall questions
currentQ = toSelectFrom.get( random.nextInt(toSelectFrom.size())); // the current question <-- edited here too.
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <--- HERE
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
// the textview in which the question will be displayed
// the three buttons,
// the idea is to set the text of three buttons with the options from question bank
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
// the textview in which will be displayed
scored = (TextView) findViewById(R.id.score);
// the timer
times = (TextView) findViewById(R.id.timers);
rounds = (TextView) findViewById(R.id.round);
// method which will set the things up for our game
setQuestionView();
times.setText("00:02:00");
// A timer of 60 seconds to play for, with an interval of 1 second (1000 milliseconds)
CounterClass timer = new CounterClass(60000, 1000);
timer.start();
// button click listeners
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// passing the button text to other method
// to check whether the anser is correct or not
// same for all three buttons
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
}
});
topscore = (TextView) findViewById(R.id.Topscore);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(topscore) > score) {
topscore.setText(sharedpreferences.getString(topscore, ""));
}
}
public void Save(View view) {
String n = topscore.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(Topscore, n);
editor.commit();
}
public void clear(View view) {
topscore = (TextView) findViewById(R.id.Topscore);
topscore.setText("");
}
public void Get(View view) {
topscore = (TextView) findViewById(R.id.Topscore);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
if (sharedpreferences.contains(topscore)) {
topscore.setText(sharedpreferences.getString(topscore, ""));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void getAnswer(String AnswerString) {
if (currentQ.getANSWER().equals(AnswerString)) {
// if conditions matches increase the int (score) by 1
// and set the text of the score view
score++;
scored.setText(" Score : " + score);
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.correct,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("CORRECT");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
} else if(lives > -10){
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.wrong,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("WRONG");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
else {
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
{
}
if (qid < 10) {
// if questions are not over then do this
Random random = new Random();
currentQ = toSelectFrom.get(random.nextInt(toSelectFrom.size())); // <<--- HERE
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <<--- AND HERE
setQuestionView();
round++;
rounds.setText(" Question:" + round + "/10");
} else {
// if over do this
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
times.setText("Time is up");
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put all things together
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
qid++;
}
#Override
public void onBackPressed() {
return;
}
}
sharedpreferences is not defined in your CS_Assembly_Easy class.
Try changing your code to this:
SharedPreferences sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);

how to delay the process/incrementation in Android

I'm creating a android quiz application and what I want to do and know is how to delay the process or incrementation
i want to delay 2seconds before it adds another question
here is my code, i have qid++ there which will add question after the user answer a question. I want to delay it for 2 seconds.
package com.example.quiz;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Random;
import java.util.concurrent.TimeUnit;
public class CS_Assembly_Easy extends Activity{
ArrayList<Question> quesList;
ArrayList<Question> toSelectFrom; // <--- HERE
int score = 0;
int qid = 0;
int lives = 5;
int round = 1;
int timer;
Question currentQ;
TextView txtQuestion, times, scored, livess, rounds;
Button button1, button2, button3;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cs_assembly_easy);
CS_Assembly_QuizHelper db = new CS_Assembly_QuizHelper(this); // my question bank class
quesList = db.getAllQuestions();
toSelectFrom = new ArrayList<Question>(); // <--- HERE
toSelectFrom.addAll(quesList); // <--- HERE
Random random = new Random();// this will fetch all quetonall questions
currentQ = toSelectFrom.get( random.nextInt(toSelectFrom.size())); // the current question <-- edited here too.
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <--- HERE
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
// the textview in which the question will be displayed
// the three buttons,
// the idea is to set the text of three buttons with the options from question bank
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
livess = (TextView) findViewById(R.id.livess);
// the textview in which will be displayed
scored = (TextView) findViewById(R.id.score);
// the timer
times = (TextView) findViewById(R.id.timers);
rounds = (TextView) findViewById(R.id.round);
// method which will set the things up for our game
setQuestionView();
times.setText("00:02:00");
// A timer of 60 seconds to play for, with an interval of 1 second (1000 milliseconds)
CounterClass timer = new CounterClass(60000, 1000);
timer.start();
// button click listeners
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// passing the button text to other method
// to check whether the anser is correct or not
// same for all three buttons
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
}
});
}
public void getAnswer(String AnswerString) {
if (currentQ.getANSWER().equals(AnswerString)) {
// if conditions matches increase the int (score) by 1
// and set the text of the score view
score++;
scored.setText(" Score : " + score);
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.correct,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("CORRECT");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
} else if(lives > 1){
lives--;
livess.setText("Lives: " + lives);
LayoutInflater inflater = getLayoutInflater();
// Inflate the Layout
View layout = inflater.inflate(R.layout.wrong,
(ViewGroup) findViewById(R.id.custom_toast_layout));
TextView text = (TextView) layout.findViewById(R.id.textToShow);
// Set the Text to show in TextView
text.setText("WRONG");
text.setTextSize(25);
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.BOTTOM, 0, 50);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setView(layout);
toast.show();
}
else {
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
{
}
if (qid < 10) {
// if questions are not over then do this
Random random = new Random();
currentQ = toSelectFrom.get(random.nextInt(toSelectFrom.size())); // <<--- HERE
toSelectFrom.remove(toSelectFrom.indexOf(currentQ)); // <<--- AND HERE
setQuestionView();
round++;
rounds.setText(" Question:" + round + "/10");
} else {
// if over do this
Intent intent = new Intent(CS_Assembly_Easy.this,
ResultActivity_Assembly_Easy.class);
Bundle b = new Bundle();
b.putInt("score", score); // Your score
intent.putExtras(b); // Put your score to your next
startActivity(intent);
finish();
}
}
#TargetApi(Build.VERSION_CODES.GINGERBREAD)
#SuppressLint("NewApi")
public class CounterClass extends CountDownTimer {
public CounterClass(long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
// TODO Auto-generated constructor stub
}
#Override
public void onFinish() {
times.setText("Time is up");
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
long millis = millisUntilFinished;
String hms = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS
.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS
.toMinutes(millis)));
System.out.println(hms);
times.setText(hms);
}
}
private void setQuestionView() {
// the method which will put all things together
txtQuestion.setText(currentQ.getQUESTION());
button1.setText(currentQ.getOPTA());
button2.setText(currentQ.getOPTB());
button3.setText(currentQ.getOPTC());
qid++;
}
#Override
public void onBackPressed() {
return;
}
}
You might try scheduling a Runnable with Handler.postDelayed(runnable, timeInMilliseconds)
Put the code that should be delayed inside a Runnable.run() method like this:
Handler h = new Handler();
h.postDelayed(new Runnable() {
#Override
public void run() {
// TODO your code here
}
}, 2000L);
See this link Android sleep() without blocking UI
you can use :
handler=new Handler();
Runnable r=new Runnable() {
public void run() {
//your code here
}
};
handler.postDelayed(r, 2000); // waiting for 2s

Eclipse(Android) - unfortunately HelloWorld has stopped working

I get that error message everytime I try running my program. I have a fairly simple program, with two buttons. If you press one button it subtracts 1 from a number. If you press the add button it adds 1 to the number. I have no compiling errors and I'm fairly new to android. Any help would be great... Thanks!
Here is my code: (The main activity).
package com.example.helloworld;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView numberText = (TextView) findViewById(R.id.number);
numberText.setText(String.valueOf(0));
Button.OnClickListener listenerAdd = new Button.OnClickListener() {
#Override
public void onClick(View v) {
TextView numberText = (TextView) findViewById(R.id.number);
switch(v.getId()) {
case R.id.HomeScreenChangeAdd: {
String currText = numberText.getText().toString();
int curNumb = Integer.parseInt(currText);
int newNumb = curNumb +1;
String newText = String.valueOf(newNumb);
numberText.setText(newText);
break;
}
}
}
};
Button.OnClickListener listenerSub = new Button.OnClickListener() {
#Override
public void onClick(View v) {
TextView numberText = (TextView) findViewById(R.id.number);
switch(v.getId()) {
case R.id.HomeScreenChangeSub: {
String currText = numberText.getText().toString();
int curNumb = Integer.parseInt(currText);
int newNumb = curNumb -1;
String newText = String.valueOf(newNumb);
numberText.setText(newText);
break;
}
}
}
};
((Button) findViewById(R.id.HomeScreenChangeAdd)).setOnClickListener(listenerAdd);
((Button) findViewById(R.id.HomeScreenChangeSub)).setOnClickListener(listenerSub);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Make sure
R.id.number,
R.id.HomeScreenChangeAdd, and
R.id.HomeScreenChangeSub
are included in R.layout.activity_main.
There is nothing else in your code that could crash the app at startup.

Categories