Issues reading sensor from a fragment in android [duplicate] - java

This question already has answers here:
getView returning null when fragment has been created from an activity
(6 answers)
Closed 5 years ago.
I'm having an issue displaying and interacting with sensors in a fragment. I have a couple of working fragments already, but when I load the sensor fragment it force closes.
sensors.java is the fragment and looks like this
public class sensors extends Fragment implements SensorEventListener
{
private float lastX, lastY, lastZ;
private SensorManager sensorManager;
private Sensor accelerometer;
private float deltaXMax = 0;
private float deltaYMax = 0;
private float deltaZMax = 0;
private float deltaX = 0;
private float deltaY = 0;
private float deltaZ = 0;
private float vibrateThreshold = 0;
private TextView currentX, currentY, currentZ, maxX, maxY, maxZ;
public Vibrator v;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup
container, #Nullable Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.sensor, container, false);
initializeViews();
sensorManager = (SensorManager)
getActivity().getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
// success! we have an accelerometer
accelerometer =
sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
vibrateThreshold = accelerometer.getMaximumRange() / 2;
} else {
// fai! we dont have an accelerometer!
}
//initialize vibration
v = (Vibrator)
this.getActivity().getSystemService(Context.VIBRATOR_SERVICE);
return rootView;
}
public void initializeViews() {
currentX = (TextView) getView().findViewById(R.id.currentX);
currentY = (TextView) getView().findViewById(R.id.currentY);
currentZ = (TextView) getView().findViewById(R.id.currentZ);
maxX = (TextView) getView().findViewById(R.id.maxX);
maxY = (TextView) getView().findViewById(R.id.maxY);
maxZ = (TextView) getView().findViewById(R.id.maxZ);
}
//onResume() register the accelerometer for listening the events
public void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer,
SensorManager.SENSOR_DELAY_NORMAL);
}
//onPause() unregister the accelerometer for stop listening the events
public void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
// clean current values
displayCleanValues();
// display the current x,y,z accelerometer values
displayCurrentValues();
// display the max x,y,z accelerometer values
displayMaxValues();
// get the change of the x,y,z values of the accelerometer
deltaX = Math.abs(lastX - event.values[0]);
deltaY = Math.abs(lastY - event.values[1]);
deltaZ = Math.abs(lastZ - event.values[2]);
// if the change is below 2, it is just plain noise
if (deltaX < 2)
deltaX = 0;
if (deltaY < 2)
deltaY = 0;
if (deltaZ < 2)
deltaZ = 0;
// set the last know values of x,y,z
lastX = event.values[0];
lastY = event.values[1];
lastZ = event.values[2];
vibrate();
}
// if the change in the accelerometer value is big enough, then vibrate!
// our threshold is MaxValue/2
public void vibrate() {
if ((deltaX > vibrateThreshold) || (deltaY > vibrateThreshold) ||
(deltaZ > vibrateThreshold)) {
v.vibrate(50);
}
}
public void displayCleanValues() {
currentX.setText("0.0");
currentY.setText("0.0");
currentZ.setText("0.0");
}
// display the current x,y,z accelerometer values
public void displayCurrentValues() {
currentX.setText(Float.toString(deltaX));
currentY.setText(Float.toString(deltaY));
currentZ.setText(Float.toString(deltaZ));
}
// display the max x,y,z accelerometer values
public void displayMaxValues() {
if (deltaX > deltaXMax) {
deltaXMax = deltaX;
maxX.setText(Float.toString(deltaXMax));
}
if (deltaY > deltaYMax) {
deltaYMax = deltaY;
maxY.setText(Float.toString(deltaYMax));
}
if (deltaZ > deltaZMax) {
deltaZMax = deltaZ;
maxZ.setText(Float.toString(deltaZMax));
}
}
}
My sensor.xml looks like this
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:background="#ffffff"
android:gravity="center"
android:orientation="vertical"
android:paddingTop="20dp" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:text="Max Acceleration:"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Max Acceleration: X-Axis"
android:textSize="15dp" />
<TextView
android:id="#+id/maxX"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="0.0"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Max Acceleration: Y-Axis"
android:textSize="15dp" />
<TextView
android:id="#+id/maxY"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="0.0"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:text="Max Acceleration: Z-Axis"
android:textSize="15dp" />
<TextView
android:id="#+id/maxZ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="0.0"
android:textSize="20dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="10dp"
android:layout_marginTop="30dp"
android:text="Current Acceleration:"
android:textSize="20dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:gravity="center|top"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:background="#ffffff"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="X-Axis"
android:textSize="15dp" />
<TextView
android:id="#+id/currentX"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="0.0"
android:textSize="15dp" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:background="#ffffff"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="Y-Axis"
android:textSize="15dp" />
<TextView
android:id="#+id/currentY"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="0.0"
android:textSize="15dp" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.33"
android:background="#ffffff"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="Z-Axis"
android:textSize="15dp" />
<TextView
android:id="#+id/currentZ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="10dp"
android:text="0.0"
android:textSize="15dp" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
my logcat reads the issue
04-19 01:59:56.723 6460-6460/abrunette.blackhawk.edu.pagenavi W/art: Before
Android 4.1, method int
android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int,
boolean) would have incorrectly overridden the package-private method in
android.widget.ListView
04-19 01:59:59.052 6460-6460/abrunette.blackhawk.edu.pagenavi
D/AndroidRuntime: Shutting down VM
04-19 01:59:59.054 6460-6460/abrunette.blackhawk.edu.pagenavi
E/AndroidRuntime: FATAL EXCEPTION: main
Process: abrunette.blackhawk.edu.pagenavi, PID: 6460
Theme: themes:{default=overlay:system, iconPack:system, fontPkg:system,
com.android.systemui=overlay:system,
com.android.systemui.navbar=overlay:system}
java.lang.NullPointerException: Attempt to invoke virtual method
'android.view.View android.view.View.findViewById(int)' on a null object
reference
at abrunette.blackhawk.edu.pagenavi.sensors.initializeViews(sensors.java:61)
at abrunette.blackhawk.edu.pagenavi.sensors.onCreateView(sensors.java:42)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:2080)
at
android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1108)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1290)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:801)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1677)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:536)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5461)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

