Set timer in android quiz application - java

I'm a beginner in android application. I want to make android quiz application with a timer. Every question has a timer and resets in every next question. How can I input countdown timer with my java activity?
Here's my code:
public class QuizHistoryActivity extends AppCompatActivity {
private TextView countLabel;
private TextView questionLabel;
private Button answerBtn1, answerBtn2, answerBtn3;
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 [][] = {
{"Question random", "correctanswer",
"choice a", "choice b", "choice c"},
{"Question random", "correct answer",
"choice a,""choice b","choice c"},
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz_history);
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);
//Create quizArray from quizdata
for (int i = 0; i < quizData.length; i++) {
//Prepare array
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]);
//Add tmpArray to quizArray
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz () {
//Update quizCountLabel
countLabel.setText("Question #" + quizCount);
//Generate random number between 0 and 14 (Quiz Array's size -1)
Random random = new Random();
int randomNum = random.nextInt(quizArray.size());
//Pick ine quiz set
ArrayList<String> quiz = quizArray.get(randomNum);
//Set question and right answer
//array format
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
//remove "country" from quiz and shuffle choice
quiz.remove(0);
Collections.shuffle(quiz);
//Set Choices
answerBtn1.setText(quiz.get(0));
answerBtn2.setText(quiz.get(1));
answerBtn3.setText(quiz.get(2));
//Remove this quiz from quizArray
quizArray.remove(randomNum);
}
public void checkAnswer (View view) {
//Get pushed button
Button answerBtn = (Button)findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
if(btnText.equals(rightAnswer)) {
//Correct!
alertTitle = "Correct!";
rightAnswerCount++;
}else {
//Wrong
alertTitle = "Wrong";
}
//create Dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage("Answer : \n \t \t" + rightAnswer);
builder.setPositiveButton("Got It!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (quizCount == QUIZ_COUNT) {
//Show Result
Intent resultintent = new Intent(getApplicationContext(), ResultQuizHistoryActivity.class);
resultintent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(resultintent);
}else {
quizCount++;
showNextQuiz();
}
}
});
builder.setCancelable(false);
builder.show();
}
}

You can use a Chronometer from the Android framework to show the time in the UI, and:
long start = System.currentTimeMillis();
At the beginning of the quiz, and at the end
long end = System.currentTimeMillis();
long timeTranscurredInMillis = end - start;
...to get the time that the quiz lasted.

here is it
CountDownTimer countDown;
countDown= new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
//call nextQuestionMethod here
}
};
countDown.start();
A 30 Sec timer with 1 sec tick , you can change these values according to your choice. Refer to this link for more details.

Related

