ArrayIndexOutOfBoundsException / passing arraylist from alertdialog to activity - java

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();
}
}

Related

Add Correct answers to Alert Dialog

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]);

ArrayList size becomes 0 inside onClick

public void confirmDelete(final ArrayList<Rec> list,final String d){
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure, You wanted to delete "+list.size()+" item(s)?");
System.out.println("list size " + list.size());
alertDialogBuilder.setPositiveButton("yes",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
VaravuSelavu userDB = new VaravuSelavu(getBaseContext());
System.out.println("list size "+ list.size()+ " "+d);
if (userDB.deleteIncome(list, d))
{
re=userDB.displayIncome(dateView.getText().toString());
if (re != null) {
incomeAdapter = new ListViewAdapter(re, getBaseContext());
incomeAdapter.notifyDataSetChanged();
}
}
I want to pass the list inside the deleteIncome method.. the first print statement shows the correct size of the list... but inside the onClick method,the list size becomes 0... How to access the ArrayList inside onClick?

dynamic way to work with checkboxes

I have alertdialog with custom checkboxes, i need to pass the selected choices to the host activity, and persist the selected choices. here is my code :
public class TimelineSettings extends DialogFragment {
ArrayList<Integer> selected_categories = new ArrayList<Integer>();
boolean[] itemsChecked = {false, false, false, false, false, false};
private FlatCheckBox fourniture,nourriture,voyages,habillement,medias,autres;
public interface dialoglistener {
public void onOkay(ArrayList<Integer> selected);
public void onCancel();
}
dialoglistener mlistener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// ensure that the host activity implements the callback interface
try {
// Instantiate the dialogListener so we can send events to the host
mlistener = (dialoglistener) activity;
} catch (ClassCastException e) {
// if activity doesn't implement the interface, throw an exception
throw new ClassCastException(activity.toString()
+ " must implement dialogListener");
}
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = LayoutInflater.from(getActivity());
View custom = inflater.inflate(R.layout.custom_settings,null);
fourniture = (FlatCheckBox)custom.findViewById(R.id.fourniture);
nourriture = (FlatCheckBox)custom.findViewById(R.id.nourriture);
voyages = (FlatCheckBox)custom.findViewById(R.id.voyages);
habillement = (FlatCheckBox)custom.findViewById(R.id.habillement);
medias = (FlatCheckBox)custom.findViewById(R.id.medias);
autres = (FlatCheckBox)custom.findViewById(R.id.autres);
if (selected_categories.contains(0)){
fourniture.setChecked(true);
}
if (selected_categories.contains(1)){
nourriture.setChecked(true);
}
if (selected_categories.contains(2)){
voyages.setChecked(true);
}
if (selected_categories.contains(3)){
habillement.setChecked(true);
}
if (selected_categories.contains(4)){
medias.setChecked(true);
}
if (selected_categories.contains(5)){
autres.setChecked(true);
}
builder.setView(custom)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
checkboxState();
mlistener.onOkay(selected_categories);
}
})
.setNegativeButton("Annuler", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mlistener.onCancel();
}
});
return builder.create();
}
public void checkboxState(){
if (fourniture.isChecked()){
if(!selected_categories.contains(0)){
selected_categories.add(0);
itemsChecked[0]=true;
}
else if (selected_categories.contains(0)) {
// Else, if the item is already in the array, remove it
selected_categories.remove(0);
itemsChecked[0]=false;
}
}
if (nourriture.isChecked()){
if(!selected_categories.contains(1)){
selected_categories.add(1);
itemsChecked[1]=true;
}
else if (selected_categories.contains(1)) {
selected_categories.remove(1);
itemsChecked[1]=false;
}
}
if (voyages.isChecked()){
if(!selected_categories.contains(2)){
selected_categories.add(2);
itemsChecked[2]=true;
}
else if (selected_categories.contains(2)) {
selected_categories.remove(2);
itemsChecked[2]=false;
}
}
if (habillement.isChecked()){
if(!selected_categories.contains(3)){
selected_categories.add(3);
itemsChecked[3]=true;
}
else if (selected_categories.contains(3)) {
selected_categories.remove(3);
itemsChecked[3]=false;
}
}
if (medias.isChecked()){
if(!selected_categories.contains(4)){
selected_categories.add(4);
itemsChecked[4]=true;
}
else if (selected_categories.contains(4)) {
selected_categories.remove(4);
itemsChecked[4]=false;
}
}
if (autres.isChecked()){
if(!selected_categories.contains(5)){
selected_categories.add(5);
itemsChecked[5]=true;
}
else if (selected_categories.contains(5)) {
selected_categories.remove(5);
itemsChecked[5]=false;
}
}
}
}
this code works fine, but it does not look so! too much if elses...
my question is if there is a way to use a loop on my checkboxes to get their state, and then to set the elements of the array itemschecked to true/false for the persistency.
thanks !
Keep an array of FlatCheckBoxs:
private FlatCheckBox [] check = new FlatCheckBox[6];
and use an enum to retrive what checkbox you need:
private enum Names
{
fourniture(0),
nourriture(1),
voyages(2),
habillement(3),
medias(4),
autres(5);
private int val;
Names(int a)
{
val = a;
}
public int get()
{
return val;
}
};
Now use:
public void checkboxState()
{
for(FlatCheckBox fb : check)
{
if (fb.isChecked())
{
}
}
}
And you can access individual elements of the array like this:
FlatCheckBox fourniture = check[Names.fourniture.get()];
I would use the enum for a better readability, using [0], [1] ... can be confusing and lead to programming errors.

