Skip to content

Instantly share code, notes, and snippets.

@udacityandroid
Created May 25, 2015 23:58
  • Star 41 You must be signed in to star a gist
  • Fork 26 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
Android Development for Beginners : Court Counter - DisplayTeamA
/**
* Displays the given score for Team A.
*/
public void displayForTeamA(int score) {
TextView scoreView = (TextView) findViewById(R.id.team_a_score);
scoreView.setText(String.valueOf(score));
}
@lann22
Copy link

lann22 commented Jan 7, 2018

clear

@dennisotugo
Copy link

dab dab dab dab

@Maxwe1
Copy link

Maxwe1 commented Feb 1, 2018

Very Clear.

@abdullahelsheikh
Copy link

thanks

@Nogaeman
Copy link

Nogaeman commented Feb 6, 2018

This Code
1
And This is Result
untitled

@mamdogogo
Copy link

mamdogogo commented Feb 12, 2018


package com.example.android.courtcounter;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

int score = 0;
@OverRide
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

}
/**

  • Displays the given score for Team A.

*/
public void team_3_score (View view) {
score = (score + 3);
display (score);
}

public void team_2_score (View view) {
score = (score + 2);
display (score);
}

public void team_1_score (View view) {
score = (score + 1);
display (score);
}

private void display(int number) {
TextView quantityTextView = (TextView)
findViewById(R.id.team_a_score);
quantityTextView.setText("" + number);
}

}

screenshot_20180212-061521

@abdahma01
Copy link

untitled

@badrddinb
Copy link

DONE
image

@kkdroidgit
Copy link

kkdroidgit commented Mar 23, 2018

No need to cast View type explicitly from API level 26, this should also work

/**
  * Displays the given score for Team A.
  */
 public void displayForTeamA(int score) {
   TextView scoreView = findViewById(R.id.team_a_score);
   scoreView.setText(String.valueOf(score));
 }

@adithikrishnan
Copy link

amelenp, Even i have the same error...could you help me out?

@hudsonpereira
Copy link

Thanks

@hortontan
Copy link

package com.example.android.courtcounter;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    displayForTeamA(8);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

/**
 * Increase the score for Team A by 1 point.
 */
public void addOneForTeamA(View v) {
    displayForTeamA(1);
}

/**
 * Increase the score for Team A by 2 points.
 */
public void addTwoForTeamA(View v) {
    displayForTeamA(2);
}

/**
 * Increase the score for Team A by 3 points.
 */
public void addThreeForTeamA(View v) {
    displayForTeamA(3);
}

/**
 * Displays the given score for Team A.
 */
public void displayForTeamA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.team_a_score);
    scoreView.setText(String.valueOf(score));
}

@sneha123
Copy link

sneha123 commented May 14, 2018

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="TEAM A"
    android:gravity="center_horizontal"
    android:layout_margin="14dp"/>

<TextView
    android:id="@+id/team_a_score"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:gravity="center_horizontal"
    android:text="0" />


<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:text="+3 points"
    android:onClick="addThreeForTeamA"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:text="+2 points"
    android:onClick="addTwoForTeamA"/>


<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="8dp"
    android:text="Free throw"
    android:onClick="addOneForTeamA"/>
<LinearLayout
    android:orientation="vertical"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="wrap_content"
    >

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="TEAM B"
        android:gravity="center_horizontal"
        android:layout_margin="14dp"/>

    <TextView
        android:id="@+id/team_b_score"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:gravity="center_horizontal"
        android:text="0" />


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="+3 points"
        android:onClick="addThreeForTeamB"/>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="+2 points"
        android:onClick="addTwoForTeamB"/>


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:text="Free throw"
        android:onClick="addOneForTeamB"/>


</LinearLayout>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:text="Reset" />

How to add reset button in middle

@araby123
Copy link

its working :)
screen shot 2018-05-24 at 2 32 02 am