You're calling getView() before the root view is set, before you return from the onCreateView() method.
Try this:
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View rootView = inflater.inflate(R.layout.sensor, container, false);
initializeViews(rootView);
....
}
public void initializeViews(rootView) {
currentX = (TextView) rootView.findViewById(R.id.currentX);
currentY = (TextView) rootView.findViewById(R.id.currentY);
currentZ = (TextView) rootView.findViewById(R.id.currentZ);
maxX = (TextView) rootView.findViewById(R.id.maxX);
maxY = (TextView) rootView.findViewById(R.id.maxY);
maxZ = (TextView) rootView.findViewById(R.id.maxZ);
}

Related

How to fix java.lang.IllegalStateException: Could not execute method for android:onClick

I am a newbie trying to create a simple quiz app in Android Studio. Things were progressing reasonably well until I tried to create an onClick event for a radiogroup.
I took a look at this previously answered question: java.lang.IllegalStateException: Could not execute method for android:onClick Android App but the solution did not shed any light on my issue.
Another thing I noticed was a problem with the imported AppCompatViewInflater.java WHICH 'cannot resolve symbol 'R''?
Any advice would much appreciated.
This is the logcat error message that I see:
02-05 09:19:16.989 29473-29473/com.example.hughdavidson_quizapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hughdavidson_quizapp, PID: 29473
java.lang.IllegalStateException: Could not execute method for android:onClick
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:414)
at android.view.View.performClick(View.java:5205)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992)
at android.view.View$PerformClick.run(View.java:21164)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invoke(Native Method)
at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:409)
at android.view.View.performClick(View.java:5205) 
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:992) 
at android.view.View$PerformClick.run(View.java:21164) 
at android.os.Handler.handleCallback(Handler.java:739) 
at android.os.Handler.dispatchMessage(Handler.java:95) 
at android.os.Looper.loop(Looper.java:148) 
at android.app.ActivityThread.main(ActivityThread.java:5417) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616) 
Caused by: android.content.res.Resources$NotFoundException: Resource ID #0x7f0c0004
This is the MainActivity.java code
///
public class MainActivity extends AppCompatActivity {
RadioGroup radioGroupQ1;
ImageView q1ImageView;
TextView textViewQ2;
ImageView q2ImageView;
CheckBox checkBoxQ3_i, checkBoxQ3_ii, checkBoxQ3_iii, checkBoxQ3_iv, checkBoxQ3_v;
ImageView q3_i_ImageView, q3_ii_ImageView, q3_iii_ImageView, q3_iv_ImageView, q3_v_ImageView;
boolean hasCheckBoxQ3_i = false;
boolean hasCheckBoxQ3_ii = false;
boolean hasCheckBoxQ3_iii = false;
boolean hasCheckBoxQ3_iv = false;
boolean hasCheckBoxQ3_v = false;
EditText editTextQ4_i_Answer, editTextQ4_ii_Answer, editTextQ4_iii_Answer, editTextQ4_iv_Answer;
ImageView q4_i_ImageView, q4_ii_ImageView, q4_iii_ImageView, q4_iv_ImageView;
int userScore = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Ref for working with radiogroups: https://stackoverflow.com/questions/9748070/radio-group-onclick-event-not-firing-how-do-i-tell-which-is-selected
radioGroupQ1 = (RadioGroup) findViewById(R.id.q1_radio_buttons);
radioGroupQ1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId){
case R.id.q1_radioButton_false:
userScore += + 0;
q1ImageView.setImageResource(R.mipmap.red_cross);
break;
case R.id.q1_radioButton_true:
userScore += + 1;
q1ImageView.setImageResource(R.mipmap.green_tick);
break;
}
}
});
textViewQ2 = (TextView) findViewById(R.id.q2_editText);
checkBoxQ3_i = (CheckBox) findViewById(R.id.checkBoxQ3_i) ;
checkBoxQ3_ii = (CheckBox) findViewById(R.id.checkBoxQ3_ii) ;
checkBoxQ3_iii = (CheckBox) findViewById(R.id.checkBoxQ3_iii) ;
checkBoxQ3_iv = (CheckBox) findViewById(R.id.checkBoxQ3_iv) ;
checkBoxQ3_v = (CheckBox) findViewById(R.id.checkBoxQ3_v) ;
editTextQ4_i_Answer = (EditText) findViewById(R.id.q4_i_editBox);
editTextQ4_ii_Answer = (EditText) findViewById(R.id.q4_ii_editBox);
editTextQ4_iii_Answer = (EditText) findViewById(R.id.q4_iii_editBox);
editTextQ4_iv_Answer = (EditText) findViewById(R.id.q4_iv_editBox);
q1ImageView = (ImageView) findViewById(R.id.q1_redcross_image_view);
q2ImageView = (ImageView) findViewById(R.id.q2_redgreencheck_image_view);
q3_i_ImageView = (ImageView) findViewById(R.id.q3_i_greencheck_image_view);
q3_ii_ImageView = (ImageView) findViewById(R.id.q3_ii_greencheck_image_view);
q3_iii_ImageView = (ImageView) findViewById(R.id.q3_iii_redcheck_image_view);
q3_iv_ImageView = (ImageView) findViewById(R.id.q3_iv_greencheck_image_view);
q3_v_ImageView = (ImageView) findViewById(R.id.q3_v_greencheck_image_view);
q4_i_ImageView = (ImageView) findViewById(R.id.q4_i_redgreencheck_image_view);
q4_ii_ImageView = (ImageView) findViewById(R.id.q4_ii_redgreencheck_image_view);
q4_iii_ImageView = (ImageView) findViewById(R.id.q4_iii_redgreencheck_image_view);
q4_iv_ImageView = (ImageView) findViewById(R.id.q4_iv_redgreencheck_image_view);
}
//Show users total score
public void showScore(View view){
//Check score for question 1
//Check score for question 2
String q2Answer = "1000000";
if (textViewQ2.getText().toString().equals(q2Answer)){
userScore = userScore + 1;
q2ImageView.setImageResource(R.mipmap.green_tick);
}
else q2ImageView.setImageResource(R.mipmap.red_cross);
//check score for question 3
//has Q3-i been ticked
hasCheckBoxQ3_i = checkBoxQ3_i.isChecked();
//has Q3-ii been ticked
hasCheckBoxQ3_ii = checkBoxQ3_ii.isChecked();
//has Q3-iii been ticked
hasCheckBoxQ3_iii = checkBoxQ3_iii.isChecked();
//has Q3-iv been ticked
hasCheckBoxQ3_iv = checkBoxQ3_iv.isChecked();
//has Q3-v been ticked
hasCheckBoxQ3_v = checkBoxQ3_i.isChecked();
if(hasCheckBoxQ3_i){
userScore += +1;
q3_i_ImageView.setImageResource(R.mipmap.green_tick);
}
if(hasCheckBoxQ3_ii){
userScore += +1;
q3_ii_ImageView.setImageResource(R.mipmap.green_tick);
}
if(hasCheckBoxQ3_iii){
userScore += +1;
q3_iii_ImageView.setImageResource(R.mipmap.green_tick);
}
if(hasCheckBoxQ3_iv){
userScore += +1;
q3_iv_ImageView.setImageResource(R.mipmap.green_tick);
}
if(hasCheckBoxQ3_v){
userScore += +0;
q3_v_ImageView.setImageResource(R.mipmap.red_cross);
}
//Check score for Q4
//Reference: string comparison https://stackoverflow.com/questions/16143562/string-comparison-android/16143606#:~:text=The%20%3D%3D%20operator%20checks%20to,to%20compare%20strings%20for%20equality.
String Q4_i = "E";
String Q4_ii = "A";
String Q4_iii = "C";
String Q4_iv = "B";
if(editTextQ4_i_Answer.getText().toString().equals(Q4_i)){
userScore += +1;
q4_i_ImageView.setImageResource(R.mipmap.green_tick);
}
else q4_i_ImageView.setImageResource(R.mipmap.red_cross);
if(editTextQ4_ii_Answer.getText().toString().equals(Q4_ii)){
userScore += +1;
q4_ii_ImageView.setImageResource(R.mipmap.green_tick);
}
else q4_ii_ImageView.setImageResource(R.mipmap.red_cross);
if(editTextQ4_iii_Answer.getText().toString().equals(Q4_iii)){
userScore += +1;
q4_iii_ImageView.setImageResource(R.mipmap.green_tick);
}
else q4_iii_ImageView.setImageResource(R.mipmap.red_cross);
if(editTextQ4_iv_Answer.getText().toString().equals(Q4_iv)){
userScore += +1;
q4_iv_ImageView.setImageResource(R.mipmap.green_tick);
}
else q4_iv_ImageView.setImageResource(R.mipmap.red_cross);
// Toast message to user with score
Context context = getApplicationContext();
CharSequence text = "You scored: " + userScore + " out of 11";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
...
}
///
and this is the XML:
///
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:id="#+id/q1"
style="#style/QuestionLabel"
android:text="#string/q1" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"/>
<TextView
android:id="#+id/q1_text"
style="#style/QuestionText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="#string/q1_text"/>
<RadioGroup
android:id="#+id/q1_radio_buttons"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintEnd_toStartOf="#+id/guideline5"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/q1_text">
<RadioButton
android:id="#+id/q1_radioButton_false"
android:text="#string/q1_radio_button_false"/>
<RadioButton
android:id="#+id/q1_radioButton_true"
android:text="#string/q1_radio_button_true"/>
</RadioGroup>
<TextView
android:id="#+id/q2"
style="#style/QuestionLabel"
android:text="#string/q2"/>
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="100dp" />
<TextView
android:id="#+id/q2_text"
style="#style/QuestionText"
android:text="#string/q2_text" />
<EditText
android:id="#+id/q2_editText"
android:hint="#string/user_hint"
android:importantForAutofill="no"
android:inputType="number|text" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="176dp" />
<TextView
android:id="#+id/q3"
style="#style/QuestionLabel"
android:text="#string/q3" />
<TextView
android:id="#+id/q3_text"
style="#style/QuestionText"
android:text="#string/q3_text" />
<CheckBox
android:id="#+id/checkBoxQ3_i"
style="#style/CheckBox"
android:checked="false"
android:text="#string/q3_i" />
<CheckBox
android:id="#+id/checkBoxQ3_ii"
style="#style/CheckBox"
android:checked="false"
android:text="#string/q3_ii" />
<CheckBox
android:id="#+id/checkBoxQ3_iii"
style="#style/CheckBox"
android:checked="false"
android:text="#string/q3_iii" />
<CheckBox
android:id="#+id/checkBoxQ3_iv"
style="#style/CheckBox"/>
<CheckBox
android:id="#+id/checkBoxQ3_v"
style="#style/CheckBox"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginEnd="70dp"
android:layout_marginRight="70dp"
android:checked="false"
android:text="#string/q3_v" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="180dp" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline5"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
app:layout_constraintGuide_begin="326dp" />
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline6"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="316dp" />
<TextView
android:id="#+id/q4"
style="#style/QuestionLabel"
android:text="#string/q4"
app:layout_constraintEnd_toStartOf="#+id/guideline"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="#+id/guideline6" />
<ImageView
android:id="#+id/q4_imageView3"
android:layout_width="0dp"
android:layout_height="189dp"
android:contentDescription="#string/red_cross"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#id/guideline6"
app:srcCompat="#mipmap/motion_time_graph" />
<TextView
android:id="#+id/q4_text"
style="#style/QuestionText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="#string/q4_text"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/q4_imageView3" />
<TextView
android:id="#+id/q4_i_text"
style="#style/QuestionText"
android:layout_width="287dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="#string/q4_i"
app:layout_constraintEnd_toStartOf="#+id/guideline5"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/q4_text" />
<EditText
android:id="#+id/q4_i_editBox"
style="#style/Q4EditTextBox"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline5"
app:layout_constraintTop_toBottomOf="#+id/q4_text"
app:layout_constraintTop_toTopOf="#+id/q4_i_text" />
<TextView
android:id="#+id/q4_ii_text"
style="#style/QuestionText"
android:layout_width="291dp"
android:layout_height="36dp"
android:layout_marginTop="10dp"
android:text="#string/q4_ii"
app:layout_constraintEnd_toStartOf="#+id/guideline5"
app:layout_constraintHorizontal_bias="0.612"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/q4_i_text" />
<EditText
android:id="#+id/q4_ii_editBox"
style="#style/Q4EditTextBox"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline5"
app:layout_constraintTop_toTopOf="#+id/q4_ii_text" />
<TextView
android:id="#+id/q4_iii_text"
style="#style/QuestionText"
android:layout_width="287dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="#string/q4_iii"
app:layout_constraintEnd_toStartOf="#+id/guideline5"
app:layout_constraintHorizontal_bias="0.612"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/q4_ii_text" />
<EditText
android:id="#+id/q4_iii_editBox"
style="#style/Q4EditTextBox"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline5"
app:layout_constraintTop_toTopOf="#+id/q4_iii_text" />
<TextView
android:id="#+id/q4_iv_text"
style="#style/QuestionText"
android:layout_width="287dp"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:text="#string/q4_iv"
app:layout_constraintEnd_toStartOf="#+id/guideline5"
app:layout_constraintHorizontal_bias="0.612"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/q4_iii_text" />
<EditText
android:id="#+id/q4_iv_editBox"
style="#style/Q4EditTextBox"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="#+id/guideline5"
app:layout_constraintTop_toTopOf="#+id/q4_iv_text" />
<Button
android:id="#+id/reset"
style="#style/SubmitResetButton"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:text="#string/reset"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/guideline4"
app:layout_constraintStart_toStartOf="#+id/guideline"
app:layout_constraintTop_toBottomOf="#+id/guideline7"
app:layout_constraintVertical_bias="0.0"
android:onClick="resetAnswers"/>
<Button
android:id="#+id/submit"
style="#style/SubmitResetButton"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:text="#string/submit"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toStartOf="#+id/guideline5"
app:layout_constraintStart_toStartOf="#+id/guideline4"
app:layout_constraintTop_toBottomOf="#+id/guideline7"
app:layout_constraintVertical_bias="0.0"
android:onClick="showScore"/>
<androidx.constraintlayout.widget.Guideline
android:id="#+id/guideline7"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layout_constraintGuide_begin="734dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
///
Button onClick and RadioGroup onClick are not the same. Please use this:
myradioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
}
});

