0

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

Dheepak
  • 1,381
  • 2
  • 11
  • 14

1 Answers1

2

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.
Stephen C
  • 632,615
  • 86
  • 730
  • 1,096
  • Index value is what is expected. But while writing to array it is not written at expected index location. – Dheepak Aug 31 '12 at 11:04
  • I just checked. This problem is happening only in a few devices. It works properly in HTC Salsa(Gingerbread), LG Optimus(Gingerbread), Samsung Galaxy Tab(Honeycomb). The problem occurs in Galaxy Nexus(JellyBean) and Galaxy Note(JellyBean). Is this anyway related to OS? – Dheepak Sep 04 '12 at 08:36
  • It is possible, though I think you would be better off trying to understand what I said in my answer. – Stephen C Sep 04 '12 at 13:15
  • I understood your answer and checked..The index value i get is what I expect when i debugged with a break point; Event.values are also what is expected. To add to the last point in ur answer ,Multiple listeners update the sensorValues list. But why does the duplication occurs only in certain devices(4.0+ OS) is what I am trying to find :) – Dheepak Sep 05 '12 at 04:05