Android: app crashing after adding a method to MainActvity - java

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...
}

Related

ScrollView not scrolling with onTouch

My scroll view isn't scrolling. I have a feeling it may be due to an "onTouch" method I have that instead of scrolling is incrementing the counter shown. I have tried to find some solutions but none seem to be directly related to mine and any attempt to change the scroll view has not worked.
I am not sure how to get around this and any help would be greatly appreciated.
Java Code
package com.alanlyne.tbm.Variables.varL;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import com.alanlyne.tbm.Menu.Menu;
import com.alanlyne.tbm.Menu.menuCounter;
import com.alanlyne.tbm.R;
import com.alanlyne.tbm.Variables.Var;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
public class varL2 extends AppCompatActivity {
TextView t0, t1, t2, t3, t4, t5, t6, t7, t8, x;
Button b1;
int counter = 0;
DatabaseReference databaseName;
private long mLastClickTime = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_var_l2);
databaseName = FirebaseDatabase.getInstance().getReference("counter");
t0 = findViewById(R.id.t0);
t1 = findViewById(R.id.t1);
t2 = findViewById(R.id.t2);
t3 = findViewById(R.id.t3);
t4 = findViewById(R.id.t4);
t5 = findViewById(R.id.t5);
t6 = findViewById(R.id.t6);
t7 = findViewById(R.id.t7);
t8 = findViewById(R.id.t8);
b1 = findViewById(R.id.b1);
x = findViewById(R.id.x);
x.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent x = new Intent(varL2.this, Var.class);
startActivity(x);
}
});
View view = findViewById(R.id.ScrollView01);
view.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent event) {
if (SystemClock.elapsedRealtime() - mLastClickTime < 500) {
System.out.println("Fun");
}
else{
mLastClickTime = SystemClock.elapsedRealtime();
counter++;
System.out.println(counter);
if (counter > 0) {
TextView tv = findViewById(R.id.t1);
tv.setVisibility(View.VISIBLE);
}
if (counter > 1) {
TextView tv = findViewById(R.id.t2);
tv.setVisibility(View.VISIBLE);
}
if (counter > 2) {
TextView tv = findViewById(R.id.t3);
tv.setVisibility(View.VISIBLE);
}
if (counter > 3) {
TextView tv = findViewById(R.id.t4);
tv.setVisibility(View.VISIBLE);
}
if (counter > 4) {
TextView tv = findViewById(R.id.t5);
tv.setVisibility(View.VISIBLE);
}
if (counter > 5) {
TextView tv = findViewById(R.id.t6);
tv.setVisibility(View.VISIBLE);
}
if (counter > 6) {
TextView tv = findViewById(R.id.t7);
tv.setVisibility(View.VISIBLE);
}
if (counter > 7) {
TextView tv = findViewById(R.id.t8);
tv.setVisibility(View.VISIBLE);
}
if (counter > 8) {
Button b1 = findViewById(R.id.b1);
b1.setVisibility(View.VISIBLE);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent Menu = new Intent(varL2.this, Var.class);
startActivity(Menu);
addCounter();
}
});
}}
return true;
}
});
}
private void addCounter(){
if(Menu.counter == 12) {
Menu.counter = 13;
menuCounter counter = new menuCounter(Menu.counter);
databaseName.child(FirebaseAuth.getInstance().getCurrentUser().getUid()).setValue(counter);
System.out.println("AHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHHH");
}
}
}
XML Code
<?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:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bgcolour"
tools:context=".Variables.varL.varL2">
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent">
<TextView
android:id="#+id/t0"
android:layout_width="300sp"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:background="#drawable/edit_round"
android:gravity="center"
android:padding="10dp"
android:text="There are 8 primitive data types for creating variables in Java."
android:textColor="#android:color/black"
android:textColorHighlight="#FF000000"
android:textSize="15sp"
android:visibility="visible"
app:layout_constraintBottom_toTopOf="#+id/t1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/t1"
android:layout_width="300sp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="#drawable/edit_round"
android:gravity="center"
android:padding="10dp"
android:text="byte\n8 bit integer\n-128 to 127\nDefault of 0"
android:textColor="#android:color/black"
android:textColorHighlight="#FF000000"
android:textSize="15sp"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/t2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/t0" />
<TextView
android:id="#+id/t2"
android:layout_width="300sp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="#drawable/edit_round"
android:gravity="center"
android:padding="10dp"
android:text="short\n16 bit integer\n-32768 to 32767\nDefault of 0"
android:textColor="#android:color/black"
android:textColorHighlight="#FF000000"
android:textSize="15sp"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/t3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/t1" />
<TextView
android:id="#+id/t3"
android:layout_width="300sp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="#drawable/edit_round"
android:gravity="center"
android:padding="10dp"
android:text="int\n32 bit integer\n-2147483648 to 2147483647\nDefault of 0"
android:textColor="#android:color/black"
android:textColorHighlight="#FF000000"
android:textSize="15sp"
android:visibility="invisible"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/t2" />
<TextView
android:id="#+id/t4"
android:layout_width="300sp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="#drawable/edit_round"
android:gravity="center"
android:padding="10dp"
android:text="long\n64 bit integer\n-9223372036854775808 to 9223372036854775807\nDefault of 0L"
android:textColor="#android:color/black"
android:textColorHighlight="#FF000000"
android:textSize="15sp"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/t5"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/t3" />
<TextView
android:id="#+id/t5"
android:layout_width="300sp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="#drawable/edit_round"
android:gravity="center"
android:padding="10dp"
android:text="float\nDecimal point number\n1.5*10^-45 to 3.4*10^38\nDefault of 0.0f"
android:textColor="#android:color/black"
android:textColorHighlight="#FF000000"
android:textSize="15sp"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/t6"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.495"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/t4" />
<TextView
android:id="#+id/t6"
android:layout_width="300sp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="#drawable/edit_round"
android:gravity="center"
android:padding="10dp"
android:text="double\nDecimal point number\n5.0*10^-324 to 1.7*10^308\nDefault of 0.0"
android:textColor="#android:color/black"
android:textColorHighlight="#FF000000"
android:textSize="15sp"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/t7"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/t5" />
<TextView
android:id="#+id/t7"
android:layout_width="300sp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="#drawable/edit_round"
android:gravity="center"
android:padding="10dp"
android:text="char\nA unicode character e.g 'a','b'\n(\u0000 to \uffff) or (0 to 65535)\nDefault of null"
android:textColor="#android:color/black"
android:textColorHighlight="#FF000000"
android:textSize="15sp"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/t8"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.504"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/t6" />
<TextView
android:id="#+id/t8"
android:layout_width="300sp"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="#drawable/edit_round"
android:gravity="center"
android:padding="10dp"
android:text="boolean\nLogical true or false\ntrue or false\nDefault of false"
android:textColor="#android:color/black"
android:textColorHighlight="#FF000000"
android:textSize="15sp"
android:visibility="invisible"
app:layout_constraintBottom_toTopOf="#+id/b1"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.504"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/t7" />
<Button
android:id="#+id/b1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="150dp"
android:layout_marginTop="20dp"
android:layout_marginEnd="150dp"
android:layout_marginBottom="20dp"
android:background="#drawable/b_round"
android:text="Continue"
android:textColor="#android:color/white"
android:visibility="invisible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/t8" />
<TextView
android:id="#+id/x"
android:layout_width="15dp"
android:layout_height="35dp"
android:layout_marginStart="10dp"
android:text="x"
android:textColor="#android:color/white"
android:textSize="30sp"
app:layout_constraintBottom_toTopOf="#+id/t0"
app:layout_constraintEnd_toEndOf="#+id/t0"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0" />
</androidx.constraintlayout.widget.ConstraintLayout>
</ScrollView>
Fixed the issue by having the
View view = findViewById(R.id.ScrollView01);
reference the id of the constraint layout instead of the scroll view.
Usually when you are dealing with ScrollView you need to set android:fillViewport to true
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true">