How to resolve Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

I am getting this error while running my app. I can't figure out what to do.
Here's my MainActivity.java
package com.example.user.sensor;
import android.content.Context;
import android.content.DialogInterface;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements SensorEventListener {
private float lastX = 0, lastY = 0, lastZ = 0;
private SensorManager sensorManager;
private Sensor accelerometer;
private float deltaXMax = 0;
private float deltaYMax = 0;
private float deltaZMax = 0;
private float deltaX = 0;
private float deltaY = 0;
private float deltaZ = 0;
private float vibrateThreshold = 0;
TextView currentX, currentY, currentZ;
public Vibrator v;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getSupportActionBar().getThemedContext();
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(getSupportActionBar().getThemedContext(), android.R.style.Theme_Material_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(getSupportActionBar().getThemedContext());
}
builder.setTitle("Alert Dialog")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
if (sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER) != null) {
// success! we have an accelerometer
accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
vibrateThreshold = accelerometer.getMaximumRange() / 2;
} else {
// fai! we dont have an accelerometer!
}
//initialize vibration
v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
}
//onResume() register the accelerometer for listening the events
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, accelerometer, SensorManager.SENSOR_DELAY_NORMAL);
}
//onPause() unregister the accelerometer for stop listening the events
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
// clean current values
displayCleanValues();
// display the current x,y,z accelerometer values
displayCurrentValues();
// display the max x,y,z accelerometer values
// get the change of the x,y,z values of the accelerometer
deltaX = Math.abs(lastX - event.values[0]);
deltaY = Math.abs(lastY - event.values[1]);
deltaZ = Math.abs(lastZ - event.values[2]);
// if the change is below 2, it is just plain noise
if (deltaX < 2)
deltaX = 0;
if (deltaY < 2)
deltaY = 0;
if (deltaZ > (vibrateThreshold) || (deltaY > vibrateThreshold) || (deltaZ > vibrateThreshold)) {
v.vibrate(50);
}
}
public void displayCleanValues() {
currentX.setText("0.0");
currentY.setText("0.0");
currentZ.setText("0.0");
}
// display the current x,y,z accelerometer values
public void displayCurrentValues() {
currentX.setText(Float.toString(deltaX));
currentY.setText(Float.toString(deltaY));
currentZ.setText(Float.toString(deltaZ));
}
}
// display the max x,y,z accelerometer values
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical"
android:layout_marginLeft="15dp">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GYROSCOPE"
android:textColor="#android:color/black"
android:layout_marginTop="30dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="8dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X :"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginLeft="10dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Y :"
android:layout_marginTop="4dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Z :"
android:layout_marginTop="4dp"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
/>
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ACCELEROMETER"
android:textColor="#android:color/black"
android:layout_marginTop="30dp"
/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginTop="8dp">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X :"
/>
<TextView
android:id="#+id/currentX"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginLeft="10dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Y :"
android:layout_marginTop="4dp"
/>
<TextView
android:id="#+id/currentY"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Z :"
android:layout_marginTop="4dp"
/>
<TextView
android:id="#+id/currentZ"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="0"
android:layout_marginLeft="10dp"
android:layout_marginTop="4dp"
/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
</LinearLayout>
and here is the log file:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.user.sensor, PID: 8586
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
at com.example.user.sensor.MainActivity.displayCleanValues(MainActivity.java:121)
at com.example.user.sensor.MainActivity.onSensorChanged(MainActivity.java:100)
at android.hardware.SystemSensorManager$SensorEventQueue.dispatchSensorEvent(SystemSensorManager.java:830)
at android.os.MessageQueue.nativePollOnce(Native Method)
at android.os.MessageQueue.next(MessageQueue.java:325)
at android.os.Looper.loop(Looper.java:142)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
First, you need to provide an id of a TextView in Layout file
<TextView
android:id="#id/txt1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="GYROSCOPE"
android:textColor="#android:color/black"
android:layout_marginTop="30dp"
/>
After that you need to declare the TextView in java file see below code:
TextView txt1, txt2;
after that in onCreate(), initialize the TextView:
txt1 = (TextView) findViewById(R.id.txt1);// R.id.txt1 is a layout textbox ID