True answer button green [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I make a quizz app.
When the user click the right answer, I want the button to turn green.
But I don't know how.
private TextView countLabel;
private ImageView questionImage;
private Button answerBtn1;
private Button answerBtn2;
private Button answerBtn3;
private Button answerBtn4;
private TextView textView;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
// {"Image Name", "Right Answer", "Choice1", "Choice2", "Choice3"}
{"Aşağıdaki tümcelerle bir paragraf oluşturulduğunda, hangisi son tümce olur ?", "Önce hoşa gidiyor,sonra üşütüyordu insanı.", "Pencereyi ardına kadar açtım.", "Pencereyi ardına kadar açtım.", "Odanın içine gecenin serinliği doldu."},
{"Ben insanın iş görme isteğini ve yaşama çabasını daima canlı tutmasını isterim.Ölüm,bahçeme fidanlarını dikerken bulmalı beni;ama ölüm korkusu,bahçemi yitirme korkusu içinde değil Diyen biri için aşağıdakilerden hangisi söylenemez ?", "Telaşlı olduğu", "Hayatı sevdiği", "Umutlu olduğu", "Çalışkan olduğu"},
{"Bu ayrımın dışında iki toplum birbirini kabullenmiş hatta kaynaşmış olarak yaşıyorlardı. Öylesine ki Feride? nin çocukluğunda bir Rum delikanlısı, dul bir kadının tek oğlu, bir kaza sonucu öldüğünde, bu acıklı olaya türkü yakanlar Türkler olmuşlardır. Yukarıdaki paragrafın konusu aşağıdaki seçeneklerin hangisindedir ?", "İki toplumun kaynaşması", "Rum delikanlısı", "Feride'nin çocukluğu", "Dul bir kadının yası"},
{"Aşağıdaki cümlelerin hangisinde büyük harf yanlış kullanılmıştır ?", "İleride Matematik Öğretmeni olmak istiyor.", "Yazları İzmire gidiyor.", "Üç yıldır Şirinevlerde oturuyor.", "Salim 24 Şubatta doğmuş."},
{"Aşağıdaki kelimelerin hangisinin yazımı doğrudur ?", "pek az", "hiçkimse", "bir az", "herşey"},
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
countLabel = findViewById(R.id.countLabel);
questionImage = findViewById(R.id.questionImage);
answerBtn1 = findViewById(R.id.answerBtn1);
answerBtn2 = findViewById(R.id.answerBtn2);
answerBtn3 = findViewById(R.id.answerBtn3);
answerBtn4 = findViewById(R.id.answerBtn4);
textView = findViewById(R.id.textView);
// Create quizArray from quizData.
for (int i = 0; i < quizData.length; i++) {
// Prepare array.
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]); // Image Name
tmpArray.add(quizData[i][1]); // Right Answer
tmpArray.add(quizData[i][2]); // Choice1
tmpArray.add(quizData[i][3]); // Choice2
tmpArray.add(quizData[i][4]); // Choice3
// Add tmpArray to quizArray.
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz() {
// Update quizCountLabel.
countLabel.setText("Soru:" + quizCount);
// Generate random number between 0 and 4 (quizArray's size -1)
Random random = new Random();
int randomNum = random.nextInt(quizArray.size());
// Pick one quiz set.
ArrayList<String> quiz = quizArray.get(randomNum);
// Set Image and Right Answer.
// Array format: {"Image Name", "Right Answer", "Choice1", "Choice2", "Choice3"}
textView.setText(quiz.get(0));
rightAnswer = quiz.get(1);
// Remove "Image Name" from quiz and shuffle choices.
quiz.remove(0);
Collections.shuffle(quiz);
// Set choices.
answerBtn1.setText(quiz.get(0));
answerBtn2.setText(quiz.get(1));
answerBtn3.setText(quiz.get(2));
answerBtn4.setText(quiz.get(3));
// Remove this quiz from quizArray.
quizArray.remove(randomNum);
}
public void checkAnswer(View view) {
// Get pushed button.
Button answerBtn = findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
if (btnText.equals(rightAnswer)) {
// Correct!!
alertTitle = "Doğru!";
rightAnswerCount++;
} else {
// Wrong
alertTitle = "Yanlış...";
}
// Create Dialog.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage("Cevap : " + rightAnswer);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (quizArray.size() < 1) {
// quizArray is empty.
showResult();
} else {
quizCount++;
showNextQuiz();
}
}
});
builder.setCancelable(false);
builder.show();
}
public void showResult() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Sonuç");
builder.setMessage(rightAnswerCount + " / 5");
builder.setPositiveButton("Tekrar Dene", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
recreate();
}
});
builder.setNegativeButton("Çıkış", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
finish();
}
});
builder.show();
}
}
You can use this :
If(rightAnswer){
// If you're in an activity:
answerBtn1.setBackgroundColor(getResources().getColor(R.color.green));
// OR, if you're not:
answerBtn1.setBackgroundColor(Button11.getContext().getResources().getColor(R.color.green));
}
Or, alternatively:
if(rightAnswer){
answerBtn1.setBackgroundColor(Color.GREEN); // From android.graphics.Color
}

Android studio html view in ArrayList

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

My Android UI doesn't run?

