在数组中设置一个元素会更改其他元

时间:2012-08-24 12:00:26

标签: java android arraylist android-sensors

我检查了几乎相同标题的其他类似标签。这些答案无关紧要

在数组的一个位置设置元素时,两个元素都具有相同的值。

公共类LogActivity扩展了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)
            {


            }
        };
    }
}

}

当index为0时,执行set命令时,它也会改变索引位置“1”的值。 任何人都可以帮我这个吗?

先谢谢, Dheepak

1 个答案:

答案 0 :(得分:2)

  

当index为0时,执行set命令时,它也会改变索引位置“1”的值。任何人都可以帮我这个吗?

你肯定错误的是它导致了什么。在ArrayList的一个位置设置值不会神秘地导致另一个位置的值发生变化。它根本不起作用。

您正在观察的效果将归因于其他因素:

  • 也许index的价值不是您所期望的
  • 也许event.values的价值不是您所期望的。 (也许你在创建Event对象的方式上犯了一个错误,并且它们都是共享一个float[]对象。)
  • 也许位置1的值已经是那个值
  • 也许你有多个线程正在更新sensorValues列表。