Android: app crashing after adding a method to MainActvity

I am working on an app to time and score basketball games, when I added the countdown part and a button to control the count to the MainActivity.java file, the app builds fine but crashes every time. Here are codes I used.
Here is the error generated every time i try to launch the app
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.abdulkarim.courtcounter, PID: 19740
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.abdulkarim.courtcounter/com.example.abdulkarim.courtcounter.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5603)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at android.support.v7.app.AppCompatDelegateImplBase.<init>(AppCompatDelegateImplBase.java:116)
at android.support.v7.app.AppCompatDelegateImplV9.<init>(AppCompatDelegateImplV9.java:147)
at android.support.v7.app.AppCompatDelegateImplV11.<init>(AppCompatDelegateImplV11.java:27)
at android.support.v7.app.AppCompatDelegateImplV14.<init>(AppCompatDelegateImplV14.java:50)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:201)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:181)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:521)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at com.example.abdulkarim.courtcounter.MainActivity.<init>(MainActivity.java:14)
at java.lang.Class.newInstanceImpl(Native Method)
at java.lang.Class.newInstance(Class.java:1208)
at android.app.Instrumentation.newActivity(Instrumentation.java:1067)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2297)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471) 
at android.app.ActivityThread.access$900(ActivityThread.java:175) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308) 
at android.os.Handler.dispatchMessage(Handler.java:102) 
at android.os.Looper.loop(Looper.java:146) 
at android.app.ActivityThread.main(ActivityThread.java:5603) 
at java.lang.reflect.Method.invokeNative(Native Method) 
at java.lang.reflect.Method.invoke(Method.java:515) 
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1283) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) 
at dalvik.system.NativeStart.main(Native Method)
MainActivity.java
package com.example.abdulkarim.courtcounter;
import android.os.CountDownTimer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int scoreTeamA = 0, scoreTeamB = 0;
TextView minutes = (TextView) findViewById(R.id.min_counter);
TextView seconds = (TextView) findViewById(R.id.sec_counter);
long milliLeft, min, sec;
CountDownTimer gameTime;
final Button timeoutButton = (Button) findViewById(R.id.timeout_button);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the +3 points button is clicked
*/
public void threePointsA(View view){
scoreTeamA = scoreTeamA + 3;
displayScoreA(scoreTeamA);
}
/**
* This method is called when the +2 points button is clicked
*/
public void twoPointsA(View view){
scoreTeamA = scoreTeamA + 2;
displayScoreA(scoreTeamA);
}
/**
* This method is called when the Free Throw button is clicked
*/
public void freeThrowA(View view){
scoreTeamA = scoreTeamA + 1;
displayScoreA(scoreTeamA);
}
/**
* This method is called when the +3 points button is clicked
*/
public void threePointsB(View view){
scoreTeamB = scoreTeamB + 3;
displayScoreB(scoreTeamB);
}
/**
* This method is called when the +2 points button is clicked
*/
public void twoPointsB(View view){
scoreTeamB = scoreTeamB + 2;
displayScoreB(scoreTeamB);
}
/**
* This method is called when the Free Throw button is clicked
*/
public void freeThrowB(View view){
scoreTeamB = scoreTeamB + 1;
displayScoreB(scoreTeamB);
}
/**
* This method is called when the reset button is clicked
*/
public void reset(View view){
scoreTeamA = 0;
scoreTeamB = 0;
displayScoreA(scoreTeamA);
displayScoreB(scoreTeamB);
}
/**
* This method initializes the countdown timer
*/
public void gameTime(long timeLengthMilli) {
gameTime = new CountDownTimer(timeLengthMilli, 1000) {
#Override
public void onTick(long milliTillFinish) {
milliLeft = milliTillFinish;
min = (milliTillFinish / (1000 * 60));
sec = ((milliTillFinish / 1000) - min * 60);
minutes.setText(Long.toString(min));
seconds.setText(Long.toString(sec));
Log.i("Tick", "Tock");
}
public void onFinish() {
minutes.setText("00");
seconds.setText("00");
}
}.start();
}
public void timerPause() {
gameTime.cancel();
}
private void timerResume() {
Log.i("min", Long.toString(min));
Log.i("Sec", Long.toString(sec));
gameTime(milliLeft);
}
/**
*This method is called when the timeOut button is clicked
*/
public void timeOut(View view){
timeoutButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(timeoutButton.getText().equals("Start")){
Log.i("Started", timeoutButton.getText().toString());
timeoutButton.setText("Timeout");
gameTime(60*1000);
} else if (timeoutButton.getText().equals("Pause")){
Log.i("Timeout", timeoutButton.getText().toString());
timeoutButton.setText("Resume");
timerPause();
} else if (timeoutButton.getText().equals("Resume")){
timeoutButton.setText("Timeout");
timerResume();
}
}
});
}
/**
* This method handles the display of scores for team A
*/
private void displayScoreA(int score){
TextView scoreTextView = (TextView) findViewById(R.id.teamA_score_text_view);
scoreTextView.setText(String.valueOf(score));
}
/**
* This method handles the display of scores for team A
*/
private void displayScoreB(int score){
TextView scoreTextView = (TextView) findViewById(R.id.teamB_score_text_view);
scoreTextView.setText(String.valueOf(score));
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.abdulkarim.courtcounter.MainActivity">
<RelativeLayout
android:id="#+id/r1_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true">
<TextView
android:id="#+id/min_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="75dp"
android:paddingTop="16dp"
android:text="Mins"
android:textAllCaps="true"
android:textColor="#android:color/black"
android:textSize="10sp" />
<TextView
android:id="#+id/sec_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:paddingTop="16dp"
android:layout_toRightOf="#id/min_text_view"
android:text="Secs"
android:textAllCaps="true"
android:textColor="#android:color/black"
android:textSize="10sp" />
<TextView
android:id="#+id/min_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/min_text_view"
android:layout_marginTop="8dp"
android:fontFamily="sans-serif-light"
android:text="00"
android:textColor="#000000"
android:textSize="56sp" />
<TextView
android:id="#+id/blinker_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/min_text_view"
android:layout_marginTop="8dp"
android:layout_toRightOf="#id/min_counter"
android:fontFamily="sans-serif-light"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:text=":"
android:textColor="#000000"
android:textSize="56sp" />
<TextView
android:id="#+id/sec_counter"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/min_text_view"
android:layout_marginTop="8dp"
android:layout_toRightOf="#id/blinker_text_view"
android:fontFamily="sans-serif-light"
android:text="00"
android:textColor="#000000"
android:textSize="56sp" />
</RelativeLayout>
<LinearLayout
android:id="#+id/l1_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/r1_layout"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif-medium"
android:gravity="center_horizontal"
android:text="Team A"
android:textColor="#616161"
android:textSize="14sp" />
<TextView
android:id="#+id/teamA_score_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif-light"
android:gravity="center_horizontal"
android:text="0"
android:textColor="#000000"
android:textSize="56sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:layout_marginTop="24dp"
android:fontFamily="sans-serif-medium"
android:onClick="threePointsA"
android:text="+3 Points"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:fontFamily="sans-serif-medium"
android:onClick="twoPointsA"
android:text="+2 Points"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:fontFamily="sans-serif-medium"
android:onClick="freeThrowA"
android:text="Free Throw"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
</LinearLayout>
<View
android:layout_width="1dp"
android:layout_height="match_parent"
android:layout_marginTop="16dp"
android:background="#android:color/darker_gray"></View>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif-medium"
android:gravity="center_horizontal"
android:text="Team B"
android:textColor="#616161"
android:textSize="14sp" />
<TextView
android:id="#+id/teamB_score_text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:fontFamily="sans-serif-light"
android:gravity="center_horizontal"
android:text="0"
android:textColor="#000000"
android:textSize="56sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:layout_marginTop="24dp"
android:fontFamily="sans-serif-medium"
android:onClick="threePointsB"
android:text="+3 Points"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:fontFamily="sans-serif-medium"
android:onClick="twoPointsB"
android:text="+2 Points"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginLeft="24dp"
android:layout_marginRight="24dp"
android:fontFamily="sans-serif-medium"
android:onClick="freeThrowB"
android:text="Free Throw"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true">
<Button
android:id="#+id/timeout_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="8dp"
android:layout_marginBottom="32dp"
android:layout_marginLeft="16dp"
android:text="Start"
android:fontFamily="sans-serif-medium"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp"
android:onClick="timeOut"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="32dp"
android:layout_marginRight="16dp"
android:layout_marginLeft="8dp"
android:fontFamily="sans-serif-medium"
android:onClick="Reset"
android:text="Reset"
android:textAllCaps="true"
android:textColor="#616161"
android:textSize="14sp" />
</LinearLayout>
</RelativeLayout>
You can't call findViewById before the onCreate method.
Move the initialization of your view references inside onCreate.
public class MainActivity extends AppCompatActivity {
int scoreTeamA = 0, scoreTeamB = 0;
TextView minutes;
TextView seconds;
long milliLeft, min, sec;
CountDownTimer gameTime;
Button timeoutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
minutes = (TextView) findViewById(R.id.min_counter);
seconds = (TextView) findViewById(R.id.sec_counter);
timeoutButton = (Button) findViewById(R.id.timeout_button);
}
Declare all the variable in global
Move findViewById in onCreate method. You should initialize them inside onCreate method, not in global.
public class MainActivity extends AppCompatActivity {
int scoreTeamA = 0, scoreTeamB = 0;
TextView minutes;
TextView seconds;
long milliLeft, min, sec;
CountDownTimer gameTime;
final Button timeoutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
minutes = (TextView) findViewById(R.id.min_counter);
seconds = (TextView) findViewById(R.id.sec_counter);
timeoutButton = (Button) findViewById(R.id.timeout_button);
}
// others code...
}

