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
}
Related
Please help. I want to display the correct answers in an alert dialog, if i type "rightAnswers" inside "builder.setMessage("Answer : " + rightAnswers);" an alert show "Answer: 1". Number 1 instead of the correct answer. please teach me what to put to be able to display the correct answer. thank you so much.
public class thisactivity extends AppCompatActivity {
Button choice1,choice2;
ImageView images;
List<Model> list;
int turn = 1;
int rightAnswers = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_thisactivity);
images = (ImageView) findViewById(R.id.images);
choice1 = (Button) findViewById(R.id.choice1);
choice2 = (Button) findViewById(R.id.choice2);
list = new ArrayList<>();
for (int i = 0; i < new Signsdatabase().answers.length; i++) {
list.add(new Model(new Signsdatabase().answers[i], new
Signsdatabase().signs[i]));
}
newQuestion(turn);
choice1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String alertTitle;
if(choice1.getText().toString().equalsIgnoreCase(list.get(turn -
1).getName())) {
rightAnswers = rightAnswers + 1;
alertTitle = "Correct!";
if (turn < list.size()) {
turn++;
newQuestion(turn);
} else {
Toast.makeText(thisactivity.this, "You have completed the Quiz!", Toast.LENGTH_SHORT).show();
}
}
AlertDialog.Builder builder = new
AlertDialog.Builder(thisactivity.this)
builder.setTitle(alertTitle);
builder.setMessage("Answer : " + **CORRECT ANSWERS**); <---I WANT TO DISPLAY THE CORRECT ANSWER HERE BUT I DO NOT KNOW HOW------->
builder.setIcon(R.drawable.pic);
builder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
}
});
}
});
choice2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (choice2.getText().toString().equalsIgnoreCase(list.get(turn - 1).getName())) {
rightAnswers = rightAnswers + 1;
if (turn < list.size()) {
turn++;
newQuestion(turn);
} else {
Toast.makeText(thisactivity.this, "You have completed the Quiz!", Toast.LENGTH_SHORT).show();
getResults();
}
} else {
}
AlertDialog.Builder builder = new
AlertDialog.Builder(Roadsigns.this)
builder.setTitle(alertTitle);
builder.setMessage("Answer : " + **CORRECT ANSWERS**); <---I WANT TO DISPLAY THE CORRECT ANSWER HERE BUT I DO NOT KNOW HOW------->
builder.setIcon(R.drawable.pic);
builder.setPositiveButton("OK", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
}
});
builder.setCancelable(false);
builder.show();
}
});
}
............
And this is my Signsdatabase
public class Signsdatabase {
Integer[] signs ={
R.drawable.q1,
R.drawable.q2,
R.drawable.q3,
};
String[] answers = {
"Ans1",
"Ans2",
"Ans3",
};
}
Make this change in alter dialog.
make Signsdatabase object or make static in answer array.
builder.setMessage("Answer : " + Signsdatabase.answers[rightAnswers]);
You display the index of the right answer, you need to get the item from the list at the corresponding position:
builder.setMessage("Answer : " + signsdatabase.answers[rightAnswers]);
builder.setMessage("Answer : " + list[rightAnswers]);// it also check.
And you also need to initialize signsdatabase before
signsdatabase = new Signsdatabase();
Suppose you have the correct index of the answer You can do one of the following :
One
Create an object of SignsDatabase :
signsDb = new Signsdatabase();
With index i of correct answer :
builder.setMessage("Answer : "+ signDb.answers[i];
Two
If you do not want to create an instance of SignDatabase, you can declare the answers as static variable so :
public class SignDatabase{
... //some code here
public static String[] answers = ["Abc","xyz"];
}
Then access it directly by calling :
builder.setMessage(SignDatabase.answers[i]);
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.
I am making a math quiz where a mathematical question will be asked in the form of a formula. I put my questions in an ArrayList:
public class DEasy extends AppCompatActivity {
private TextView countLabel;
private TextView questionLabel;
private Button answerBtn1;
private Button answerBtn2;
private Button answerBtn3;
private Button answerBtn4;
private String rightAnswer;
private int rightAnswerCount = 0;
private int quizCount = 1;
static final private int QUIZ_COUNT = 10;
ArrayList<ArrayList<String>> quizArray = new ArrayList<>();
String quizData[][] = {
{"x", "1", "0", "x", "-1"},
{"x²", "2x", "x", "2/x²", "2x²"},
{"64", "0", "1", "64", "8"},
{"x² + 5x", "2x + 5", "7x", "2x", "½x + 5"},
{"19x", "19", "x", "0", "x + 19"},
{"642", "34", "97", "5x-2", "1"}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deasy);
countLabel = (TextView) findViewById(R.id.countLabel);
questionLabel = (TextView) findViewById(R.id.questionLabel);
answerBtn1 = (Button) findViewById(R.id.answerBtn1);
answerBtn2 = (Button) findViewById(R.id.answerBtn2);
answerBtn3 = (Button) findViewById(R.id.answerBtn3);
answerBtn4 = (Button) findViewById(R.id.answerBtn4);
for (int i = 0; i < quizData.length; i++) {
ArrayList<String> tmpArray = new ArrayList<>();
tmpArray.add(quizData[i][0]);
tmpArray.add(quizData[i][1]);
tmpArray.add(quizData[i][2]);
tmpArray.add(quizData[i][3]);
tmpArray.add(quizData[i][4]);
quizArray.add(tmpArray);
}
showNextQuiz();
}
public void showNextQuiz() {
countLabel.setText( getString(R.string.question) + " " + quizCount + ".");
Random random = new Random();
int randomNum = random.nextInt(quizArray.size());
ArrayList<String> quiz = quizArray.get(randomNum);
questionLabel.setText(quiz.get(0));
rightAnswer = quiz.get(1);
quiz.remove(0);
Collections.shuffle(quiz);
answerBtn1.setText(quiz.get(0));
answerBtn2.setText(quiz.get(1));
answerBtn3.setText(quiz.get(2));
answerBtn4.setText(quiz.get(3));
quizArray.remove(randomNum);
}
public void checkAnswer(View view){
Button answerBtn = (Button) findViewById(view.getId());
String btnText = answerBtn.getText().toString();
String alertTitle;
if (btnText.equals(rightAnswer)){
alertTitle = "Correct";
rightAnswerCount++;
}
else {
alertTitle = "Wrong";
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(alertTitle);
builder.setMessage("Answer: " + rightAnswer);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (quizCount == QUIZ_COUNT){
Intent intent = new Intent(getApplicationContext(), DResult.class);
intent.putExtra("RIGHT_ANSWER_COUNT", rightAnswerCount);
startActivity(intent);
}
else{
quizCount++;
showNextQuiz();
}
}
});
builder.setCancelable(false);
builder.show();
}
}
As you can see I tried to make the formula x^2, this wil not be shown as x with a small exponent 2 but as x^2. This x^2 is not what I want. How can I used for example html in this arraylist to achieve this goal. Or is there another way?
Thanks aton!
Here in replacement of "^" we can use this: "∧".
So now replace code at where you accessing this string array in Adapter as:
Html.fromHtml(quizArray[][])
Thanks and happy coding
EDITED:
Here change it as:
questionLabel.setText(Htm.fromHtml(quiz.get(0)));
Just it will work
I'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.
I checked other similar tags with almost same title. Those answers were not relevant
When setting element at one position of array, both the elements have the same value.
public class LogActivity extends Activity
{
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
startStopButton = (Button) findViewById(R.id.btnStart);
loggingStatusText = (TextView) findViewById(R.id.logStatusText);
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL);
sensorValues=new ArrayList<float[]>(sensorList.size());
sensorValsArray=new float[sensorList.size()][];
sensorNameList = new ArrayList<String>();
selectedSensorNames = new ArrayList<String>();
for (Sensor itemSensor : sensorList)
{
if (itemSensor != null)
{
sensorNameList.add(itemSensor.getName());
}
}
showSensorList();
}
private void showSensorList()
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(R.drawable.ic_launcher);
builder.setMultiChoiceItems((CharSequence[]) sensorNameList
.toArray(new CharSequence[sensorNameList.size()]),
new boolean[sensorNameList.size()],
new DialogInterface.OnMultiChoiceClickListener()
{
public void onClick(DialogInterface dialog,
int whichButton, boolean isChecked)
{
if (isChecked)
{
if (!selectedSensorNames.contains(sensorNameList
.get(whichButton)))
selectedSensorNames.add(sensorNameList
.get(whichButton));
} else
{
if (selectedSensorNames.contains(sensorNameList
.get(whichButton)))
{
selectedSensorNames.remove(sensorNameList
.get(whichButton));
}
}
}
});
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int whichButton)
{
listeners=new SensorEventListener[selectedSensorNames.size()];
float[] tempVals = new float[] { 0, 0, 0 };
for (int i = 0; i < selectedSensorNames.size(); i++)
{
sensorValsArray[i]=tempVals;
}
showRateList();
}
});
builder.setCancelable(false);
builder.create().show();
}
void registerSensors()
{
for (Sensor sensor : sensorList)
{
if (selectedSensorNames.contains(sensor.getName()))
{
mSensorManager.registerListener(listeners[selectedSensorNames.indexOf(sensor.getName())], sensor, selectedDelay);
}
}
}
class SchedulerTask extends TimerTask
{
/*
* The task to run should be specified in the implementation of the
* run() method
*/
public void run()
{
logSensorData();
}
}
private void createLog(String fileName)
{
File root = getExternalFilesDir(null);// Get the Android external
// storage directory
Date cDate = new Date();
String bstLogFileName = fileName;
bstLogFile = new File(root, bstLogFileName);// Construct a new file for
// using the specified
// directory and name
FileWriter bstLogWriter;
logScheduler = new Timer();// Create a new timer for updating values
// from content provider
logScheduler.schedule(new SchedulerTask(),
LOG_TASK_DELAY_IN_MILLISECONDS,
getLogPeriodInMilliSeconds(selectedDelay));
}
public void logSensorData()
{
Date stampDate = new Date();
String LogPack ="\r\n";
for (int count=0;count<selectedSensorNames.size();count++)
{
LogPack += sensorValsArray[count][0] + "," + sensorValsArray[count][1] + "," + sensorValsArray[count][2] + ",";
}
LogPack += "\r\n";
try
{
F_StreamWriter.write(LogPack);
F_StreamWriter.flush();
}
catch (IOException e)
{
}
catch (NullPointerException e)
{
}
}
public void startStopLog(View v)
{
if (startStopButton.getText().equals("Start"))
{
createSensorListeners();
registerSensors();
showFilenameDialog();
} else if (startStopButton.getText().equals("Stop"))
{
stopLog();
}
}
public void startLog(String fileName)
{
createLog(fileName);
}
public void stopLog()
{
logScheduler.cancel();
logScheduler.purge();
for(int i=0;i<listeners.length;i++)
mSensorManager.unregisterListener(listeners[i]);
}
private void showFilenameDialog()
{
final Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.custom_text_input_dialog);
dialog.setCancelable(true);
final EditText fileNameInput = (EditText) dialog
.findViewById(R.id.fileNameText);
Button button = (Button) dialog.findViewById(R.id.okButton);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
startLog(nameInput);
dialog.dismiss();
}
});
dialog.show();
}
private void createSensorListeners()
{
listeners=new SensorEventListener[selectedSensorNames.size()];
for (int i = 0; i < selectedSensorNames.size(); i++)
{
listeners[i]=new SensorEventListener()
{
#Override
public void onSensorChanged(SensorEvent event)
{
sensorValsArray[selectedSensorNames.indexOf(event.sensor.getName())]=event.values;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy)
{
}
};
}
}
}
When index is 0, when set command is executed, it also changes the the value at index position '1'.
Can anyone help me with this?
Thanks in Advance,
Dheepak
When index is 0, when set command is executed, it also changes the the value at index position '1'. Can anyone help me with this?
You are definitely mistaken as to what it is causing this. Setting the value at one position of an ArrayList WILL NOT mysteriously cause the value at another position to change. It simply does not work like that.
The effect you are observing will be due to something else:
maybe the value of index is not what you expect
maybe the value of event.values is not what you expect. (Maybe you've made a mistake in the way that you create the Event objects, and they are all sharing one float[] object.)
maybe the value at position 1 was already that value
maybe you've got multiple threads updating the sensorValues list.