I implemented AsyncTask to execute results. Here is the error I get...
FATAL EXCEPTION: AsyncTask #1
Process: ai69.psoui, PID: 3287
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.app.Activity.<init>(Activity.java:754)
at android.support.v4.app.SupportActivity.<init>(SupportActivity.java:31)
at android.support.v4.app.BaseFragmentActivityGingerbread.<init>(BaseFragmentActivityGingerbread.java:37)
at android.support.v4.app.BaseFragmentActivityHoneycomb.<init>(BaseFragmentActivityHoneycomb.java:29)
at android.support.v4.app.BaseFragmentActivityJB.<init>(BaseFragmentActivityJB.java:30)
at android.support.v4.app.FragmentActivity.<init>(FragmentActivity.java:79)
at android.support.v7.app.AppCompatActivity.<init>(AppCompatActivity.java:61)
at ai69.psoui.MainActivity.<init>(MainActivity.java:0)
at android_tests.CustomUseCase.<init>(CustomUseCase.java:19)
at android_tests.TestFactory.getTest(TestFactory.java:15)
at ai69.psoui.ParticleActivity.runTest(ParticleActivity.java:91)
at ai69.psoui.ParticleActivity$runTests.doInBackground(ParticleActivity.java:53)
at ai69.psoui.ParticleActivity$runTests.doInBackground(ParticleActivity.java:50)
at android.os.AsyncTask$2.call(AsyncTask.java:295)
I have looked at different SOF posts about "Looper.prepare()" but the thing is, prior to a few changes in changing static variables to getter/setter methods, my UI was working fine.
Here is my code...
public class ParticleActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "PSOUI.MESSAGE";
private ProgressDialog pd;
private double[] results = {-1.0, -1.0, -1.0};
EditText particles;
EditText iterations;
EditText userSol;
EditText userBatt;
private double battery;
private double solution;
//int numberOfDimensions = MainActivity.dimensions.size();
//public ArrayList<Double> costData = MainActivity.costDATA; //costs that
the user enters for each resource
//public ArrayList<Double> costWlan = MainActivity.costWLAN;
//public ArrayList<Double> costUtilities = MainActivity.costUTILITY;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_particle);
particles = (EditText) findViewById(R.id.particles);
iterations = (EditText) findViewById(R.id.iterations);
userSol = (EditText) findViewById(R.id.solution);
userBatt = (EditText) findViewById(R.id.battery);
pd = null;
runPSOButton();
}
#Override
public void onPause(){
super.onPause();
if(pd != null)
pd.dismiss();
}
public class runTests extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) { //sort this out
results = runTest("CustomUseCase"); //i only want to run this one!!!
return null;
}
#Override
protected void onPostExecute(Void v) {
if (results != null && results.length > 0 && results[0] != -1) {
loadIntent(results);
} //otherwise it will evaluate the next logic statement results[0] != -1 with no chance of NulLPointerException
}
#Override
protected void onPreExecute() {
pd = ProgressDialog.show(ParticleActivity.this, "Busy", "Algorithm is currently executing");
pd.setCancelable(true);
pd.show();
}
}
public void runPSOButton() {
final Button runPSO = (Button) findViewById(R.id.runpso);
runPSO.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
new runTests().execute();
}
});
}
public double[] runTest(String test) {
int noPart = Integer.parseInt(particles.getText().toString());
int noIter = Integer.parseInt(iterations.getText().toString());
return new TestFactory(noPart, noIter).getTest(test).test();
}
public void loadIntent(double[] result) {
double[] results = result;
Intent intent = new Intent(this, SolutionActivity.class);
intent.putExtra(EXTRA_MESSAGE, results);
startActivity(intent);
}
public double setBatteryCost(){
battery = Double.parseDouble(userBatt.getText().toString());
return battery;
}
public double getBatteryCost(){return setBatteryCost();}
public double setUserSolution(){
solution = Double.parseDouble(userSol.getText().toString());
return solution;
}
public double getUserSolution(){return setUserSolution();}
}
Can someone explain whats happening? New to Android Studio and have been developing for only 3 months in Java, so for any solutions can I kindly request an explanation for it too? Much appreciated thank you
UPDATE:
Here is my mainActivity...
public class MainActivity extends AppCompatActivity {
//declare variables
EditText name;
EditText data;
EditText wlan;
EditText utility;
Button addservice;
ListView lv;
ListView lv2;
ListView lv3;
ListView lv4;
public ArrayList<String> servicenames;
public ArrayList<String> dimensions;
public ArrayList<Double> costDATA;
public ArrayList<Double> costWLAN;
public ArrayList<Double> costUTILITY;
ArrayAdapter<String> namesAdapter;
ArrayAdapter<Double> dataAdapter;
ArrayAdapter<Double> wlanAdapter;
ArrayAdapter<Double> utilityAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//map the components to the variables
name = (EditText) findViewById(R.id.servicename);
data = (EditText) findViewById(R.id.data);
wlan = (EditText) findViewById(R.id.wlan);
utility = (EditText) findViewById(R.id.utility);
addservice = (Button) findViewById(R.id.addservice);
lv = (ListView) findViewById(R.id.lv);
lv2 = (ListView) findViewById(R.id.lv2);
lv3 = (ListView) findViewById(R.id.lv3);
lv4 = (ListView) findViewById(R.id.lv4);
//create arraylists for each component
servicenames = new ArrayList<String>();
dimensions = new ArrayList<String>();
costDATA = new ArrayList<Double>();
costWLAN = new ArrayList<Double>();
costUTILITY = new ArrayList<Double>();
//create adapters to pass on the arraylist
namesAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, servicenames);
dataAdapter = new ArrayAdapter<Double>(MainActivity.this, android.R.layout.simple_list_item_1, costDATA);
wlanAdapter = new ArrayAdapter<Double>(MainActivity.this, android.R.layout.simple_list_item_1, costWLAN);
utilityAdapter = new ArrayAdapter<Double>(MainActivity.this, android.R.layout.simple_list_item_1, costUTILITY);
//display each arraylist in the listviews
lv.setAdapter(namesAdapter);
lv2.setAdapter(wlanAdapter);
lv3.setAdapter(dataAdapter);
lv4.setAdapter(utilityAdapter);
namesAdapter.notifyDataSetChanged();
dataAdapter.notifyDataSetChanged();
wlanAdapter.notifyDataSetChanged();
utilityAdapter.notifyDataSetChanged();
dimensions.add("DATA");
dimensions.add("WLAN");
onClickBtn();
}
public void onClickBtn() { //when user clicks button, the user input is added to the listview, and cleared for the next service
addservice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String namesOfService = name.getText().toString(); //user input for service names
String costOfData = data.getText().toString(); //user input for data costs
String costOfWLAN = wlan.getText().toString(); //user input for wlan costs
String costOfUtility = utility.getText().toString(); //user input for utility costs
Double doubleWLAN = Double.parseDouble(costOfWLAN); //convert user input into double
Double doubleData = Double.parseDouble(costOfData);
Double doubleUtility = Double.parseDouble(costOfUtility);
costDATA.add(doubleData); //add the double costs to each resource arraylist
costWLAN.add(doubleWLAN);
costUTILITY.add(doubleUtility);
servicenames.add(namesOfService);
dimensions.add(namesOfService);
namesAdapter.notifyDataSetChanged();
dataAdapter.notifyDataSetChanged();
wlanAdapter.notifyDataSetChanged();
utilityAdapter.notifyDataSetChanged();
name.setText(""); //empty the edit text fields when button is clicked
wlan.setText("");
data.setText("");
utility.setText("");
}
});
}
public void nextButton(View view) //next button, onto the next activity
{
Intent intent = new Intent(MainActivity.this, ParticleActivity.class);
startActivity(intent);
}
public int getDimensions(){ return dimensions.size();}
public ArrayList<String> getElements(){ return servicenames;}
public ArrayList<Double> getCostDATA(){;return costDATA;}
public ArrayList<Double> getCostWLAN(){return costUTILITY;}
public ArrayList<Double> getCostUTILITY(){return costUTILITY;}
}
As you can see, the arraylists that store the user input is accessible using getters and setters rather than setting the arraylists static (which I did before). I access these arraylists in another class called CustomUseCase and CustomService. Here is the code for customUseCase:
public class CustomUseCase extends Test {
MainActivity mainActivity = new MainActivity();
ParticleActivity particleActivity = new ParticleActivity();
private int numberOfDimensions = mainActivity.getDimensions();
private ArrayList<Double> costData = mainActivity.getCostDATA(); //costs that the user enters for each resource
private ArrayList<Double> costWlan = mainActivity.getCostWLAN();
private ArrayList<Double> costUtilities = mainActivity.getCostUTILITY();
private double batteryCost = particleActivity.getBatteryCost();
private int maxIter;
private int noParticles;
public CustomUseCase(int noParticles, int maxIterations) {
this.noParticles = noParticles;
this.maxIter = maxIterations;
}
#Override
public double[] test() {
long max = 10000; //maximum number of iterations, override //2 bits for the WLAN/DATA and the rest for the amount of services the user inputs
double[] results = new double[numberOfDimensions]; //new array of results with numOfBits as number of elements
for (int i = 1; i <= max; i++) {
BinaryPso bpso = new BinaryPso(noParticles,
numberOfDimensions);
ParticleActivity getUserInput = new ParticleActivity();
CustomService customService =
new CustomService(batteryCost, costData, costWlan, costUtilities);
long start = System.currentTimeMillis(); //start time
bpso.setSolution(getUserInput.getUserSolution()); //changed this to user selection
bpso.optimize(maxIter, customService, true);
this.found += (bpso.getFound() ? 1 : 0);
this.iterations += bpso.getSolIterations(); //use the method in bpso to get number of iterations taken
long end = System.currentTimeMillis() - start; //end time minus start time
this.sumTimes += end; //override the time spent variable
System.out.println("P-value: " + Particle.getValue(Particle.bestGlobal()));
System.out.println("P-bitCombo: " + Arrays.toString(Particle.bestGlobal()));
System.out.println("P-goodness: " + customService.getGoodness(Particle.bestGlobal()));
}
System.out.println("Time: " + sumTimes / max);
System.out.println("Iterations: " + iterations / max);
System.out.println("Success Rate: " + found);
boolean[] bestCombo = Particle.bestGlobal();
for (Boolean b : bestCombo) {
System.out.print(b + " ");
}
System.out.println();
results[0] = sumTimes / max;
results[1] = iterations / max;
results[2] = found;
return results;
}
public static List<Boolean> getBestComboArray() { //method to get best global array
boolean[] bestCombo = Particle.bestGlobal(); //calculate best global
List<Boolean> bestCombi = new ArrayList<>(bestCombo.length);
for (int x = 0; x < bestCombo.length; x++) {
bestCombi.add(bestCombo[x]);
}
return bestCombi;
}
}
And here is my CustomService class:
public class CustomService implements Goodness {
MainActivity mainActivity = new MainActivity();
private int numOfDimensions = mainActivity.getDimensions();
private ArrayList<String> serviceNames = mainActivity.getElements();
private ArrayList<Double> costData = mainActivity.getCostDATA();
private ArrayList<Double> costWlan = mainActivity.getCostWLAN();
private ArrayList<Double> costUtilities = mainActivity.getCostUTILITY();
private double batteryCost;
public void setBatteryCost(double batteryCost) {
this.batteryCost = batteryCost;
}
public CustomService(double batteryCost, ArrayList<Double> costData, ArrayList<Double> costWlan,
ArrayList<Double> costUtilities) {
if (costUtilities == null || costUtilities.size() < 1 || costData.size() < 1 || costWlan.size() < 1) {
throw new RuntimeException("Please add atleast 1 cost to Data, WLAN and Utility");
}
this.batteryCost = batteryCost; //make sure you add battery field to UI, user enters battery level
this.costData = costData;
this.costWlan = costWlan;
this.costUtilities = costUtilities;
}
public double getGoodness(boolean[] bits) {
double utility = 0.0;
double rcost = 0.0;
ArrayList<Double> resourceCost = new ArrayList<Double>();
Collections.sort(costUtilities); //sort the costUtilities arraylist
double maxValue = Collections.max(costUtilities); //get the maximum value from the costUtilities arraylist
if(bits[0] && bits[1]){
return -500;
}
if(!bits[0] || bits[1]){
return -1000;
}
for(int x = 1; x < numOfDimensions; x++){
if(bits[x] == costUtilities.contains(maxValue)){
return -1900;
}
}
if (bits[0]) {
resourceCost = costData;
} else if (bits[1]) {
resourceCost = costWlan;
}
for (int i = 2; i <= serviceNames.size(); i++) { //if i = 2, 2<=4
if (bits[i]) {
utility += costUtilities.get(i-2);
rcost += resourceCost.get(i-2);
}
}
if (rcost < batteryCost) {
return utility;
}
return utility * 0.50;
}
}
you can not update UI items on nonUIThread.
search usage of runOnUiThread on google.
call your method in runOnUiThread().
#Override
protected Void doInBackground(Void... params) { //sort this out
runOnUiThread (new Runnable() {
public void run() {
results = runTest("CustomUseCase");
}
}
return null;
}
This explains all: "Can't create handler inside thread that has not called Looper.prepare()" and it seems your TestFactory() method creates a Handler without a Looper.
Inside a secondary Thread a Handler should be like this
....
Looper.prepare();
mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
// do work with received messages
}
};
Looper.loop();
....
More info : What is the purpose of Looper and how to use it?