Unable to draw a circle on an ImageView

I'm trying to draw a circle in the middle of an ImageView. Below is my UI code.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/white">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:layout_weight="2"
android:id="#+id/bluh">
<ImageView
android:id="#+id/image_background"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:adjustViewBounds="true"
android:scaleType="centerCrop"
android:layout_weight="2"
android:src="#drawable/hhh" />
</LinearLayout>
<LinearLayout
android:id="#+id/l22Parent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/bluh"
android:layout_marginTop="10dp"
android:layout_weight="1"
android:orientation="horizontal">
<Button
android:id="#+id/step18button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/step18textView"
android:layout_marginLeft="3dp"
android:layout_weight="1"
android:text="1"
android:textSize="13dp" />
<Button
android:id="#+id/step18button2"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/step18button1"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button1"
android:layout_toRightOf="#+id/step18button1"
android:layout_weight="1"
android:text="2"
android:textSize="13dp" />
<Button
android:id="#+id/step18button3"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button2"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button2"
android:layout_toRightOf="#+id/step18button2"
android:layout_weight="1"
android:text="3"
android:textSize="13dp" />
<Button
android:id="#+id/step18button4"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button3"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button3"
android:layout_toRightOf="#+id/step18button3"
android:layout_weight="1"
android:text="4"
android:textSize="13dp" />
<Button
android:id="#+id/step18button5"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button4"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button4"
android:layout_toRightOf="#+id/step18button4"
android:layout_weight="1"
android:text="5"
android:textSize="13dp" />
<Button
android:id="#+id/step18button6"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button5"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button5"
android:layout_toRightOf="#+id/step18button5"
android:layout_weight="1"
android:text="6"
android:textSize="13dp" />
<Button
android:id="#+id/step18button7"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button6"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button6"
android:layout_toRightOf="#+id/step18button6"
android:layout_weight="1"
android:text="7"
android:textSize="13dp" />
<Button
android:id="#+id/step18button8"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button7"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button7"
android:layout_toRightOf="#+id/step18button7"
android:layout_weight="1"
android:text="8"
android:textSize="13dp" />
<Button
android:id="#+id/step18button9"
style="?android:attr/buttonStyleSmall"
android:layout_width="39dp"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/step18button8"
android:layout_marginLeft="3dp"
android:layout_toEndOf="#+id/step18button8"
android:layout_toRightOf="#+id/step18button8"
android:layout_weight="1"
android:text="9"
android:textSize="13dp" />
</LinearLayout>
</LinearLayout>
The generated UI is below
Below is my Fragment class
/**
* Created by user on 5/12/2016.
*/
public class GeneralizationFragment extends Fragment {
Context context;
private ImageView imageView;
private int width;
private int height;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.generalization_fragment, container, false);
createBitMap(v);
return v;
}
public static GeneralizationFragment newInstance() {
GeneralizationFragment f = new GeneralizationFragment();
Bundle b = new Bundle();
f.setArguments(b);
return f;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
Activity a = getActivity();
if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
private void createBitMap(final View v) {
BitmapFactory.Options myOptions = new BitmapFactory.Options();
myOptions.inDither = true;
myOptions.inScaled = true;
myOptions.inPreferredConfig = Bitmap.Config.ARGB_8888;// important
myOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.hhh, myOptions);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.BLUE);
Bitmap workingBitmap = Bitmap.createBitmap(bitmap);
Bitmap mutableBitmap = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
imageView = (ImageView)v.findViewById(R.id.image_background);
ViewTreeObserver vto = imageView.getViewTreeObserver();
vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
public boolean onPreDraw() {
imageView.getViewTreeObserver().removeOnPreDrawListener(this);
height = imageView.getMeasuredHeight();
width = imageView.getMeasuredWidth();
Log.d("GENERALIZED", "Width:" + width);
return true;
}
});
float radius = (float) (width-(width*0.2));
DisplayMetrics displaymetrics = new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int height = displaymetrics.heightPixels;
int width = displaymetrics.widthPixels;
Canvas canvas = new Canvas(mutableBitmap);
canvas.drawCircle(100, 100, 60, paint);
imageView.setAdjustViewBounds(true);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(mutableBitmap);
}
}
However I am not able to draw the circle (or the circle is not visible) until I remove imageView.setScaleType(ImageView.ScaleType.CENTER_CROP); from my code. However that part is mandetory for me.
Also I have no idea of drawing it in the center.

