I'm writing a simple application as an exercise - display a list of all sensors on the device as a ListView, and display current sensor values/details in a new activity when clicking on each sensor name in the ListView.
I have the ListView working correctly, and can pass the sensor name to the new activity so far. Is there a way to get the sensor details using this passed name? It seems like I cannot use putExtra() to pass the sensor itself to the new activity. Or is there another approach to this?
SensorList activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_sensor_activity);
sensorListView = (ListView) findViewById(R.id.sensorlist);
sensorListView.setOnItemClickListener((AdapterView.OnItemClickListener) this); //allows each item in ListView to be clickable
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorList = mSensorManager.getSensorList(Sensor.TYPE_ALL); //get list of sensors
ArrayList<String> sensorNames = new ArrayList<String>(); //list of sensor names
//iterate through list of sensors, get name of each and append to list of names
for(int i=0; i< sensorList.size(); i++) {
String sensor= sensorList.get(i).getName();
if(sensor == null || sensor.equals(""))
continue;
sensorNames.add(sensor);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_list_item_1, sensorNames);
sensorListView.setAdapter(adapter); //populate ListView with sensor names
}
@Override
public void onItemClick(AdapterView<?> adapter, View v, int position, long id ) {
Intent sensorDetails = new Intent(ListSensorActivity.this, SensorDetailActivity.class);
sensorDetails.putExtra("SENSOR_NAME", sensorList.get(position).getName()); //pass sensor name to detail activity
startActivity(sensorDetails);
}
** SensorDetail activity **
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sensor_detail);
sensorTitle = (TextView) findViewById(R.id.sensortitle);
manager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
Bundle extras = getIntent().getExtras();
sensorName = extras.getString("SENSOR_NAME");
sensorTitle.setText(sensorName);
}
Pass the type from the sensor to the second activity, then request the sensor in the activity via SensorManager.getDefaultSensor(type)