I'm new to Android and in my class we have to make a program where every time a button is pressed the count increases and this number is shown inside the button. For example, the button starts at 0 and I click the button and it changes the text from 0 to 1, than click again it goes from 1 to 2 and so on but number changes in the button. Is it possible to do something like this without using TextView?
This is what I have on my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="countUp"
android:text="0"
tools:layout_editor_absoluteX="72dp"
tools:layout_editor_absoluteY="61dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
and this is what I have on my MainActivity.java
package com.example.tapgrid;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button showValue;
int counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showValue = (Button) findViewById(R.id.button);
}
public void countUp (Button view) {
counter++;
showValue.setText(Integer.toString(counter));
}
}
EditText accepts only Strings values since the counter variable is an integer so the app crashes, it is better to cast it to string then set it to edittext
showValue.setText(String.valueOf(counter));
You need to set the onClick Listener on the button which listens to click events
findViewById(R.id.button).setOnClickListener(clickListener);
...
private View.OnClickListener clickListener = v -> {
int count = Integer.parseInt(((Button) v).getText().toString());
((Button) v).setText(String.valueOf(++count));
};
public class MainActivity extends AppCompatActivity {
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String str = (String) button.getText();
int i = Integer.parseInt(str);
button.setText(String.valueOf(++i));
}
});
}
}
Related
I'm working on a pretty simple project .. All I'm trying to do is changing the value of a textView.
Here is the scenario: There is a button and a textView. The default value of that textView is no. it should be yes when I click on that button. That's it.
Here is my XML 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" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="No"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
And this is the JAVA code:
package ir.testApp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class TestAppActivity extends Activity {
TextView text1;
Button btn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button) findViewById(R.id.button1);
text1 = (TextView) findViewById(R.id.textView1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
text1.setText("yes");
}
});
}
}
Currently it doesn't work. I mean nothing happens when I click on that button. Well what's wrong?
Note: When I put that button in the top of that textView, it works like a charm. So Why it won't work when the button is after that textView?
Changing the button position in XML only changes the View of your activity and can't resolve your problem.
Your are instantiating the TextView and setting a view to it in every click of button(!)
Instead of this, you have to instantiate the TextView like as your button and in your button clickListener just call setText("yes").
public class TestAppActivity extends Activity {
TextView text1;
Button btn1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn1 = (Button) findViewById(R.id.button1);
text1 = (TextView) findViewById(R.id.textView1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
text1.setText("yes");
}
});
}
}
Try this,
text1 = (TextView) findViewById(R.id.textView1);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
text1.setText("yes");
}
});
Note : Best way is, Initialize all UI Components at Outside of the listeners.
Edit Code Like this
btn1 = (Button) findViewById(R.id.button1);
text1 = (TextView) findViewById(R.id.textView1);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
text1.setText("yes");
}
});
What is going on i don't know!! Code is 100000% ok. Nothing wrong.
I'm a newcomer to Java and Android Studio so am still learning, so sorry if this question is simplistic. I have recently discovered that as an alternative to coding an onClickListener in the activity.java file to respond to a button click, it can be done more simply with an android:onClick="method name" in the corresponding layout.xml file. I have already looked at this site's questions relating to the pros and cons of each method, but that is not my problem. My problem is, where and how can I declare a text field that is used by two methods without having to declare it in each method?
The code that follows is as minimal as possible. There are two buttons and one text view. If I attempt to put "TextView themessage = (TextView) findViewById(R.id.message);" anywhere other than in both methods, I get the dreaded "Attempt to invoke virtual method 'android.view.View android.view.Window.findViewById(int)' on a null object reference".
Is there anywhere and any way to make a single declaration that can be used by both methods without generating this exception?
Extract from the .xml file
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click me"
android:id="#+id/topbutton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="88dp"
android:onClick="doit"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="***"
android:id="#+id/message"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Again"
android:id="#+id/againbutton"
android:layout_below="#+id/message"
android:layout_centerHorizontal="true"
android:layout_marginTop="63dp"
android:onClick="starit"/>
Top end extract from the .java file
package com.example.owner.clickme;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void doit (View v)
{
TextView themessage = (TextView) findViewById(R.id.message);
themessage.setText("Well clicked, Sir!");
}
public void starit (View v)
{
TextView themessage = (TextView) findViewById(R.id.message);
themessage.setText("****");
}
.
. etc.
It is common practice in Android to instantiate any Views within the onCreate, or where you inflate the main content view.
So, make a field inside of MainActivity like so
private TextView themessage;
Within onCreate get the TextView
theMessage = (TextView) findViewById(R.id.message);
Then you are free to use theMessage across both methods.
All in all, it looks like this
public class MainActivity extends AppCompatActivity
{
private TextView themessage;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
themessage = (TextView) findViewById(R.id.message);
}
public void doit (View v)
{
themessage.setText("Well clicked, Sir!");
}
public void starit (View v)
{
themessage.setText("****");
}
}
I think what you want to do is have the TextField as member of your activity class.
Something like that probably
public class MainActivity extends AppCompatActivity {
TextView theMessage;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
theMessage = (TextView) findViewById(R.id.message);
}
public void doit () {
theMessage.setText("Well clicked, Sir!");
}
public void starit() {
themessage.setText("****");
}
}
I'm trying to create a settings page for my app which has the radioGroup for 3 options to help users change the colour of the text in differrent layout/xml file. But in mysettings page I cant call the view from different layout, any idea?
Below are my codes:
Settings.Java
package com.example.sunny.mynote;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import android.widget.EditText;
/**
* Created by Sunny on 19/04/2015.
*/
public class Settings extends Activity {
private RadioGroup RadioGroup1;
private RadioButton rdbRed, rdbBlue, rdbOrange;
private Button btnSave;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings);
RadioGroup1 = (RadioGroup) findViewById(R.id.RadioGroup1);
RadioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId == R.id.rdbRed)
{
Toast.makeText(getApplicationContext(), "choice: Red",
Toast.LENGTH_SHORT).show();
}
else if(checkedId == R.id.rdbBlue)
{
Toast.makeText(getApplicationContext(), "choice: Blue",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "choice: Orange",
Toast.LENGTH_SHORT).show();
}
}
});
rdbRed = (RadioButton) findViewById(R.id.rdbRed);
rdbBlue = (RadioButton) findViewById(R.id.rdbBlue);
rdbOrange = (RadioButton) findViewById(R.id.rdbOrange);
editText = (EditText) findViewById(R.id.editText);
btnSave = (Button)findViewById(R.id.btn_Save);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int selectedId = RadioGroup1.getCheckedRadioButtonId();
if(selectedId == rdbRed.getId()) {
//textView.setText("You chose 'Sound' option");
} else if(selectedId == rdbBlue.getId()) {
//textView.setText("You chose 'Vibration' option");
} else {
//textView.setText("You chose 'Silent' option");
}
finish();
}
});
}
#Override
public void onBackPressed() {
}
}
and I want to FindViewbyID from this layout, an EditText from this view to be exactly
<?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">
<EditText
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/noteText"
android:singleLine="false"
android:gravity="top"
android:inputType="textImeMultiLine"
android:layout_alignParentBottom="true" />
</RelativeLayout>
I think you can create an intent with extras like this:
Intent i=new Intent(context,Class.class);
i.putExtra("ColorChoice",color);
And then extract this data from your main class with:
intent.getStringExtra("ColorChoice");
You cannot do that in your Settings.java activity if your editText is not in this activity.
You can either use intent with putExtra and getExtra like #user3624383 mentioned. (more on this here)
Or a better way would be to use SharedPreferences to save your settings even if the user exits your app and return to it later
I have just gone through the android "first app" tutorial located Here, and I want to start experimenting on my own with the stuff that tutorial taught me.
What I want to do is take the message the user writes in the first activity, and display it in a TextView element, which i have defined in the XML file for the second activity. How do I edit the properties of a text view using the java code? I have no idea how to edit any of the properties of the element, even though I know its android:id . Can anyone give me any insight into this?
TextView textView = (TextView) findViewById(R.id.id_of_the_textview);
textView.setText(yourNewText);
What I want to do is take the message the user writes in the first activity
I assume you'll use an EditText in your FirstActivity, so you have to get the text from this widget and pass it as an extra in your intent used to switch to the second activity.
In your FirstActivity onCreate method it will look like :
EditText myEditText = (EditText) findViewById(R.id.yourEditTextId);
Intent i = new Intent(this, ToClass.class);
i.putExtra("myText", myEditText.getText().toString());
startActivity(i);
And in your SecondActivity onCreate methode :
Intent intent = getIntent();
String text = intent.getExtras().getString("myText");
TextView myTextView = (TextView) findViewById(R.id.yourTextViewId);
myTextView.setText(text);
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.EditText;
public class MainActivity extends Activity {
Button button1;
String text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addListenerOnButton();
}
public void addListenerOnButton() {
button1 = (Button) findViewById(R.id.buttoncalculate);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
EditText editText = (EditText)findViewById(R.id.editText1);
String text = editText.getText().toString();
Intent myIntent = new Intent(view.getContext(),Calculated.class);
myIntent.putExtra("mytext",text);
startActivity(myIntent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Calculated.java
public class Calculated extends Activity {
TextView mTextview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculated);
mTextview = (TextView)findViewById(R.id.textView1);
mTextview.setText(getIntent().getStringExtra("mytext"));
}
calculated.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
It's fairly simple. I am trying to learn how to establish sqlite connection for an android application.
I am using Android Studio to write the code. When I try to load the app on my testing device - Android Phone of API 15 - a white screen flashes and an alert box pops up saying "LearnDB has stopped working".
Please tell me where I am going wrong.
IMPORTANT NOTE- Please try to explain how a sqlite connection should be exactly established and what rules should I definitely keep in mind while doing the same.
Feel free to tell me any good programming practices while working with sqlite for android.
This is my MainActivity.java file.
package com.example.summer.learndb;
import android.database.sqlite.SQLiteDatabase;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private SQLiteDatabase db ;
public static final String DB_NAME = "scoreDb.db";
public static final int DB_VERSION = 1;
public static final String CREATE_DB_TABLE = "CREATE TABLE IF NOT EXISTS scoreTable (score1 INTEGER, score2 INTEGER);";
public static final String DB_TABLE = "scoreTable";
Button b1= (Button) findViewById(R.id.button1);
Button b2 = (Button) findViewById(R.id.button2);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
db = openOrCreateDatabase(DB_NAME, SQLiteDatabase.CREATE_IF_NECESSARY,null);
db.close();
try{
db.execSQL(DB_TABLE);
db.close();
Toast.makeText(getBaseContext(),"Table created!!!",Toast.LENGTH_LONG).show();
}
catch(Exception e){
Toast.makeText(getBaseContext(),"ERROR!!!!", Toast.LENGTH_LONG).show();
}
b1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
}
});
b2.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
}
});
}
}
This is my activity_main.xml file.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="add"
android:id="#+id/button1" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="show"
android:id="#+id/button2" />
</LinearLayout>
Take one context and write following code.
public Context context;
db = context.openOrCreateDatabase("scoreDb.db", Context.MODE_PRIVATE, null);
You need to remove following line that you have written exactly after openorCreateDatabase().
db.close();
Write this
db.execSQL(CREATE_DB_TABLE);
instead of
db.execSQL(DB_TABLE);
Ram Mansawala is absolutely wright, but I think You have another problem. Your db.execSQL is inside a try catch, so it will not be the cause of the crash. What You have done is, to initialize buttons before setContentView. That´s a problem, because the system cannot find them. Do it like this:
public class MainActivity extends Activity {
private SQLiteDatabase db ;
public static final String DB_NAME = "scoreDb.db";
public static final int DB_VERSION = 1;
public static final String CREATE_DB_TABLE = "CREATE TABLE IF NOT EXISTS scoreTable (score1 INTEGER, score2 INTEGER);";
public static final String DB_TABLE = "scoreTable";
Button b1;
Button b2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button1);
b2 = (Button) findViewById(R.id.button2);
db = openOrCreateDatabase(DB_NAME, SQLiteDatabase.CREATE_IF_NECESSARY,null);
.
.
.
etc
Initialize Your buttons after setContentView()
EDIT
Explaining how sqlite should be implemented is out of range here, but here are good tutorials:
http://www.vogella.com/tutorials/AndroidSQLite/article.html
http://hmkcode.com/android-simple-sqlite-database-tutorial/
http://examples.javacodegeeks.com/android/core/database/sqlite/sqlitedatabase/android-sqlite-example/