@yasoamro
Copy link

Thanks

@ayatbahaa96
Copy link

xml code :

<TextView
    android:id="@+id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Team A"
    android:textAlignment="center"
    android:layout_marginBottom="16dp"
    android:textSize="36sp"
    android:textColor="#000000"/>

<TextView
    android:id="@+id/text2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
   android:textAlignment="center"
    android:text="@string/_0"
    tools:ignore="InvalidId"
    android:layout_marginBottom="16dp"
    android:textColor="#000000"
    android:textSize="36dp"/>


<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:text="+3 points"
    android:textAllCaps="true"
    android:textSize="20sp"
    android:onClick="Button1"
    android:background="#000000"
    android:textColor="#ffffff"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="16dp"
    android:text="+2 points"
    android:textAllCaps="true"
    android:textSize="20sp"
    android:onClick="Button2"
    android:background="#000000"
    android:textColor="#ffffff"
    />

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"

    android:layout_marginBottom="16dp"

    android:text="Free throw"
    android:textAllCaps="true"
    android:textSize="20sp"
    android:onClick="Button3"
    android:background="#000000"
    android:textColor="#ffffff"
    />

java code
image

execute
image

@tooptooptoop
Copy link

screenshot_2018-06-03-18-26-46 1package com.example.android.courtcounter;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@OverRide
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
displayForTeamA(8);
}
/**

  • Displays the given score for Team A.
    */
    public void displayForTeamA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.team_a_score);
    scoreView.setText(String.valueOf(score));
    }
    }

@tooptooptoop
Copy link

screenshot_2018-06-03-19-25-33 1
package com.example.android.courtcounter;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    displayForTeamA(8);
}
/**
 * Displays the given score for Team A.
 */
public void displayForTeamA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.team_a_score);
    scoreView.setText(String.valueOf(score));
}

public void Button1(View view){
    displayForTeamA(3);
}
public void Button2(View view){
    displayForTeamA(2);
}
public void Button3(View view){
    displayForTeamA(1);
}

}

<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="4dp"
    android:text="Team A"/>


<TextView
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:padding="4dp"
    android:text="0"
    android:id="@+id/team_a_score"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:text="+3 Points"
    android:id="@+id/Button1"
    android:onClick="Button1"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:text="+2 Points"
    android:id="@+id/Button2"
    android:onClick="Button2"/>

<Button
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:text="Free throw"
    android:id="@+id/Button3"
    android:onClick="Button3"/>

@ahmethalici
Copy link

@TheEndIsNear
No this should be public because we will try to reach this method from xml

@Dileep124
Copy link

FAILURE: Build failed with an exception.

  • What went wrong:
    Execution failed for task ':app:mergeDebugResources'.

C:\Users\dilee\AndroidStudioProjects\FirstAPP\app\src\main\res\values\strings.xml: Error: Found item String/enter_a_number more than one time

  • Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

  • Get more help at https://help.gradle.org

BUILD FAILED in 1s

@Dileep124
Copy link

could you help me please

09/17 20:39:19: Launching app
$ adb shell am start -n "com.example.dilee.calculater/com.example.dilee.calculater.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 31260 on device oppo-cph1609-JRKFIJWOMZZDSSFU
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dilee.calculater, PID: 31260
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.Button.getText()' on a null object reference
at com.example.dilee.calculater.MainActivity$3.onClick(MainActivity.java:78)
at android.view.View.performClick(View.java:5290)
at android.view.View$PerformClick.run(View.java:21603)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:238)
at android.app.ActivityThread.main(ActivityThread.java:6006)
Application terminated.

@tko8567
Copy link

tko8567 commented Oct 5, 2018

could you help me please

