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]);
Related
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
}
I am developing an android project using ORMLite and i have a problem to figure out. There is a picture below and how can i use DISTINCT sql query in ORMLite?
I have some parameters giving to where condition and according to this conditions i am getting number list...
In this picture you are going to see some numbers and some of these numbers are same but i don't want to get same numbers so how can i use DISTINCT in ORMLite with where condition.
Thanks for helping
Also some of my code is like this:
private void modalShowEbat() {
dbHelper = (DBHelper) OpenHelperManager.getHelper(this, DBHelper.class);
RuntimeExceptionDao<Segment, Integer> segmentDao = dbHelper.getSegmentExceptionDao();
List<Segment> list = segmentDao.queryForEq(Constant.QUERY_SEGMENT, editTextSegment.getText().toString().trim());
final CharSequence items[] = new CharSequence[list.size()];
for (int i = 0; i < list.size(); i++) {
items[i] = list.get(i).getColumnEbat();
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Segment seçiniz");
builder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// the user clicked on colors[which]
editTextEbat.setText(items[which].toString());
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
}
});
alertDialog = builder.create();
alertDialog.show();
}
This is my image of result
Use this -
segmentDao.queryBuilder().distinct().where().eq("name", "value").query();
Hi I solved my problem with below code. Maybe you can say this is long way for this. I wrote my code like below because i couldn't do other ways(using .distinct() method in ORMLite or other ORMLite's method)
If you have any other ways to solve this, i am waiting your suggestions. Thanks for everybody, happy coding...
private void modalShowEbat() {
dbHelper = (DBHelper) OpenHelperManager.getHelper(this, DBHelper.class);
RuntimeExceptionDao<Segment, Integer> segmentDao = dbHelper.getSegmentExceptionDao();
List<Segment> list = segmentDao.queryForEq(Constant.QUERY_SEGMENT, editTextSegment.getText().toString().trim());
GenericRawResults<String[]> rawResults = segmentDao.queryRaw("SELECT DISTINCT Ebat FROM Segment WHERE Segment = ? ", editTextSegment.getText().toString().trim());
final CharSequence items[] = new CharSequence[list.size()];
int i = 0;
for (String[] resultColumns : rawResults) {
String author = resultColumns[0];
items[i] = author;
i++;
}
int newLenght = 0;
for (int j = 0; j < items.length; j++) {
if (items[j] != null) {
newLenght++;
}
}
final CharSequence newItems[] = new CharSequence[newLenght];
for (int j = 0; j < newLenght; j++) {
if (items[j] != null) {
newItems[j] = items[j];
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Choose Segment");
builder.setSingleChoiceItems(newItems, 0, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// the user clicked on colors[which]
editTextEbat.setText(newItems[which].toString());
if (alertDialog != null && alertDialog.isShowing()) {
alertDialog.dismiss();
}
}
});
alertDialog = builder.create();
alertDialog.show();
}
So, I am creating a little trivia game for learning purposes, but I ran into a problem.
First, I had a specific Android Fragment obtaining the data from JSON, and I will simply use that data on the callback method and display it on TextViews and Buttons. Everything was working fine, however, every time I returned to that fragment, the same questions would be there. So I decided to handle that in a better way outside of the callback method.
The problem here is that apparently my Arrays are either null or their lengths is zero. Which is weird, because according to my LOG, data is being passed to those arrays on the callback method.
Here's my full fragment code. Thanks!
public class GameFragment extends Fragment {
private TextView txtQuestion;
private Button btnAnswer1;
private Button btnAnswer2;
private Button btnAnswer3;
private Button btnAnswer4;
private Questions[] gameQuestions;
private Questions[] animeQuestions;
private Questions[] techQuestions;
private Questions[] movieQuestions;
private Questions[][] gameCategories = new Questions[4][];
int correctAnswer = -1;
private TransparentProgressDialog progressBar;
private Handler handler;
private Runnable runnable;
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
gameCategories[0] = new Questions[myApiData.getCategory()[0].getQuestions(0).length];
gameCategories[1] = new Questions[myApiData.getCategory()[1].getQuestions(1).length];
gameCategories[2] = new Questions[myApiData.getCategory()[2].getQuestions(2).length];
gameCategories[3] = new Questions[myApiData.getCategory()[3].getQuestions(3).length];
//gameCategories = new Questions[][] {gameQuestions, animeQuestions, techQuestions, movieQuestions};
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
gameCategories[i][j] = myApiData.getCategory()[i].getQuestions(i)[j];
//Log.d("GameFragment", "gameCategories[i][j] - gameCategories["+i+"]["+j+"]: " + gameCategories[i][j].getQuestion());
}
}
//displayQuestion();
progressBar.dismiss();
displayQuestion();
}
#Override
public void failure(RetrofitError error) {
Log.d("GameScreen", "Callback failed!");
}
};
public GameFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_game, container, false);
txtQuestion = (TextView) view.findViewById(R.id.txtQuestion);
btnAnswer1 = (Button) view.findViewById(R.id.btnAnswer1);
btnAnswer2 = (Button) view.findViewById(R.id.btnAnswer2);
btnAnswer3 = (Button) view.findViewById(R.id.btnAnswer3);
btnAnswer4 = (Button) view.findViewById(R.id.btnAnswer4);
btnAnswer1.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer2.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer3.setOnClickListener(new View.OnClickListener() {
#Override public void onClick(View view) { checkAnswer(view); } });
btnAnswer4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checkAnswer(view);
}
});
handler = new Handler();
progressBar = new TransparentProgressDialog(getActivity(), R.drawable.loading_spinner);
runnable = new Runnable() {
#Override
public void run() {
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
};
//launchRingDialog();
//RestClient.get().getQuestions(cb);
// Inflate the layout for this fragment
return view;
}
public void launchRingDialog() {
new Thread(new Runnable() {
public void run(){
try {
Log.d("Thred", "Try");
progressBar.show();
RestClient.get().getQuestions(cb);
//Thread.sleep(10000);
} catch (Exception e) {
}
//progressBar.dismiss();
}
}).start();
}
public void checkAnswer(View v){
switch(v.getId()){
case R.id.btnAnswer1:
if(correctAnswer == 1){
feedback(true, btnAnswer1);
}else {
feedback(false, btnAnswer1);
}
break;
case R.id.btnAnswer2:
if(correctAnswer == 2){
feedback(true, btnAnswer2);
}else {
feedback(false, btnAnswer2);
}
break;
case R.id.btnAnswer3:
if(correctAnswer == 3){
feedback(true, btnAnswer3);
}else {
feedback(false, btnAnswer3);
}
break;
case R.id.btnAnswer4:
if(correctAnswer == 4){
feedback(true, btnAnswer4);
}else {
feedback(false, btnAnswer4);
}
break;
default: txtQuestion.setText("Error");
break;
}
}
public void feedback(Boolean correct, Button btn){
if(correct){
btn.setBackgroundColor(Color.GREEN);
btn.setText("CORRECT!");
}else{
btn.setBackgroundColor(Color.RED);
btn.setText("WRONG!");
}
}
#Override
public void onResume() {
super.onResume();
//displayQuestion();
}
public void displayQuestion(){
Random randomizer = new Random();
int randomQuestion;
int category = GTMain.choosenCategory;
if(category == 5){
category = randomizer.nextInt(4);
}
randomQuestion = randomizer.nextInt(25);
Log.d("displayQuestion", "Before if statements");
if(gameCategories != null && gameCategories.length != 0) {
Log.d("displayQuestion", "First if");
if(gameCategories[category] != null && gameCategories[category].length != 0){
Log.d("displayQuestion", "Second if");
txtQuestion.setText(gameCategories[category][randomQuestion].getQuestion());
correctAnswer = gameCategories[category][randomQuestion].getCorrectAnswer();
Log.d("displayQuestion()", "correctAnswer: " + correctAnswer);
btnAnswer1.setText(gameCategories[category][randomQuestion].getAnswers().getA1());
btnAnswer2.setText(gameCategories[category][randomQuestion].getAnswers().getA2());
btnAnswer3.setText(gameCategories[category][randomQuestion].getAnswers().getA3());
btnAnswer4.setText(gameCategories[category][randomQuestion].getAnswers().getA4());
}
}
}
}
PS: On my main activity, I check to see which fragment should be loaded. If it's the fragment that contains the components to display the questions and answer (the one from the code above), I call the following method: gameFragment.launchRingDialog(); (and yes, I have created an instance of my GameFragment fragment before calling that method!)
When onResume() is called, your RestClient.get().getQuestions(cb) is still running in background, and your call displayQuestion(), so of course nothing is shown.
Can you put displayQuestion() inside success() of your callback?
Callback cb = new Callback<MyApiData>(){
#Override
public void success(MyApiData myApiData, Response response) {
....
for(int i = 0; i < 4 ; i++){
for(int j = 0; j < gameCategories[i].length ; j++){
...
}
}
displayQuestion();
}
....
};
I would also suggest you to remove displayQuestion() in onResume() method.
I have an alertdialog with multiple choices, I store the user's choices on an ArrayList of strings, and I want to pass the stored arraylist to the host activity (I will use the array's elements to query my database)..
When i run my app, i get an ArrayIndexOutOfBoundsException (may be the index is -1..), I'm not sure if it's the loop, or if i did not pass the arraylist correctly from the alertdialog...
can you guys take a look ? here is my function :
public void onOkay(ArrayList<String> selected) {
StringBuilder stringBuilder = new StringBuilder();
if (selected.size() != 0) {
for (int i = 0; i < selected.size(); i++) {
String categories = selected_items_array[selected.indexOf(i)];
stringBuilder = stringBuilder.append(" " + categories);
}
Toast.makeText(this, "You have selected: "
+ stringBuilder.toString(), Toast.LENGTH_SHORT).show();
}
}
logcat :
java.lang.ArrayIndexOutOfBoundsException: length=6; index=-1
at com.hichamridouane.smartshop.MainActivity.onOkay(MainActivity.java:164)
at com.hichamridouane.smartshop.TimelineSettings$2.onClick(TimelineSettings.java:71)
here is my dialogfragment class.
and here is my host activity.(as I said, i'm not sure if i'm passing correctly the arraylist to the host activity)
thanks !
It looks really strange to me, especially in
String categories = selected_items_array[selected.indexOf(i)];
From JavaDocs about indexOf
Returns the index of the first occurrence of the specified element
in this list, or -1 if this list does not contain the element.
More formally, returns the lowest index <tt>i</tt> such that
<tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,
or -1 if there is no such index.
So, you try to find element in your selected_items_array (not correct name in Java)
in first iteration i == 0, selected_items_array have no such element => indexOf return -1. Array can't have element with index = -1, it starts from 0. So you have your ArrayIndexOutOfBoundsException
Problem solved. Had to use Arraylists of integers in my activity and my dialogfragment.
here is what i did in my DialogFragment class:
public class TimelineSettings extends DialogFragment {
ArrayList<Integer> selected_categories = new ArrayList<Integer>();
boolean[] itemsChecked = {false, false, false, false, false, false};
// this interface to communicate with the host activity.
public interface dialoglistener {
public void onOkay(ArrayList<Integer> selected);
public void onCancel();
}
dialoglistener mlistener;
//this function is to instantiate the dialoglistener
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mlistener = (dialoglistener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement dialogListener");
}
}
My multichoice dialog :
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
for(int i=0;i<itemsChecked.length;i++){
if(selected_categories.contains((String)String.valueOf(i)))
itemsChecked[i]=true;
}
// Set the dialog title
builder.setTitle("Choisissez vos paramètres")
.setMultiChoiceItems(R.array.categories, itemsChecked,
new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int indexselected,
boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
if(!selected_categories.contains(indexselected)){
selected_categories.add(indexselected);
itemsChecked[indexselected]=true;
}
} else if (selected_categories.contains(indexselected)) {
// Else, if the item is already in the array, remove it
selected_categories.remove(indexselected);
itemsChecked[indexselected]=false;
}
}
})
// Set the action buttons
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mlistener.onOkay(selected_categories);
}
})
.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mlistener.onCancel();
}
});
return builder.create();
}
On my host activity, I implemented the fragment's interface :
#Override
public void onCreate(Bundle savedInstanceState) {
/* some fancy stuff */
Resources res = getResources();
selectedArray = res.getStringArray(R.array.categories);
}
Getting the selected items (and show them on a toast, just for testing) :
#Override
public void onOkay(ArrayList<Integer> selected) {
StringBuilder stringBuilder = new StringBuilder();
if (selected.size() != 0) {
for (int i = 0; i < selected.size(); i++) {
String categories = selectedArray[selected.get(i)];
stringBuilder = stringBuilder.append(" " + categories);
}
Toast.makeText(this, "You have selected: "
+ stringBuilder.toString(), Toast.LENGTH_SHORT).show();
}
}
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.