How to display multiple EditText inputs after pressing Button in one TextView?

I'm in the beginning of my learning how to make apps. I want to make an app which should display randomized inputted tasks to do for the user. Firstly user should choose how many tasks would like to create and then write down tasks in EditText. I am able to create particular amount of EditText but I have no clue how to display all EditText input after pressing button. I have many versions of the code but non of them work. I got stuck and I need advice.
Here is one of my code version for the second activity.
public class TaskActivity extends AppCompatActivity {
LinearLayout containerLayout;
TextView receiverTV;
TextView tv;
TextView displayTaskTv;
EditText et;
Button btn;
Button randomTaskBtn;
int i = 0;
int size;
String inputEditText;
String inputTextView;
String stringsEt[];
String stringsTv [];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_task);
containerLayout = (LinearLayout) findViewById(R.id.linear_layout);
receiverTV = (TextView) findViewById(R.id.receiver_textView);
Intent intent = getIntent();
int number = intent.getIntExtra("Number", defaultValue);
receiverTV.setText("You have chosen to add: " + number + " tasks!");
createEtTvBtn(number);
createBtn();
createTextView();
}
public void createEtTvBtn(int number) {
for (i = 1; i <= number; i++) {
tv = new TextView(this);
tv.setText("Task nr: " + i);
tv.setPadding(16, 16, 16, 16);
tv.setTextColor(Color.parseColor("#008b50"));
tv.setTextSize(20);
tv.setId(i + value);
containerLayout.addView(tv);
et = new EditText(this);
et.setHint("Enter task nr: " + i);
et.setId(i + value);
et.setLines(2);
containerLayout.addView(et);
btn = new Button(this);
btn.setText("Confirm task nr: " + i);
btn.setId(i + value);
containerLayout.addView(btn);
final List<EditText> allEditText = new ArrayList<EditText>();
final List<TextView>allTextView = new ArrayList<TextView>();
final List<Button>allButton = new ArrayList<Button>();
String[] stringsEditText = new String[(allEditText.size())];
String[] stringsTextView = new String[(allTextView.size())];
String[] stringsBtn = new String[(allButton.size())];
for(int i=0; i < allEditText.size(); i++){
stringsEditText[i] = allEditText.get(i).getText().toString();
}
for (int i=0; i < allTextView.size(); i++) {
stringsTextView[i] = allTextView.get(i).getText().toString();
size = allTextView.get(i).getText().toString().length();
}
for(int i=0; i < allButton.size(); i++){
stringsBtn[i] = allButton.get(i).getText().toString();
}
allTextView.add(tv);
allEditText.add(et);
allButton.add(btn);
allButton.get(0).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
inputEditText = allEditText.get(0).getText().toString();
stringsEt = new String[] {allEditText.get(0).getText().toString()};
if (inputEditText.length() > 0) {
allTextView.get(0).setText(inputEditText);
allEditText.add(allEditText.get(0));
allEditText.get(0).setText("");
}
else if (inputEditText.length() ==0){
Toast.makeText(TaskActivity.this, "You need to write down your task", Toast.LENGTH_LONG).show();
}
inputTextView = allTextView.get(0).getText().toString();
stringsTv = new String[] {allTextView.get(0).getText().toString()};
if (inputTextView.length() > 0) {
allTextView.get(0).getText();
allTextView.add(allTextView.get(0));
}
}
});
}
}
private Button createBtn() {
randomTaskBtn = new Button(this);
randomTaskBtn.setText("Task");
containerLayout.addView(randomTaskBtn);
randomTaskBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
double luckyTask = Math.random();
luckyTask *=size;
int luckyIndex = (int)luckyTask;
displayTaskTv.setText(stringsTv[luckyIndex]);
}
});
return randomTaskBtn;
}
private TextView createTextView() {
displayTaskTv = new TextView(this);
displayTaskTv.setTextSize(20);
displayTaskTv.setTextColor(Color.parseColor("#dd2626"));
displayTaskTv.setText("");
containerLayout.addView(displayTaskTv);
return displayTaskTv;
}
}
Thank you for any constructive advices.
I am sure my code is big mess. I wanted to created more methods but I didn't succeed.
This is what you should do
Step 1 -
Create multiple EditTexts and store each one of them in an ArrayList say myEditTextList.
Step 2- Take data from all edit texts
String str = ""
for(EditText et: myEditTextList) {
str += et.getText().toString();
}
Step 3- Display data in str wherever you want.

