Reputation: 301
I am trying to obtain Accelerometer's raw data and show it on a TextView.
I have two classes: MainActivity and SensorActivity. I am new to Android development and I made SensorActivity class intentionally just to learn how non-activity class and activity class interact. To do so, I learned, by searching, that I need to pass the Context of the MainActivity, so that SensorActivity class can interact with the MainActivity. So, I tried as far as I could, but I seem to get stuck.
In initialize function, my effort to get an access to a TextView of MainActivity doesn't seem to work. I cannot even make the correct syntax. Codes snippets are provided below. If I could get any help, it would be appreciated, tremendously.
In MainActivity.java
public class MainActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SensorActivity sensorActivity = new SensorActivity(this);
sensorActivity.initialize();
}
}
In SensorActivity.java
public class SensorActivity implements SensorEventListener{
Context mainActivityContext;
private SensorManager mySensorManager = (SensorManager) mainActivityContext.getSystemService(Context.SENSOR_SERVICE);
public SensorActivity (Context context){
this.mainActivityContext = context;
}
...
protected void initialize(){
...
TextView tv = (TextView) findViewById(R.id.default_text_view);
...
}
}
Upvotes: 0
Views: 952
Reputation: 132982
Use Activity Context for accessing View from non Activity class as:
protected void initialize(Activity activity){
...
TextView tv = (TextView)activity.findViewById(R.id.default_text_view);
...
}
because findViewById
is method from Activity class instead of Context
Upvotes: 3