Get button coordinates and detect if finger is over them - Android

I have 4 buttons in my android app activity. This is what it looks like:
As you can see, the textViews at the bottom of the screen display the x and y coordinates. The coordinates are in reference to a relative layout. (See below given code)
Now, what I want to do is get the x and y coordinates of the 4 buttons at runtime and then figure out if my finger is touching the buttons while moving or not. In simple words, I want to press the buttons by swiping my finger over them instead of lifting and touching. How can I achieve it? I want to implement it in my piano application.
I was able to get the coordinates on screen and they change as I move my finger.
So, my question is How can I get the coordinates of the buttons and detect if my finger is swiping above them?:
XML
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
android:id="#+id/relativelayout">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Y Cord : "
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="X Cord : "
android:layout_marginLeft="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/textView2"
android:layout_above="#+id/textView"
android:layout_alignParentLeft="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView3"
android:textColor="#000000"
android:layout_below="#+id/textView2"
android:layout_toRightOf="#+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView4"
android:textColor="#000000"
android:layout_marginBottom="10dp"
android:layout_above="#+id/textView"
android:layout_toRightOf="#+id/textView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:textColor="#000000"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:textColor="#000000"
android:id="#+id/button2"
android:layout_below="#+id/button"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:textColor="#000000"
android:id="#+id/button3"
android:layout_below="#+id/button2"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button4"
android:textColor="#000000"
android:layout_below="#+id/button3"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
</RelativeLayout>
Java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView xcordview = (TextView) findViewById(R.id.textView4);
final TextView ycordview = (TextView) findViewById(R.id.textView3);
RelativeLayout touchview = (RelativeLayout) findViewById(R.id.relativelayout);
touchview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()));
ycordview.setText(String.valueOf(event.getY()));
return true;
}
});
}
}
Thank you all very very much!
Update:
public class MainActivity extends Activity {
RelativeLayout touchview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView xcordview = (TextView) findViewById(R.id.textView4);
final TextView ycordview = (TextView) findViewById(R.id.textView3);
touchview = (RelativeLayout) findViewById(R.id.relativelayout);
touchview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()));
ycordview.setText(String.valueOf(event.getY()));
for(int i = 0; i < touchview.getChildCount(); i++){
if(checkInterSection(touchview.getChildAt(i), event.getRawX(), event.getRawY())){
Button button = (Button) findViewById(R.id.button);
button.setBackgroundColor(Color.BLUE);
break;
}
}
return true;
}
});
}
private boolean checkInterSection(View view, float rawX, float rawY) {
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
int width = view.getWidth();
int height = view.getHeight();
//Check the intersection of point with rectangle achieved
return (!(rawX < x || rawY > x + width || rawY < y || rawY > y + height));
}
}
package com.example.touch;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
public class MainActivity extends Activity {
Button b1, b2, b3, b4;
int b1x1, b1x2, b1y1, b1y2;
private TextView xcordview;
private TextView ycordview;
private TextView buttonIndicator;
private RelativeLayout touchview;
private static int defaultStates[];
private Button mLastButton;
private final static int[] STATE_PRESSED = {
android.R.attr.state_pressed,
android.R.attr.state_focused
| android.R.attr.state_enabled };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
xcordview = (TextView) findViewById(R.id.textView4);
ycordview = (TextView) findViewById(R.id.textView3);
buttonIndicator = (TextView) findViewById(R.id.button_indicator);
touchview = (RelativeLayout) findViewById(R.id.relativelayout);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
b3 = (Button) findViewById(R.id.button3);
b4 = (Button) findViewById(R.id.button4);
defaultStates = b1.getBackground().getState();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
touchview.setOnTouchListener(new View.OnTouchListener() {
private boolean isInside = false;
#Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
xcordview.setText(String.valueOf(x));
ycordview.setText(String.valueOf(y));
for (int i = 0; i < touchview.getChildCount(); i++) {
View current = touchview.getChildAt(i);
if (current instanceof Button) {
Button b = (Button) current;
if (!isPointWithin(x, y, b.getLeft(), b.getRight(), b.getTop(),
b.getBottom())) {
b.getBackground().setState(defaultStates);
}
if (isPointWithin(x, y, b.getLeft(), b.getRight(), b.getTop(),
b.getBottom())) {
b.getBackground().setState(STATE_PRESSED);
if (b != mLastButton) {
mLastButton = b;
buttonIndicator.setText(mLastButton.getText());
}
}
}
}
return true;
}
});
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
// TODO Auto-generated method stub
super.onWindowFocusChanged(hasFocus);
}
static boolean isPointWithin(int x, int y, int x1, int x2, int y1, int y2) {
return (x <= x2 && x >= x1 && y <= y2 && y >= y1);
}
}
layout file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativelayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff" >
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:text="Y Cord : "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_marginBottom="10dp"
android:layout_marginLeft="10dp"
android:text="X Cord : "
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView2"
android:layout_toRightOf="#+id/textView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/textView"
android:layout_marginBottom="10dp"
android:layout_toRightOf="#+id/textView"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:text="B1"
android:textColor="#000000" />
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button1"
android:text="B2"
android:textColor="#000000" />
<Button
android:id="#+id/button3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button2"
android:text="B3"
android:textColor="#000000" />
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/button3"
android:text="B4"
android:textColor="#000000" />
<TextView
android:id="#+id/button_indicator"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignTop="#+id/textView4"
android:layout_marginRight="33dp"
android:text="No one"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/button_indicator"
android:layout_alignBottom="#+id/button_indicator"
android:layout_marginRight="29dp"
android:layout_toLeftOf="#+id/button_indicator"
android:text="Entered: "
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
private boolean checkInterSection(View view, int rawX, int raxY) {
int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0];
int y = location[1];
int width = view.getWidth();
int height = view.getHeight();
//Check the intersection of point with rectangle achieved
return (!(rawX < x || rawY > x + width || rawY < y || rawY > y + height));
}
for(int i = 0; i < touchview.getChildCount(); i++){
if(checkInterSection(touchview.getChildAt(i), event.getRawX(), event.getRawY())){
if(checkInterSection(touchview.getChildAt(i), event.getRawX(), event.getRawY())){
((Button)touchview.getChildAt(i)).setBackgroundColor(Color.BLUE);// Type casting may not be required
}else{
((Button)touchview.getChildAt(i)).setBackgroundColor(Color.WHITE);
}
break;
}
}
getX() getY() for a OnTouchListener give coordinates relative the the cooresponding view.
If you prefer screen coordinates instead you can use one of the following
overwrite onTouchEvent for the activity and remove OnTouchListener-s for buttons,
in which case MotionEvent will report screen coordinates instead of Button coordinates
#Override
public boolean onTouchEvent (MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()));
ycordview.setText(String.valueOf(event.getY()));
return true;
}
use getTop() getLeft() in OnTouchListener for a button:
touchview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
xcordview.setText(String.valueOf(event.getX()+v.getLeft()));
ycordview.setText(String.valueOf(event.getY()+v.getTop()));
return true;
}
});
You may consider using GestureDetector to detect swipes, however it isn't really necessary.
karioki 's solution works well. In order to make it work even when we start the move from inside one of the buttons, just add
android:clickable="false"
for every button in xml.

Categories