Add a switch statement to Navigation Drawer

I am learning to program for android and java in general and need some help with the "Navigation Drawer" on android.
I am struggling to add a switch statement to the click listener for the drawer items, The code I am using is taken from an example here: http://hmkcode.com/android-creating-a-navigation-drawer/
How exactly should I handle the switch statement so as to launch new activities from the touch of one of the items?
Thank you
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
actionBarDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Call ActionBarDrawerToggle.onOptionsItemSelected(), if it returns true
// then it has handled the app icon touch event
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, ((TextView)view).getText(), Toast.LENGTH_LONG).show();
drawerLayout.closeDrawer(drawerListView);
}
}
Edit....
public void onItemClick(AdapterView parent, View view, int position, long id) {
switch (position){
case 0:
new DataTask(this).execute();
MainActivity.this.finish();//Set this Activity to Finish so no loop back
Intent intent=new Intent(MainActivity.this,SplashScreen.class);
startActivity(intent);
System.out.println("Click working");
case 1:
//do stuff
default:
break;
}
The new DataTask(this).execute(); is giving this warning....The constructor DataTask(MainActivity.DrawerItemClickListener) is undefined. I am unsure why?
DataTask Class...
public class DataTask extends AsyncTask<Void, Void, Integer> {
Context context;
DataTask(Context context) {
this.context = context.getApplicationContext();
}
// Global Int for counting how many Tasks have been completed
int asynCount = 0;
ArrayList<String> arr_dataVts=new ArrayList<String>();
ArrayList<String> arr_dataNtm=new ArrayList<String>();
ArrayList<String> arr_dataOdas=new ArrayList<String>();
ArrayList<String> arr_dataMetAll=new ArrayList<String>();
ArrayList<String> arr_dataMet3HrTask=new ArrayList<String>();
ArrayList<String> arr_dataTideTask=new ArrayList<String>();
#Override
protected Integer doInBackground(Void... params) {
//VtsAsyncTask
VtsTask task1 = new VtsTask();
task1.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//NtmAsyncTask
NtmTask task2 = new NtmTask();
task2.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//OdasAsyncTask
OdasTask task3 = new OdasTask();
task3.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//MetAllTask
MetAllTask task4 = new MetAllTask();
task4.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//Met3HrTask
Met3HrTask task5 = new Met3HrTask();
task5.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
//TideTask
TideTask task6 = new TideTask();
task6.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
return 1;
}
private class VtsTask extends AsyncTask<Void, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(Void... params) {
Document docVTS;
try {
Connection.Response response = Jsoup.connect("https://vts.mhpa.co.uk/main_movelistb.asp")
.timeout(10000)
.ignoreHttpErrors(true)
.execute();
int statusCode = response.statusCode();
if(statusCode == 200) {
docVTS = Jsoup.connect("https://vts.mhpa.co.uk/main_movelistb.asp").timeout(10000).get();
Elements tableRows = docVTS.select("table.dynlist td:eq(0),td:eq(1),td:eq(3),td:eq(4),td:eq(7),td:eq(8)");
tableRows.size();
for(int i = 1; i < 80; i++){// Only allows x results from VTS list, from 1 not 0. 0 produces needless results
String shippingList = tableRows.get(i).text() +"\n";//new line
arr_dataVts.add(shippingList);// Add value to ArrayList
};
} else {
//If can't connect for what ever reason
System.out.println("Received error code for VTS list Data : " + statusCode + " Adding Null values");
for(int i = 1; i < 80; i++){
arr_dataVts.add("No Data" + i);
}
}
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Received timeout error code for VTS list Data : Adding Null values ");
for(int i = 1; i < 80; i++){
arr_dataVts.add("No Data" + i);
}
}
return arr_dataVts;
}
#Override
protected void onPostExecute(ArrayList<String> Param) {
asynCount++;
System.out.println("Vts list Captured" + arr_dataVts + " asynCount= " + asynCount);
if (asynCount == 6){
//Start intents for main activity
System.out.println("asynCount has reached= " + asynCount + " so now starting MainActivity");
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putStringArrayListExtra("data1", arr_dataVts);
intent.putStringArrayListExtra("data2", arr_dataNtm);
intent.putStringArrayListExtra("data3", arr_dataOdas);
intent.putStringArrayListExtra("data4", arr_dataMetAll);
intent.putStringArrayListExtra("data5", arr_dataMet3HrTask);
intent.putStringArrayListExtra("data6", arr_dataTideTask);
context.startActivity(intent);
}else{
//update dialogue
}
}
}
private class NtmTask extends AsyncTask<Void, Void, ArrayList<String>> {
#Override
protected ArrayList<String> doInBackground(Void... params) {
Document docNTM;
try {
Connection.Response response = Jsoup.connect("http://www.milfordfishdocks.com/notices-to-mariners/")
.timeout(10000)
.ignoreHttpErrors(true)
.execute();
int statusCode = response.statusCode();
if(statusCode == 200) {
docNTM = Jsoup.connect("http://www.milfordfishdocks.com/notices-to-mariners/").timeout(10000).get();
Elements elements = docNTM.select("div.news-item-left");
int NtmAmount = elements.size();
String NtmAmt = Integer.toString(NtmAmount);//convert the Int to a string for adding into array
arr_dataNtm.add(NtmAmt);
} else {
System.out.println("Received error code for NTM Data : " + statusCode + " Adding Null values");
arr_dataNtm.add("0");
}
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Received timeout error code for NTM Data : Adding Null values ");
arr_dataNtm.add("0");
}
return arr_dataNtm;
}
#Override
protected void onPostExecute(ArrayList<String> Param) {
asynCount++;
System.out.println("Ntm list Captured" + arr_dataNtm + " asynCount= " + asynCount);
if (asynCount == 6){
//Start intents for main activity
System.out.println("asynCount has reached= " + asynCount + " so now starting MainActivity");
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putStringArrayListExtra("data1", arr_dataVts);
intent.putStringArrayListExtra("data2", arr_dataNtm);
intent.putStringArrayListExtra("data3", arr_dataOdas);
intent.putStringArrayListExtra("data4", arr_dataMetAll);
intent.putStringArrayListExtra("data5", arr_dataMet3HrTask);
intent.putStringArrayListExtra("data6", arr_dataTideTask);
context.startActivity(intent);
}else{
//update dialogue
}
}
}
#Override
protected void onPostExecute(Integer result) {
System.out.println("Data Task Has Executed");
}
}
It can be done like this:
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView parent, View view, int position, long id) {
switch (position){
case 0:
//do stuff
case 1:
//do stuff
default:
break;
}
drawerListView.setItemChecked(position, true);
drawerListView.setSelection(position);
drawerLayout.closeDrawer(drawerListView);
}
}
Then just attach this listener to your NavList:
drawerListView.setOnItemClickListener(new DrawerItemClickListener());
BTW, you would recommend you to switch fragments instead of switching activities, "Creating a Navigation Drawer" tutorial explains how to work with them
EDIT Handling case 0, replace with following:
new DataTask(MainActivity.this).execute();
Intent intent=new Intent(MainActivity.this,SplashScreen.class);
startActivity(intent);
Log.d("Click working");
MainActivity.this.finish();//Set this Activity to Finish so no loop back
Switch=
(Switch)navigationView.getMenu().findItem(R.id.vibrate).getActionView();
s.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean
isChecked){
if(isChecked)
//do whatever you want to do
}
});
this should work

Setting one element in array changes others

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.

Categories

Resources