09/17 20:39:19: Launching app
$ adb shell am start -n "com.example.dilee.calculater/com.example.dilee.calculater.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Connected to process 31260 on device oppo-cph1609-JRKFIJWOMZZDSSFU
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.dilee.calculater, PID: 31260
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.Button.getText()' on a null object reference
at com.example.dilee.calculater.MainActivity$3.onClick(MainActivity.java:78)
at android.view.View.performClick(View.java:5290)
at android.view.View$PerformClick.run(View.java:21603)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:238)
at android.app.ActivityThread.main(ActivityThread.java:6006)
Application terminated.

Show please your MainActivity.java file. Exception occurs at line 78. As I can see, you try the method getText() on some button which wasn't initialized, being null
Maybe you have forgotten to call findViewById(int reference) to initialize the variable

@mcface3000
Copy link

So, after creating the recommended resource file (menu) and creating menu_main (xml resource file), the final clincher for me was adding this to that xml file:

<item android:id="@+id/action_settings"
    android:title="Action Settings" />/>

Which I got from here:
https://code.tutsplus.com/tutorials/android-sdk-implement-an-options-menu--mobile-9453

@mohkatta
Copy link

finally I did
Activity_Main.Xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    android:layout_marginStart="0dp"
    android:layout_marginLeft="0dp"
    android:layout_marginTop="16dp"
    android:orientation="horizontal">

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation='vertical'
        tools:context='.MainActivity'>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="sans-serif-medium"
            android:gravity="center"
            android:padding="16dp"
            android:text="Team A"
            android:textColor="#616161"
            android:textSize="20sp" />

        <TextView
            android:id="@+id/team_a_score"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="sans-serif-black"
            android:gravity="center"
            android:padding="24dp"
            android:text="0"
            android:textColor="#000000"
            android:textSize="56sp" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="24dp"
            android:onClick="addThreeForTeamA"
            android:text="+3 Points" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="24dp"
            android:onClick="addTwoForTeamA"
            android:text="+2 Points" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="24dp"
            android:onClick="addOneForTeamA"
            android:text="Free throw" />
    </LinearLayout>

    view
        android:layout_width="10dp"
        android:layout_height="match_parent"
        android:background="@android:color/black"

    <LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:orientation='vertical'
        tools:context='.MainActivity'>

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="sans-serif-medium"
            android:gravity="center"
            android:padding="16dp"
            android:text="Team B"
            android:textColor="#616161"
            android:textSize="20sp" />
        <TextView
            android:id="@+id/team_b_score"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:fontFamily="sans-serif-black"
            android:gravity="center"
            android:padding="24dp"
            android:text="0"
            android:textColor="#000000"
            android:textSize="56sp" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="24dp"
            android:onClick="addThreeForTeamB"
            android:text="+3 Points" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="24dp"
            android:onClick="addTwoForTeamB"
            android:text="+2 Points" />

        <Button
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_margin="24dp"
            android:onClick="addOneForTeamB"
            android:text="Free throw" />
    </LinearLayout>
</LinearLayout>

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginLeft="22dp"
    android:layout_marginRight="22dp"
    android:layout_marginBottom="8dp"
    android:onClick="ResetScore"
    android:text="Reset" />

MainActivity.Java

package android.example.com;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
int scoreTeamA = 0;
int scoreTeamB = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

/**
 * Increase the score for Team A by 1 point.
 */
public void addOneForTeamA(View v) {
    scoreTeamA = scoreTeamA + 1;
    displayForTeamA(scoreTeamA);
}

/**
 * Increase the score for Team A by 2 points.
 */
public void addTwoForTeamA(View v) {
    scoreTeamA = scoreTeamA + 2;
    displayForTeamA(scoreTeamA);
}

/**
 * Increase the score for Team A by 3 points.
 */
public void addThreeForTeamA(View v) {
    scoreTeamA = scoreTeamA + 3;
    displayForTeamA(scoreTeamA);
}

/**
 * Increase the score for Team B by 1 point.
 */
public void addOneForTeamB(View v) {
    scoreTeamB = scoreTeamB + 1;
    displayForTeamB(scoreTeamB);
}