Android ... My application doesn't launch?

So, I am trying to do an application which gives a user the ability to keep track of the score and number of fouls of two different teams playing football
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
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:fontFamily="sans-serif-medium"
android:gravity="center_horizontal"
android:padding="4dp"
android:paddingBottom="16dp"
android:paddingTop="16dp"
android:text="Team A"
android:textColor="#616161"
android:textSize="14sp" />
<TextView
android:id="#+id/team_a_goal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:gravity="center_horizontal"
android:padding="4dp"
android:paddingBottom="24dp"
android:paddingLeft="24dp"
android:paddingRight="24dp"
android:text="0"
android:textColor="#000000"
android:textSize="56sp" />
<TextView
android:id="#+id/team_a_foul"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:gravity="center_horizontal"
android:padding="4dp"
android:paddingBottom="24dp"
android:paddingLeft="24dp"
android:paddingRight="24dp"
android:text="0"
android:textColor="#000000"
android:textSize="56sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginBottom="8dp"
android:onClick="addGoalForTeamA"
android:text="GOAL" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginBottom="8dp"
android:onClick="addFoulForTeamA"
android:text="FOUL" />
</LinearLayout>
<view
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#android:color/darker_gray" />
<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:fontFamily="sans-serif-medium"
android:gravity="center_horizontal"
android:padding="4dp"
android:paddingBottom="16dp"
android:paddingTop="16dp"
android:text="Team B"
android:textColor="#616161"
android:textSize="14sp" />
<TextView
android:id="#+id/team_b_goal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:gravity="center_horizontal"
android:padding="4dp"
android:paddingBottom="24dp"
android:paddingLeft="24dp"
android:paddingRight="24dp"
android:text="0"
android:textColor="#000000"
android:textSize="56sp" />
<TextView
android:id="#+id/team_b_foul"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fontFamily="sans-serif-light"
android:gravity="center_horizontal"
android:padding="4dp"
android:paddingBottom="24dp"
android:paddingLeft="24dp"
android:paddingRight="24dp"
android:text="0"
android:textColor="#000000"
android:textSize="56sp" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginBottom="8dp"
android:onClick="addGoalForTeamB"
android:text="GOAL" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:layout_marginBottom="8dp"
android:onClick="addFoulForTeamB"
android:text="FOUL" />
</LinearLayout>
</LinearLayout>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="32dp"
android:onClick="Reset"
android:text="Reset" />
and java code
package com.example.android.scorekeeper;
import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int goalTeamA = 0;
int foulTeamA = 0;
int goalTeamB = 0;
int foulTeamB = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void addGoalForTeamA(View view) {
goalTeamA = +1;
displayGoalTeamA(goalTeamA);
}
public void addFoulForTeamA(View view) {
foulTeamA = +1;
displayFoulTeamA(foulTeamA);
}
public void addGoalForTeamB(View view) {
goalTeamB = +1;
displayGoalTeamB(goalTeamB);
}
public void addFoulForTeamB(View view) {
foulTeamB = +1;
displayFoulTeamB(foulTeamB);
}
public void Reset(View view) {
goalTeamA = 0;
foulTeamA = 0;
goalTeamB = 0;
foulTeamB = 0;
displayGoalTeamA(goalTeamA);
displayFoulTeamA(foulTeamA);
displayGoalTeamB(goalTeamB);
displayFoulTeamB(foulTeamB);
}
public void displayGoalTeamA(int score) {
TextView scoreView = findViewById(R.id.team_a_goal);
scoreView.setText(String.valueOf(score));
}
public void displayFoulTeamA(int score) {
TextView scoreView = findViewById(R.id.team_a_foul);
scoreView.setText(String.valueOf(score));
}
public void displayGoalTeamB(int score) {
TextView scoreView = findViewById(R.id.team_b_goal);
scoreView.setText(String.valueOf(score));
}
public void displayFoulTeamB(int score) {
TextView scoreView = findViewById(R.id.team_b_foul);
scoreView.setText(String.valueOf(score));
} }
The code seems fine to me and Android Studio doesn't report any errors but it did't launch on my android
make sure you have added your activity to your manifest file
<activity
android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

The math logic stopped working after i put the XML in a nested layout

I've just started with Android Development. The Order button stopped working after putting the textview and increment, decrements button in the nested layout. When i tried running it without the nested layout, the Order Button worked. But with it, the increment and decrements button is only working.
<?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Quantity"
android:textAllCaps="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:onClick="decrement"
android:text="-" />
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="8dp"
android:text="2"
android:textColor="#android:color/black"
android:textSize="16sp" />
<Button
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:onClick="increment"
android:text="+" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Price"
android:textAllCaps="true" />
<TextView
android:id="#+id/price_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="10"
android:textColor="#android:color/black"
android:textSize="16sp" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:onClick="submitOrder"
android:text="ORDER" />
</LinearLayout>
This is the Java Code
package com.example.android.justjava;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.text.NumberFormat;
/**
* This app displays an order form to order coffee.
*/
public class MainActivity extends AppCompatActivity {
int quantity = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
/**
* This method is called when the order button is clicked.
*/
public void submitOrder(View view) {
displayPrice(quantity * 10);
}
/**
*This method is called when the add/minus button is called
*/
public void increment(View view) {
quantity = quantity + 1;
display(quantity);
}
public void decrement(View view) {
quantity = quantity - 1;
display(quantity);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(R.id.quantity_text_view);
quantityTextView.setText("" + number);
}
/**
* This method displays the given price on the screen.
*/
private void displayPrice(int number) {
TextView priceTextView = (TextView) findViewById(R.id.price_text_view);
priceTextView.setText(NumberFormat.getCurrencyInstance().format(number));
}
}
Init your listener directly in Java:
private TextView quantityView;
private TextView priceView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
this.quantityView = findViewById(R.id.quantity_text_view);
this.priceView = findViewById(R.id.price_text_view);
TextView decrementTextView = findViewById(R.id.decrement_view);
decrementTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
decrement();
}
});
Button incrementView = findViewById(R.id.increment_view);
incrementView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment();
}
});
Button submitOrderView = findViewById(R.id.submit_order_view);
submitOrderView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
submitOrder();
}
});
}
public void submitOrder() {
displayPrice(quantity * 10);
}
/**
*This method is called when the add/minus button is called
*/
public void increment() {
quantity = quantity + 1;
display(quantity);
}
public void decrement() {
quantity = quantity - 1;
display(quantity);
}
/**
* This method displays the given quantity value on the screen.
*/
private void display(int number) {
quantityView.setText("" + number);
}
/**
* This method displays the given price on the screen.
*/
private void displayPrice(int number) {
priceView.setText(NumberFormat.getCurrencyInstance().format(number));
}
<?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">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Quantity"
android:textAllCaps="true" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/decrement_view"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:text="-" />
<TextView
android:id="#+id/quantity_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:paddingTop="8dp"
android:text="2"
android:textColor="#android:color/black"
android:textSize="16sp" />
<Button
android:id="#+id/increment_view"
android:layout_width="48dp"
android:layout_height="48dp"
android:layout_margin="8dp"
android:text="+" />
</LinearLayout>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="Price"
android:textAllCaps="true" />
<TextView
android:id="#+id/price_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="8dp"
android:text="10"
android:textColor="#android:color/black"
android:textSize="16sp" />
<Button
android:id="#+id/submit_order_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:text="ORDER" />
</LinearLayout>

