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.
Related
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));
}
});
}
}
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 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>
I'm trying to implement onclicklistener but it isn't working on my phone or emulator.
here is the code:
package com.slaps.guess;
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 MainActivity extends Activity implements OnClickListener {
TextView tv;
Button one;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
one = (Button) findViewById(R.id.button1);
tv = (TextView) findViewById(R.id.tvd);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.button1:
tv.setText("Anything");
break;
}
}
}
the text view is not changing to anything it is still.
note: button1 exists, and their is nothing wrong with my xml.
i want to implement because i have alot of button.
You are missing one.setOnClickListener(this) in your code.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
one = (Button) findViewById(R.id.button1);
one.setOnClickListener(this);
tv = (TextView) findViewById(R.id.tvd);
}
Before using listener you will have to add it in the object for which you want it.
I guess you want for the Button one here.
Use one.setOnClickListener(this) after one = (Button) findViewById(R.id.button1);
It looks like you're missing the required XML attribute in res/layout/activity_main.xml. Ensure it looks like:
<Button
android:id="#+id/button1"
onClick="onClick"
/>
The key being you have supplied the onClick attribute with the name of your method to invoke.
But if you want to set the click listener programmatically than you will need to use the Button.setOnClickListener method. If you do this your method signature will need to change to:
one.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
I have an existing application that I am trying to modify and could really use some help.
It is a chat application. The original flow of the application was as follows:
Launch-> Splash Screen Activity-> MainActivity (extending Actionbar Sherlock)
Once in the main activity the default fragment is the ChatRoomFragment. From there you can select different tabs and interact with the application.
What I would like to change about the flow to is the following:
Launch->Splash Screen Activity-> Terms of Service/Sign -> MainMenu->MainActivity
I have created the mainmenu layout to contain 4 buttons. Join, Search, Profile, Settings
Here is the problem. My Join button works fine, onClick simply triggers the intent to start MainActivity and and the chat room loads. From this screen you can access the different tabs and fragments within the application.
However, I now would like to have the "search" button set to open a dialog. With a editText field and a search button. Upon clicking search it should pass the search string to the PlacesSearchFragment and populate results.
I copied the code from within my application where this search is normally completed (inside the ChatRoomsFragment but it will not work from within my mainMenu Activity.
How do I start the new fragment from the menu activity??
Code Below:
menuActivity.java
package com.peekatucorp.peekatu;
//import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.actionbarsherlock.app.ActionBar;
import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
public class menuActivity extends Activity implements ActionBar.TabListener {
Button b1;
Button b2;
Button b3;
EditText txtsearch;
final private static int DIALOG_LOGIN = 1;
final private static int DIALOG_FORGET = 2;
final private static int DIALOG_SEARCH = 3;
private android.app.FragmentTransaction ft;
#Override
public void onCreate(Bundle savedInstanceState) {
SharedPreferences preferences = this.getSharedPreferences("MyPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenu);
if(preferences.getString("Username", "").length()<=0 || preferences.getString("loggedin_user", "").length()<=0){
showDialog(DIALOG_LOGIN);
}
b1= (Button) this.findViewById(R.id.joinbutton);
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(menuActivity.this, MainActivity.class);
menuActivity.this.startActivity(intent);
SharedPreferences preferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("loadMain", "1");
editor.commit();
}
});
b2= (Button) this.findViewById(R.id.searchbutton);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
showDialog(DIALOG_SEARCH);
}
}
);
}
#Override
protected Dialog onCreateDialog(int id) {
AlertDialog dialogDetails = null;
switch (id) {
case DIALOG_LOGIN:
if(true){
....some code}
break;
case DIALOG_FORGET:
if(true){
...some code
}
break;
case DIALOG_SEARCH:
if(true){
LayoutInflater inflater = LayoutInflater.from(this);
View dialogview = inflater.inflate(R.layout.menusearch_layout, null);
AlertDialog.Builder dialogbuilder = new AlertDialog.Builder(this);
dialogbuilder.setTitle("Where ya headed?");
dialogbuilder.setView(dialogview);
dialogDetails = dialogbuilder.create();
}
}
return dialogDetails;
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DIALOG_LOGIN:
...some code
break;
case DIALOG_SEARCH:
final AlertDialog alertDialog3 = (AlertDialog) dialog;
final Button btnLocalsearch = (Button) alertDialog3
.findViewById(R.id.local_search);
final Button btnSearch = (Button) alertDialog3
.findViewById(R.id.btn_search);
final EditText txtsearch = (EditText) alertDialog3
.findViewById(R.id.txtsearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
//showDialog(DIALOG_FORGET);
//alertDialog3.dismiss();
// TODO Auto-generated method stub
menuActivity m = com.peekatucorp.peekatu.menuActivity.this;
final TabInfo tab = com.peekatucorp.peekatu.menuActivity.this.getCurrentTabInfo();
final PlacesSearchFragment fragment = new PlacesSearchFragment().setNAV(m).setSearch(txtsearch.getText().toString(),"1");
// fragment.setText(characters[position]);
// second, you push the fragment. It becomes visible and the up button is
// shown
m.pushFragment(tab, fragment);
}
});
}
mainmenu.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:layout_width="wrap_content"
android:layout_height="65dp"
android:layout_marginLeft="10dip"
android:src="#drawable/registration_banner3"
android:id="#+id/imageView" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Join Chat"
android:id="#+id/joinbutton"
android:layout_below="#+id/imageView"
android:layout_alignLeft="#+id/imageView"
android:layout_alignStart="#+id/imageView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:id="#+id/searchbutton"
android:layout_below="#+id/joinbutton"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="55dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Profile"
android:id="#+id/prfbutton"
android:layout_below="#+id/searchbutton"
android:layout_marginTop="72dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignLeft="#+id/searchbutton"
android:layout_alignStart="#+id/searchbutton" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Settings"
android:id="#+id/settingsbutton"
android:layout_below="#+id/prfbutton"
android:layout_marginTop="51dp"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<LinearLayout android:id="#+id/footer"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#layout/footer_repeat"
android:layout_alignParentBottom="true">
</LinearLayout>
</RelativeLayout>
ChatRoomsFragment.java (WORKING FRAGMENT)
public class ChatRoomsFragment extends SherlockFragment implements OnItemSelectedListener{
String[] items;
List<String> list;
Spinner my_spin;
RadioButton mainRoom;
RadioButton customRoom;
RadioButton GPSRoom;
EditText privateRoom;
EditText GPSsearch;
TextView GPSaddress;
String selected_public;
Context contexxt;
ImageLoader imageLoader;
public AbstractTabStackNavigationActivity navact;
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
setRetainInstance(true);
final View v = inflater.inflate(R.layout.chatrooms_layout, container, false);
contexxt = v.getContext();
// setRetainInstance(true);
SharedPreferences preferences = v.getContext().getSharedPreferences("MyPreferences", this.getActivity().MODE_PRIVATE);
my_spin=(Spinner)v.findViewById(R.id.spinner1);
my_spin.setOnItemSelectedListener(this);
selected_public = preferences.getString("selected_room", "Adult Lobby");
AsyncHttpClient client = new AsyncHttpClient();
RequestParams params = new RequestParams();
GPSsearch = (EditText)v.findViewById(R.id.cr_gps_search);
GPSaddress = (TextView)v.findViewById(R.id.cr_gps_address);
GPSaddress.setText(preferences.getString("user_location", ""));
Button search_go = (Button)v.findViewById(R.id.cr_go_search);
Button address_go = (Button)v.findViewById(R.id.cr_go_address);
Button changeroom = (Button)v.findViewById(R.id.cr_changeroom);
//Button changeroom2 = (Button)v.findViewById(R.id.cr_changeRoom2);
search_go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
MainActivity m = (MainActivity)getActivity();
final TabInfo tab = m.getCurrentTabInfo();
final PlacesSearchFragment fragment = new PlacesSearchFragment().setNAV(m).setSearch(GPSsearch.getText().toString(),"1");
// fragment.setText(characters[position]);
// second, you push the fragment. It becomes visible and the up button is
// shown
m.pushFragment(tab, fragment);
}
});
Can someone please explain to me how to get it to load the fragment. Thank you. Let me know if I am leaving out any relevant code. Im getting a null pointer exception as my error.
Well, first of all, here is the code I was talking about in my comment:
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
menuActivity m = dialog.getOwningActivity();
final TabInfo tab = m.getCurrentTabInfo();
final PlacesSearchFragment fragment = new PlacesSearchFragment().setNAV(m).setSearch(txtsearch.getText().toString(),"1");
m.pushFragment(tab, fragment);
...
However, now that I type this up, it doesn't make sense that the NPE was on the call to pushFragment like you said. If the activity outer-class reference was really the null pointer, then it should have crashed a few lines earlier, calling getCurrentTabInfo. Thus I don't think this code change will help. Please take a second look at the stack you are seeing, and tell me what line the NPE is happening on.