/**
 * Increase the score for Team B by 2 points.
 */
public void addTwoForTeamB(View v) {
    scoreTeamB = scoreTeamB + 2;
    displayForTeamB(scoreTeamB);
}

/**
 * Increase the score for Team B by 3 points.
 */
public void addThreeForTeamB(View v) {
    scoreTeamB = scoreTeamB + 3;
    displayForTeamB(scoreTeamB);
}

/**
 * Reset the score for both teams back to 0
 *
 * @param v
 */
public void ResetScore(View v) {
    scoreTeamA = 0;
    scoreTeamB = 0;
    displayForTeamA(scoreTeamA);
    displayForTeamB(scoreTeamB);
}

/**
 * Displays the given score for Team A.
 */
public void displayForTeamA(int score) {
    TextView scoreView = (TextView) findViewById(R.id.team_a_score);
    scoreView.setText(String.valueOf(score));
}

/**
 * Displays the given score for Team B.
 */
public void displayForTeamB(int score) {
    TextView scoreView = (TextView) findViewById(R.id.team_b_score);
    scoreView.setText(String.valueOf(score));
}

}

style.xml

<style name="AppTheme" parent="Theme.AppCompat.Light"> #FF9800 #FF9800 </style>

@hamada3a3
Copy link

شكرا جزيلا

@trys10studios
Copy link

works perfectly fine however I never initialed score to 0 but it starts at 0 How?

Preview shows nothing but actual phone starts at 0 ?

`package com.example.android.courtcounter;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
int score;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    displayForTeamA(score);
}

public void team_3_score (View view) {
    score = (score + 3);
    displayForTeamA(score);
}

public void team_2_score (View view) {
    score = (score + 2);
    displayForTeamA(score);
}

public void team_1_score (View view) {
    score = (score + 1);
    displayForTeamA(score);
}
/**
 * Displays the given score for Team A.
 */
public void displayForTeamA(int score ) {
    TextView scoreView = (TextView) findViewById(R.id.team_a_score);
    scoreView.setText(String.valueOf(score));
}

}`

xml code for the button, calls that Java method

<TextView
android:id="@+id/team_a_score"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:padding="16dp"
android:text="" // no value assigned either/
android:textColor="@color/colorPrimary"
android:textSize="32dp" />

For any one seeing this now, when you don't initialize a value, it's going to take (in memory) whatever value is at that address. Most of the time you get lucky and it's a "zero" value, sometimes it's some other garbage value (left over in memory from some other program for instance using that address), that's why it's best practice to initialize your values; avoids confusion and potential bugs.

BTW, I've been developing for quite some time C# (Unity3D), C (Arduino), C++, and others but I wanted to make sure I cover all the basics of Android dev, including best practices, for my own edification and self-assurance.

@trys10studios
Copy link

Using Java to set a onClickListener is a better practice than calling onClick from the XML; IMO of course. Though, I imagine that might be too much for a beginner.

@LaszloLajosT
Copy link

works perfectly fine however I never initialed score to 0 but it starts at 0 How?

Preview shows nothing but actual phone starts at 0 ?

Hi,
Your score variable is a global variable in your code, or other word: it is a class variable.
All the primitive types have default values in Java. And you called displayForTeamA(score); method automatically.
Stackoverflow Help is here:
https://stackoverflow.com/questions/19131336/default-values-and-initialization-in-java

I also checked what is happening if I don't have any value for a TextView in XML file AND I don't change the value in MainActivity.java. It that case, there is no value.

@jasvan
Copy link

jasvan commented Jun 5, 2020

THANKS

@hamzaabualkhair
Copy link

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        displayForTeamA(8);
    }
    /**
     * Displays the given score for Team A.
     */
    public void displayForTeamA(int score) {
        TextView scoreView =  findViewById(R.id.team_a_score);
        scoreView.setText(String.valueOf(score));
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment