I'm tring to build an simple android game.
Users answer the questions, when the answer is correct, it is continue..
I want to add time control for each answer.
I tried to add handler function, but I didn't.
My Code;
import java.util.Collections;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class EasyGameActivity extends Activity {
public int score = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_easygame);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
finishScreen();
}
}, 5000);
startGame();
}
private void startGame() {
// TODO Auto-generated method stub
Button b1 = (Button)findViewById(R.id.answer_one);
Button b2 = (Button)findViewById(R.id.answer_two);
Button b3 = (Button)findViewById(R.id.answer_three);
Button b4 = (Button)findViewById(R.id.answer_four);
Random number = new Random();
int first = number.nextInt(100)+1;
int second = number.nextInt(100)+1;
int answer = first + second;
int rnd1 = answer + 1;
int rnd2 = answer + 2;
int rnd3 = answer - 1;
final String a = Integer.toString(answer);
String b = Integer.toString(rnd1);
String c = Integer.toString(rnd2);
String d = Integer.toString(rnd3);
((TextView) findViewById(R.id.display)).setText(Integer.toString(first) + '+' + Integer.toString(second));
List<Button> buttons = Arrays.asList(b1, b2, b3, b4);
List<String> texts = Arrays.asList(a, b, c, d);
Collections.shuffle(texts);
int i = 0;
OnClickListener onClick = new OnClickListener() {
public void onClick(View view) {
Button button = (Button) view;
String value = (String) button.getText();
if(value == a) {
checkTrue();
} else {
finishScreen();
}
}
};
for(Button button : buttons) {
button.setText(texts.get(i++));
button.setOnClickListener(onClick);
}
}
private void checkTrue() {
score++;
((TextView) findViewById(R.id.score)).setText(Integer.toString(score));
startGame();
}
private void finishScreen() {
score = 0;
startActivity (new Intent("com.bsinternet.mathfast.RESTARTGAMESCREEN"));
finish();
}
}
How can I add time control. Thanks.
This bit of code doesn't look right
if(value == a) {
checkTrue();
} else {
finishScreen();
}
You should be using equals() to check for String equality. At the moment you are checking only object equality, which will evaluate to False, and the code will never call checkTrue().
Do this instead:
if(value.equals(a) {
checkTrue();
} else {
finishScreen();
}
Related
I made a simple quiz on Android Studio which contains 3+ questions. How to make the questions become random without duplicated. This app does not use a database. I'm new to programming so I don't know what to do about this
MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import android.app.AlertDialog; import android.graphics.Color; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
TextView totalQuestionsTextView;
TextView questionTextView;
Button ansA,ansB,ansC,ansD;
Button submitBtn;
int score=0;
int totalQuestions = QuestionAnswer.question.length;
int currentQuestionIndex = 0;
String selectedAnswer = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
totalQuestionsTextView = findViewById(R.id.total_questions);
questionTextView = findViewById(R.id.question);
ansA = findViewById(R.id.ans_A);
ansB = findViewById(R.id.ans_B);
ansC = findViewById(R.id.ans_C);
ansD = findViewById(R.id.ans_D);
submitBtn = findViewById(R.id.submbit_btn);
ansA.setOnClickListener(this);
ansB.setOnClickListener(this);
ansC.setOnClickListener(this);
ansD.setOnClickListener(this);
submitBtn.setOnClickListener(this);
totalQuestionsTextView.setText("Total Questions : "+totalQuestions);
loadNewQuestion();
}
#Override
public void onClick(View view) {
ansA.setBackgroundColor(Color.WHITE);
ansB.setBackgroundColor(Color.WHITE);
ansC.setBackgroundColor(Color.WHITE);
ansD.setBackgroundColor(Color.WHITE);
Button clickedButton = (Button) view;
if(clickedButton.getId()==R.id.submbit_btn){
currentQuestionIndex++;
loadNewQuestion();
}else{
//choices button clicked
selectedAnswer = clickedButton.getText().toString();
clickedButton.setBackgroundColor(Color.MAGENTA);
}
}
void loadNewQuestion(){
if(currentQuestionIndex == totalQuestions){
finishQuiz();
return;
}
questionTextView.setText(QuestionAnswer.question[currentQuestionIndex]);
ansA.setText(QuestionAnswer.choices[currentQuestionIndex][0]);
ansB.setText(QuestionAnswer.choices[currentQuestionIndex][1]);
ansC.setText(QuestionAnswer.choices[currentQuestionIndex][2]);
ansD.setText(QuestionAnswer.choices[currentQuestionIndex][3]);
}
void finishQuiz(){
String passStatus = "";
if (score > totalQuestions*0.60){
passStatus = "Passes";
}else{
passStatus = "Failed";
}
new AlertDialog.Builder(this)
.setTitle(passStatus)
.setMessage("Score is "+score+" out of "+ totalQuestions)
.setPositiveButton("Restart",(dialogInterface, i) -> restartQuiz())
.setCancelable(false)
.show();
}
void restartQuiz(){
score = 0;
currentQuestionIndex = 0;
loadNewQuestion();
}
QuestionAnswer.java
import java.util.Arrays; import java.util.List; import java.util.Random;
public class QuestionAnswer {
public static String[] question = {
"Which company own the android?",
"Which one is not the programming language?",
"Where are you watching this video"
};
public static String choices[][] = {
{"Google", "Apple", "Nokia", "Samsung"},
{"Java", "Kotlin", "Notepad", "Python"},
{"Facebook", "Whatsapp", "Instagram", "Youtube"},
};
public static String correctAnswers[] = {
"Google",
"Notepad",
"Youtube"
};
}
how can i add shuffle.collection or random to make my app show random question instead
You need to find out about Random class first in Java. Thereafter, you will create a random number using Random class in onClick function, then set a question's index to your Random number
My app is a timed math game. Answer as many questions as you can before the timer runs out. When the time runs out, The GameOverActivity is now the current activity. I've realized that if I give no answer, the app will crash. If I give at least 1 answer, the app doesn't crash and everything is normal. I'm not sure where the flaw in my code exista.
This is the Main Activity
package stormy.incremental.randomtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.util.Random;
public class FastMathActivity extends AppCompatActivity {
int rand1, rand2, randDecider, correctAnswer, falseAnswer, problemsSolved;
String response,sumStr;
MyCountDownTimer myCountDownTimer;
int score;
Random r;
TextView randTV1, randTV2, scoreTV, sumTV, problemsSolvedTV, timerTV;
Button choice1, choice2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_random_test);
problemsSolved =0;
falseAnswer = 1;
//Initializing TextViews
timerTV = ((TextView) findViewById(R.id.timer));
randTV1 = ((TextView) findViewById(R.id.rand1));
randTV2 = ((TextView) findViewById(R.id.rand2));
sumTV = ((TextView) findViewById(R.id.sum));
scoreTV = ((TextView) findViewById(R.id.score));
problemsSolvedTV = ((TextView) findViewById(R.id.problemsSolved));
choice1 = ((Button) findViewById(R.id.choice1));
choice2 = ((Button) findViewById(R.id.choice2));
//Initializing a Random
r = new Random();
//Set the first question
setRandomProblem();
//Starting the timer
myCountDownTimer = new MyCountDownTimer(timerTV, 5000, 1000);
myCountDownTimer.start();
// Button Listeners
choice1.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
checkResponse((Button)v);
setRandomProblem();
}
});
choice2.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
checkResponse((Button)v);
setRandomProblem();
}
});
}
public void checkResponse(Button v) {
//Convert the response and correctAnswer to String in order to compare values
response = v.getText().toString();
sumStr = Integer.toString(correctAnswer);
//If the user clicks the correct answer, increment score
if ((response.equals(sumStr))) {
score++;
scoreTV.setText(score+"");
}
//Increment the total amount of problems solved
problemsSolved++;
problemsSolvedTV.setText(problemsSolved+"");
//Keep track of the score within the timer
myCountDownTimer.recordScore(score,problemsSolved);
}
private void setRandomProblem() {
//Assigning random values to ints
rand1 = r.nextInt(5 - 1) + 1;
rand2 = r.nextInt(5 - 1) + 1;
randDecider = r.nextInt(2) + 1;
//The correctAnswer of the randoms
correctAnswer = rand1 + rand2;
//Setting the texts of the random values
randTV1.setText(rand1 + "");
randTV2.setText(rand2 + "");
//If the random deciding number is 1, set answer on choice1
if (randDecider == 1) {
choice1.setText(correctAnswer + "");
choice2.setText(correctAnswer + falseAnswer + "");
}
//If the random deciding number is 2, set answer on choice2
else {
choice1.setText(correctAnswer + falseAnswer + "");
choice2.setText(correctAnswer + "");
}
}
#Override
public void onStop(){
super.onStop();
//Stop the timer
myCountDownTimer.cancel();
}
}
This is the GameOverActivity
package stormy.incremental.randomtest;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
/**
* Created by kamalu on 12/25/2017.
*/
public class GameOverActivity extends AppCompatActivity {
TextView scoreTV, problemsSolvedTV, percentageTV;
int score, problemsSolved, percentage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gameover);
//Initializing TextViews
scoreTV = ((TextView)findViewById(R.id.score));
problemsSolvedTV = ((TextView)findViewById(R.id.problemsSolved));
percentageTV = ((TextView)findViewById(R.id.percentage));
//Opening Bundle and assigning values
Bundle extras = getIntent().getExtras();
score = extras.getInt("score");
problemsSolved = extras.getInt("problemsSolved");
//calculating the accuracy
percentage = (score/problemsSolved)*100;
//Displaying the score
percentageTV.setText(percentage+"");
scoreTV.setText(score+"");
problemsSolvedTV.setText(problemsSolved+"");
}
//Start the game over
public void retry(View v){
Intent retryIntent = new Intent(GameOverActivity.this, FastMathActivity.class);
startActivity(retryIntent);
}
public void onBackPressed()
{
}
}
This is the Timer. I believe it to be important to note that the onFinish() method in this class starts the GameOverActivity.
package stormy.incremental.randomtest;
import android.content.Intent;
import android.os.CountDownTimer;
import android.widget.TextView;
public class MyCountDownTimer extends CountDownTimer {
TextView textCounter;
int score,problemsSolved;
public MyCountDownTimer(TextView textCounter, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);
this.textCounter = textCounter;
}
#Override
public void onTick (long millisUntilFinished){
textCounter.setText(String.valueOf(millisUntilFinished / 1000));
}
#Override
public void onFinish () {
Intent gameOverIntent = new Intent(textCounter.getContext(), GameOverActivity.class);
gameOverIntent.putExtra("score", score);
gameOverIntent.putExtra("problemsSolved", problemsSolved);
textCounter.getContext().startActivity(gameOverIntent);
}
//Keep track of the scores
public void recordScore(int score,int problemsSolved){
this.problemsSolved = problemsSolved;
this.score = score;
}
}
You should check:
//calculating the accuracy
percentage = (score/problemsSolved)*100;
if problemsSolved = 0, your app will crash with exeptions: java.lang.ArithmeticException
You can refer:
if (problemSolved != 0){
//calculating the accuracy
percentage = (score/problemsSolved)*100;
} else {
// handle with problemSolved = 0;
}
I hope it can help your problem!
I am new to Android development, I am working on a App and I want to convert my below mentioned code to AnsyncTask. Because it is showing me Run-time error that I am doing too much work on UI thread. Please help me to convert it to AnsyncTask.
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class PlayActivity extends AppCompatActivity {
GridView gridview;
TextView textView;
TextView result;
TextView remainingChance;
Button giveup;
Button goback;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
textView = (TextView) findViewById(R.id.blanks);
result = (TextView) findViewById(R.id.result);
remainingChance = (TextView) findViewById(R.id.remainingChance);
giveup = (Button) findViewById(R.id.giveup);
goback = (Button) findViewById(R.id.goback);
goback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
});
String dash = "";
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String easyArray[] = bundle.getStringArray("easy");
final String randomStr = easyArray[new Random().nextInt(easyArray.length)]; // Getting a random string from Array
giveup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(randomStr); // By clicking on Give up button, it displays the actual word & a message Go Back and try again
remainingChance.setText("Go Back and try again");
}
});
final Integer strLength = randomStr.length();
// Creating string with question mark with 2nd and 5th character only
for(int i=1; i<=strLength; i++){
if(i == 2){
dash = dash+Character.toString(randomStr.charAt(1));
} else if (i == 5){
dash = dash+ Character.toString(randomStr.charAt(4));
} else {
dash = dash + "?";
}
}
final String displayVal = dash;
textView.setText(displayVal); // Displaying string with question mark with 2nd and 5th character only
gridview = (GridView) findViewById(R.id.gridview);
final String[] mAlphabets = new String[]{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
final ArrayList<String> array_list = new ArrayList<String>(Arrays.asList(mAlphabets));
final ArrayAdapter arrayAdapter = new ArrayAdapter (getApplicationContext(),android.R.layout.simple_list_item_1,array_list);
gridview.setNumColumns(8);
gridview.setBackgroundColor(Color.BLUE);
gridview.setGravity(Gravity.CENTER);
gridview.setAdapter(arrayAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
String finalDisplayVal = displayVal;
int count = 0;
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final ProgressDialog mProgressDialog = new ProgressDialog(PlayActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Checkinggg...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
long delayInMillis = 1000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mProgressDialog.dismiss();
}
}, delayInMillis);
String itemValue = (String) gridview.getItemAtPosition(position);
array_list.remove(position); // Removing character from 26 alphabets which is clicked by user
arrayAdapter.notifyDataSetChanged(); // Reset gridview
if(randomStr.contains(itemValue)){ // If selected alphabets exists in string
for(int k=0; k<strLength; k++){
if(Character.toString(randomStr.charAt(k)).equalsIgnoreCase(itemValue)){
int charPos = randomStr.indexOf(itemValue);
while(charPos >= 0){
finalDisplayVal = replaceCharAt(finalDisplayVal, charPos, itemValue);
textView.setText(finalDisplayVal);
charPos = randomStr.indexOf(itemValue, charPos + 1);
}
}
}
checkWinCount(); // Checking if User Wins
} else {
count++;
int remVal = 4-count;
remainingChance.setText("Not Exist, You have " + remVal + " chance(s) left.");
}
checkLoseCount(); // Checking if User Lose
}
public String replaceCharAt(String s, int pos, String c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
}
public void checkLoseCount() {
if(count > 3) {
Toast.makeText(PlayActivity.this, "You Loose, Value is: "+randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
}
public void checkWinCount(){
if(randomStr.equalsIgnoreCase(finalDisplayVal)){
Toast.makeText(PlayActivity.this, "Hurray!!! You WIN... It's "+randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity.this, MainActivity.class);
startActivity(goBack);
}
}
});
}
}
AsyncTask Code;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import android.os.AsyncTask;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class PlayActivity1 extends AppCompatActivity {
GridView gridview;
TextView textView;
TextView result;
TextView remainingChance;
Button giveup;
Button goback;
int count = 0;
String randomStr;
String finalDisplayVal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.play);
textView = (TextView) findViewById(R.id.blanks);
result = (TextView) findViewById(R.id.result);
remainingChance = (TextView) findViewById(R.id.remainingChance);
giveup = (Button) findViewById(R.id.giveup);
goback = (Button) findViewById(R.id.goback);
goback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
});
String dash = "";
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String easyArray[] = bundle.getStringArray("easy");
final String randomStr = easyArray[new Random().nextInt(easyArray.length)]; // Getting a random string from Array
giveup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
result.setText(randomStr); // By clicking on Give up button, it displays the actual word & a message Go Back and try again
remainingChance.setText("Go Back and try again");
}
});
final Integer strLength = randomStr.length();
// Creating string with question mark with 2nd and 5th character only
for (int i = 1; i <= strLength; i++) {
if (i == 2) {
dash = dash + Character.toString(randomStr.charAt(1));
} else if (i == 5) {
dash = dash + Character.toString(randomStr.charAt(4));
} else {
dash = dash + "?";
}
}
final String displayVal = dash;
textView.setText(displayVal); // Displaying string with question mark with 2nd and 5th character only
gridview = (GridView) findViewById(R.id.gridview);
final String[] mAlphabets = new String[]{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};
final ArrayList<String> array_list = new ArrayList<String>(Arrays.asList(mAlphabets));
final ArrayAdapter arrayAdapter = new ArrayAdapter(getApplicationContext(), android.R.layout.simple_list_item_1, array_list);
gridview.setNumColumns(8);
gridview.setBackgroundColor(Color.BLUE);
gridview.setGravity(Gravity.CENTER);
gridview.setAdapter(arrayAdapter);
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
AsyncTaskRunner runner = new AsyncTaskRunner();
String finalDisplayVal = displayVal;
runner.execute(finalDisplayVal);
String itemValue = (String) gridview.getItemAtPosition(position);
array_list.remove(position); // Removing character from 26 alphabets which is clicked by user
arrayAdapter.notifyDataSetChanged(); // Reset gridview
if (randomStr.contains(itemValue)) { // If selected alphabets exists in string
for (int k = 0; k < strLength; k++) {
if (Character.toString(randomStr.charAt(k)).equalsIgnoreCase(itemValue)) {
int charPos = randomStr.indexOf(itemValue);
while (charPos >= 0) {
finalDisplayVal = replaceCharAt(finalDisplayVal, charPos, itemValue);
textView.setText(finalDisplayVal);
charPos = randomStr.indexOf(itemValue, charPos + 1);
}
}
}
checkWinCount(); // Checking if User Wins
} else {
count++;
int remVal = 4 - count;
remainingChance.setText("Not Exist, You have " + remVal + " chance(s) left.");
}
checkLoseCount(); // Checking if User Lose
}
});
}
public String replaceCharAt(String s, int pos, String c) {
return s.substring(0, pos) + c + s.substring(pos + 1);
}
public void checkLoseCount() {
if (count > 3) {
Toast.makeText(PlayActivity1.this, "You Loose, Value is: " + randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
}
public void checkWinCount() {
if (randomStr.equalsIgnoreCase(finalDisplayVal)) {
Toast.makeText(PlayActivity1.this, "Hurray!!! You WIN... It's " + randomStr, Toast.LENGTH_LONG).show();
Intent goBack = new Intent(PlayActivity1.this, MainActivity.class);
startActivity(goBack);
}
}
private class AsyncTaskRunner extends AsyncTask<String, String, ProgressDialog> {
#Override
protected ProgressDialog doInBackground(String... params) {
final ProgressDialog mProgressDialog = new ProgressDialog(PlayActivity1.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Checkinggg...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
try {
long delayInMillis = 1000;
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
mProgressDialog.dismiss();
}
}, delayInMillis);
}catch (Exception e){
e.printStackTrace();
}
return mProgressDialog;
}
}
}
It didn't showing up any error. however when I run my application, there is no result appear from my listView. I think,the mistake is because of i didn't use the correct way doing switch case statement. here is my code.
QuickSearch.java
package com.example.awesome;
import java.io.IOException;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class QuickSearch extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//-------------------------------------------------------------------------
// Initiate database data
initiateDb();
//---------------------------------------------------------------------------
// Declaration of view
final Button qsfaculty, qscollege;
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_search);
//---------------------------------------------------------------------------
// Get reference
qsfaculty = (Button) this.findViewById(R.id.button1);
qsfaculty.setOnClickListener(this);
qscollege = (Button) this.findViewById(R.id.button2);
qscollege.setOnClickListener(this);
}
public void onClick(View v) {
char ch = 0;
View qsfaculty = null;
View qscollege = null;
if(v == qsfaculty){
ch = 'a';
}
else if (v == qscollege)
{ch = 'b';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
//---------------------------------------------------------------------------
// Initiate database data
public void initiateDb() {
DatabaseHandler myDbHandler = new DatabaseHandler(this);
try {
myDbHandler.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHandler.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
Log.d("Initiate", "UKM Location Count: " + myDbHandler.getUkmLocationCount());
myDbHandler.close();
}
//------------------------------------------------------------------------------
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quick_search, menu);
return true;
}
}
SearchLocation.java
package com.example.awesome;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class SearchLocation extends ListActivity {
//------------------------------------------------------------------
// Declaration
public static UkmLocation selectedPOI = null;
final DatabaseHandler db = new DatabaseHandler(this);
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
final ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> results_id = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_location);
final Intent c = new Intent(SearchLocation.this, LocationDetail.class);
//------------------------------------------------------------------
// Link editText to layout item
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
//------------------------------------------------------------------
// Reading Poi
Log.d("Reading", "Reading all Kategori ..");
int value = 0;
switch(value) {
case 'a' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case 'b' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}
//------------------------------------------------------------------
// Set list arrayAdapter to adapter
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
//------------------------------------------------------------------
// Set ListView from ListActivity
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//------------------------------------------------------------------
// Set click event from listView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.d("test", "position:" + position);
Log.d("test", "actualname:" + db.getUkmLocationByName(adapter.getItem(position)).getName());
// String poiID = results_id.get(position);
String poiID = db.getUkmLocationByName(adapter.getItem(position)).getID();
setSelectedPoi(poiID);
startActivity(c);
}
});
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public UkmLocation getSelectedPoi() {
return selectedPOI;
}
public void setSelectedPoi(String poiID) {
selectedPOI = db.getUkmLocation(poiID);
Log.d("test2", "_id:" + db.getUkmLocation(poiID).getID());
Log.d("test2", "Name:" + db.getUkmLocation(poiID).getName());
// Closing db
db.close();
}
}
i think,the if else statement inside QuickSearch.java is already correct. the problem at the switch case statement at SearchLocation.java
please help me solve this.
int value = 0;
switch(value) {
You are setting the value over which you switch to 0 so it is equivalent to doing switch(0) {...
Find out what that value is supposed to be and initialise it properly.
Also, value is of type int but your switch uses chars ('a', 'b'), so you need to either have value be a char and initialise it properly or have it be an int, initialise it properly and change your switch cases to use ints.
First you do int value = 0; so value is 0. So it is not 'a' nor 'b'.
You have to get the value from the intent as you put it in extras. i.putExtra("value",ch);
something like
char value;
Bundle extras = getIntent().getExtras();
if (extras != null) {
value = extras.getIntgetChar("value");
}
here, i already solve my problem..
QuickSearch.java
public void onClick(View v) {
int ch = 0;
/*View qsfaculty = null;
View qscollege = null;*/
if(v == qsfaculty){
ch = '1';
}
else if (v == qscollege)
{ch = '2';}
Intent i = new Intent(this,SearchLocation.class);
i.putExtra("value",ch);
startActivity(i);
}
SearchLocation.java
Bundle extras = getIntent().getExtras();
int value = extras.getInt("value");
switch(value) {
case '1' :
List<UkmLocation> faculty = db.getCategoryFaculty();
for(UkmLocation k : faculty) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
case '2' :
List<UkmLocation> college = db.getCategoryCollege();
for(UkmLocation k : college) {
results.add(k.getName());
results_id.add(k.getID());
}
break;
}
Hey guys I know there are many java programs for the factorial of a number...but I am facing problem with android. Following is my code....Thanks
package com.droidacid.apticalc.aptitudes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.droidacid.apticalc.R;
public class AptiFactorial extends Activity implements android.view.View.OnClickListener{
EditText number;
TextView answer;
Button calculate;
long factorial = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apti_factorial);
initialize();
calcFactorial();
}
private void initialize() {
number = (EditText) findViewById(R.id.et_apti_number);
answer = (TextView) findViewById(R.id.tv_apti_answer);
calculate = (Button) findViewById(R.id.b_apti_calc);
calculate.setOnClickListener(this);
}
private void calcFactorial() {
if (number.getText().toString().equals("")) number.setText("0");
int num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
#Override
public void onClick(View v) {
calcFactorial();
answer.setText("Factorial of " + number.getText().toString() + " is : " + factorial);
}
}
This is my code and I need to know a way around for setting the hint instead of 0, but if I remove if (number.getText().toString().equals("")) number.setText("0");
then getting NullPointerException...
Also on the first go its calculating correctly but If I calculate again then getting wrong answer. I think some loop issue because I am directly using the value of factorial.
Please help thanks
Forget all that equal stuff, cover all basis and do it like this:
package com.droidacid.apticalc.aptitudes;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.droidacid.apticalc.R;
public class AptiFactorial extends Activity implements android.view.View.OnClickListener{
EditText number;
TextView answer;
Button calculate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.apti_factorial);
initialize();
}
private void initialize() {
number = (EditText) findViewById(R.id.et_apti_number);
number.setHint("Enter number to be factorialized :P")
answer = (TextView) findViewById(R.id.tv_apti_answer);
calculate = (Button) findViewById(R.id.b_apti_calc);
calculate.setOnClickListener(this);
}
private long calcFactorial() {
long factorial = 1;
try {
factorial = Long.parseLong(number.getText().toString());
for(int i=factorial-1; i>0; i--){
factorial = i * factorial;
}
} catch (NumberFormatException e) {
Toast.makeText(this, "Incorrect Input", Toast.LENGTH_LONG).show();
} finally {}
return factorial;
}
#Override
public void onClick(View v) {
answer.setText("Factorial of " + number.getText().toString() + " is : " + calcFactorial());
}
Do something like.
private void calcFactorial() {
int num = 0;
if (!number.getText().toString().equals(""))
num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
Rather than using
(number.getText().toString().equals("")) number.setText("0");
Use
(number.getText().length==0) number.setText("0");
** first go its calculating correctly but If I calculate again then getting wrong answer**
try like this
private void calcFactorial() {
factorial = 1;///Check out the line..
int num = 0;
if (!number.getText().toString().equals(""))
num = Integer.parseInt(number.getText().toString());
for(int i = 1; i<=num; i++){
factorial = i * factorial;
}
}
You need to make sure variable factorial is reinitialise to 1 .. for getting factorial for next number..
private void fact_isClicked(View view) {
if(textField.length()>0){
int ifac = Integer.parseInt(textField.getText().toString());
int fact = factorial(ifac);
tvsec.setText(String.valueOf(fact));
textField.setText(ifac+"!");
}}