How can call to refresh my fragment class in another method (I Tried all the solution on stackoverflow)

I have a void method synchronizeNum(String String String) Which will be trigger in onViewCreated , This Line.
new DisDepartmentSender(myView.getContext(), urlAddress, accountEmail, departmentName).execute();
It will get data from database and finally pass back and set the data into this method synchronizeNum (String String String).After i set the data i wish to display it using TextView. I think the only way is execute again onViewCreated method, since we cannot setText inside synchronizeNum method.I have tried many detach and attach method inside the method but the problem is it get NullPointer i donno how to solve i have been looking around for 1 day just for this little problem. I need you guys help please.
CurrentDepartmentView FragmentClass
package com.example.cheng.freequeue.DisplayDepartmentStatus;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.example.cheng.freequeue.R;
/**
* Created by cheng on 11/4/2018.
*/
public class CurrentStatusView extends Fragment {
DisDepartmentList disDepartmentList=new DisDepartmentList();
final static String urlAddress = "https://kokcheng95.000webhostapp.com/departmentStatus.php";
private String CompanyName, accountEmail, departmentName, imageUrl;
private String num1room1, num2room2, num3room3, num1, num2, num3, room1, room2, room3;
private final Handler handler = new Handler();
View myView;
Context c;
ViewGroup container;
private LayoutInflater inflater;
TextView company_name, department_name, num_1, num_2, num_3, room_1, room_2, room_3;
de.hdodenhof.circleimageview.CircleImageView image_department;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.current_department_view, container, false);
this.container=container;
company_name = (TextView) myView.findViewById(R.id.company_name);
department_name = (TextView) myView.findViewById(R.id.department_name);
image_department = (de.hdodenhof.circleimageview.CircleImageView) myView.findViewById(R.id.image_department);
num_1 = (TextView) myView.findViewById(R.id.number1);
num_1 = (TextView) myView.findViewById(R.id.number1);
num_2 = (TextView) myView.findViewById(R.id.number2);
num_3 = (TextView) myView.findViewById(R.id.number3);
room_1 = (TextView) myView.findViewById(R.id.room1);
room_2 = (TextView) myView.findViewById(R.id.room2);
room_3 = (TextView) myView.findViewById(R.id.room3);
new DisDepartmentSender(myView.getContext(), urlAddress, accountEmail, departmentName).execute();
//Set data
company_name.setText("Company Name : " + CompanyName);
department_name.setText("Department : " + departmentName);
PicassoClientDepartment.dowloadImage(myView.getContext(), imageUrl, image_department);
//Set Data
num_1.setText(num1);
num_2.setText(num1);
num_3.setText(num1);
room_1.setText(room1);
room_2.setText(room2);
room_3.setText(room3);
return myView;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = this.getArguments();
if (bundle != null) {
CompanyName = bundle.getString("CompanyName", "noText");
accountEmail = bundle.getString("accountEmail", "noText");
departmentName = bundle.getString("departmentName", "noText");
imageUrl = bundle.getString("imageUrl", "noText");
}
}
public void synchronizeNum(String num1room1, String num2room2, String num3room3) {
String path1[] = num1room1.split("_");
String path2[] = num2room2.split("_");
String path3[] = num3room3.split("_");
num1 = path1[0];
room1 = path1[1];
num2 = path2[0];
room2 = path2[1];
num3 = path3[0];
room3 = path3[1];
/* Fragment currentFragment = getActivity().getFragmentManager().findFragmentByTag("CurrentStatusView");
FragmentTransaction fragTransaction = (getActivity()).getFragmentManager().beginTransaction();
fragTransaction.detach(currentFragment);
fragTransaction.attach(currentFragment);
fragTransaction.commit();*/
}
public void setNum1room1(String num1room1) {
this.num1room1 = num1room1;
}
public String getNum1room1() {
return num1room1;
}
public void setNum2room2(String num2room2) {
this.num2room2 = num2room2;
}
public String getNum2room2() {
return num2room2;
}
public void setNum3room3(String num3room3) {
this.num3room3 = num3room3;
}
public String getNum3room3() {
return num3room3;
}
}
current_department_view.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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="com.example.cheng.freequeue.LoginPage">
<TextView
android:id="#+id/department_name"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="4dp"
android:text="Department : Orthopedic"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.163" />
<TableLayout
android:id="#+id/tableLayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.515"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.458">
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
<TextView
android:id="#+id/textView6"
android:layout_width="200dp"
android:layout_height="80dp"
android:layout_margin="0.1sp"
android:background="#drawable/cell_shape"
android:text="Number"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="40dp"
android:textStyle="bold" />
<TextView
android:id="#+id/textView5"
android:layout_width="150dp"
android:layout_height="80dp"
android:layout_marginTop="0.1sp"
android:background="#drawable/cell_shape"
android:text="Room"
android:textAlignment="center"
android:textColor="#080808"
android:textSize="40dp"
android:textStyle="bold" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-5dp">
<TextView
android:id="#+id/number1"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_margin="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="1001"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/room1"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_marginTop="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="2"
android:textAlignment="center"
android:textColor="#080808"
android:textSize="30dp"
android:textStyle="bold" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-5dp">
<TextView
android:id="#+id/number2"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_margin="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="1002"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/room2"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_marginTop="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="2"
android:textAlignment="center"
android:textColor="#080808"
android:textSize="30dp"
android:textStyle="bold" />
</TableRow>
<TableRow
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="-5dp">
<TextView
android:id="#+id/number3"
android:layout_width="200dp"
android:layout_height="50dp"
android:layout_margin="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="1003"
android:textAlignment="center"
android:textColor="#000000"
android:textSize="30dp"
android:textStyle="bold" />
<TextView
android:id="#+id/room3"
android:layout_width="150dp"
android:layout_height="50dp"
android:layout_marginTop="0.1sp"
android:background="#drawable/cell_shape_body"
android:text="2"
android:textAlignment="center"
android:textColor="#080808"
android:textSize="30dp"
android:textStyle="bold" />
</TableRow>
</TableLayout>
<Button
android:id="#+id/btn_booking"
android:layout_width="350dp"
android:layout_height="50dp"
android:background="#d7b9b9b9"
android:text="BOOKING"
android:textColor="#ffffff"
android:textSize="20dp"
android:textStyle="bold"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.965" />
<de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/image_department"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.015"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.048"
app:civ_border_color="#ffffff"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/company_name"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:layout_marginEnd="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
android:text="Company Name: TNB"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.064" />
</android.support.constraint.ConstraintLayout>
This Line Error ,NullPointer
Fragment currentFragment=getActivity().getFragmentManager().findFragmentByTag("CurrentStatusView");
Logcat error
04-12 20:52:13.112 3021-3021/com.example.cheng.freequeue E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at com.example.cheng.freequeue.DisplayDepartmentStatus.CurrentStatusView.synchronizeNum(CurrentStatusView.java:104)
at com.example.cheng.freequeue.DisplayDepartmentStatus.DisDepartmentParse.onPostExecute(DisDepartmentParse.java:64)
at com.example.cheng.freequeue.DisplayDepartmentStatus.DisDepartmentParse.onPostExecute(DisDepartmentParse.java:18)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5166)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:745)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:561)
at dalvik.system.NativeStart.main(Native Method)
I recommend to create an interface for updating data.
public interface SynchronizeCallback {
void synchronizeNum(String num1room1, String num2room2, String num3room3);
}
Your fragment should implement this interface.
Also set the text to the TextViews inside synchronizeNum():
num_1.setText(num1);
num_2.setText(num1);
num_3.setText(num1);
room_1.setText(room1);
room_2.setText(room2);
room_3.setText(room3);
Pass the interface to your task when you create it:
new DisDepartmentSender(myView.getContext(), urlAddress, accountEmail, departmentName, this).execute();
In onPostExecute of your AsyncTask call
syncronizeCallback.updateValues(newNum1room1, newNum2room2, newNum3room3);
Then you should see the new data.

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

Categories