CountDownTimer trivia game score - Android (java)

I have a trivia game that displays 10 questions and they each have a 10 second timer. I have 2 problems that do not function correctly.
Firstly, If the timer runs out on a question, it displays the next question but the timer does not reset. The textviews stay at "Time's up!" and "Time Elapsed: 10000" instead of restarting the timer on the new question that is displayed.
Lastly, on the Results page the correct score is not displayed in the textview. The percentage textview displays correctly but the score textview displays "android.widget.TextView#416473c" or some other random memory location.
The program never crashes just functions incorrectly. Any code structure or other suggestions is much appreciated! This is my first android mobile app attempt and I am slowly and strugglingly through it. Yet enjoying it! :)
QuesteionView.java
public class QuestionView extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.questionviewmain);
answer1 = (Button)findViewById(R.id.answer1);
answer2 = (Button)findViewById(R.id.answer2);
answer3 = (Button)findViewById(R.id.answer3);
answer4 = (Button)findViewById(R.id.answer4);
question = (TextView)findViewById(R.id.question);
queries = getIntent().getParcelableArrayListExtra("queries");
timer = (TextView)findViewById(R.id.timer);
timeElapsedView = (TextView)findViewById(R.id.timeElapsedView);
cdTimer = new Timer(startTime, interval);
loadQuestion();
}
public void loadQuestion() {
if(i == 9) {
endQuiz();
} else {
if(!timerHasStarted) {
cdTimer.start();
timerHasStarted = true;
} else {
cdTimer.cancel();
timerHasStarted = false;
}
answer = queries.get(i).getCorrectAnswer();
question.setText(queries.get(i).getQuery());
answer1.setText(queries.get(i).getA1());
answer2.setText(queries.get(i).getA2());
answer3.setText(queries.get(i).getA3());
answer4.setText(queries.get(i).getA4());
answer1.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
queries.get(i).setSelectedAnswer(0);
if(answer == 0) {
correctAnswers++;
nextQuestion();
} else {
wrongAnswers++;
nextQuestion();
}
}
});
//same type of code for buttons for answers 2 through 4.
}
}
public void nextQuestion() {
score = score + timeElapsed;
i++;
loadQuestion();
}
public class Timer extends CountDownTimer {
public Timer(long startTime, long interval) {
super(startTime, interval);
}
public void onFinish() {
if(i == 9) {
cdTimer.cancel();
} else {
timer.setText("Time's up!");
timeElapsedView.setText("Time Elapsed: " + String.valueOf(startTime));
wrongAnswers++;
nextQuestion();
}
}
public void onTick(long millisUntilFinished) {
timer.setText("Time remain: " + Long.toString(millisUntilFinished));
timeElapsed = startTime - millisUntilFinished;
timeElapsedView.setText("Time Elapsed: " + Long.toString(timeElapsed));
}
}
public void endQuiz() {
Intent intent = new Intent(QuestionView.this, Results.class);
intent.putExtra("correctAnswers", correctAnswers);
intent.putExtra("wrongAnswers", wrongAnswers);
intent.putExtra("score", score);
intent.putParcelableArrayListExtra("queries", queries);
startActivity(intent);
}
}
Results.java
public class Results extends Activity {
QuestionView qv = new QuestionView();
ArrayList<Question> queryList = qv.getQueries();
int cAnswers;
int wAnswers;
long score;
ArrayList<Question> qs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.resultsmain);
cAnswers = getIntent().getIntExtra("correctAnswers", -1);
wAnswers = getIntent().getIntExtra("wrongAnswers", -1);
score = getIntent().getLongExtra("score", -1);
qs = getIntent().getParcelableArrayListExtra("queries");
Button mainmenuBtn = (Button)findViewById(R.id.mainmenuBtn);
mainmenuBtn.setText("Main Menu");
mainmenuBtn.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
restart();
}
});
showResults();
}
public void showResults() {
ArrayList<TextView> tList = new ArrayList<TextView>(9);
TextView header = (TextView)findViewById(R.id.header);
header.setText("SUMMARY");
TextView percentage = (TextView)findViewById(R.id.percentage);
percentage.setText(Integer.toString(10 * cAnswers) + "%");
TextView score = (TextView)findViewById(R.id.score);
String s = "" + score;
score.setText(s);
TextView q1 = (TextView)findViewById(R.id.q1);
TextView q2 = (TextView)findViewById(R.id.q2);
TextView q3 = (TextView)findViewById(R.id.q3);
TextView q4 = (TextView)findViewById(R.id.q4);
TextView q5 = (TextView)findViewById(R.id.q5);
TextView q6 = (TextView)findViewById(R.id.q6);
TextView q7 = (TextView)findViewById(R.id.q7);
TextView q8 = (TextView)findViewById(R.id.q8);
TextView q9 = (TextView)findViewById(R.id.q9);
TextView q10 = (TextView)findViewById(R.id.q10);
tList.add(q1);
tList.add(q2);
tList.add(q3);
tList.add(q4);
tList.add(q5);
tList.add(q6);
tList.add(q7);
tList.add(q8);
tList.add(q9);
tList.add(q10);
for(int i = 0; i < tList.size(); i++) {
tList.get(i).setText(qs.get(i).getQuery());
if(qs.get(i).getSelectedAnswer() == qs.get(i).getCorrectAnswer()) {
tList.get(i).setTextColor(Color.GREEN);
} else {
tList.get(i).setTextColor(Color.RED);
}
}
}
public void restart() {
Intent intent = new Intent(Results.this, MainMenu.class);
startActivity(intent);
}
}
From all of that code, this is what I think is happening
Firstly, If the timer runs out on a question, it displays the next question but the timer does not reset. The textviews stay at "Time's up!" and "Time Elapsed: 10000" instead of restarting the timer on the new question that is displayed.
This appears to be due to you not setting your timerHasStarted variable to false after the time runs out so I would set that to false probably when you load your next question or after you show the results.
Lastly, on the Results page the correct score is not displayed in the textview. The percentage textview displays correctly but the score textview displays "android.widget.TextView#416473c" or some other random memory location.
This is because you are setting your q variables to the textview and getting the id. You need something like q1.getText().toString()
You have multiple variables with the same name score. So change it to
TextView score2 = (TextView)findViewById(R.id.score);
String s = "" + score;
score2.setText(s);
the score displays not what you expected because you assigned the String s = "" + score where score is what you named for the Textview which obviously not an integer and not equivalent to the score that the user has. :)

Categories

Resources