[Hello], I have a problem.
Strings.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="num_e1_n1">%1$d</string>
</resources>
In the layout file :
<TextView
android:id="#+id/num_joueur_e1_n1"
style="#style/num_joueur"
android:layout_alignTop="#id/maillot_rouge1"
android:layout_centerHorizontal="true"
android:text="#string/num_e1_n1" />
And in the method onCreate() in the .java file :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_saisie_stats);
// ...
Resources res = getResources();
String numero = String.format(res.getString(R.string.num_e1_n1), 98);
num_rouge1 = (TextView) findViewById(R.id.num_joueur_e1_n1);
num_rouge1.setText(numero);
num_rouge2 = (TextView) findViewById(R.id.num_joueur_e1_n2);
num_rouge3 = (TextView) findViewById(R.id.num_joueur_e1_n3);
num_rouge4 = (TextView) findViewById(R.id.num_joueur_e1_n4);
//***
}
Unfortunately when I run my application, my Textview displays "%1$d"
Except I want it displays 98.
What's wrong? What do I need to change?
Thank you very much.
Update:
The problem seems to be that you somehow don't succeed to set text programmatically and your TextView shows value declared in layout :
<TextView
...
android:text="#string/num_e1_n1" />
You can try putting another string in layout to confirm that. Then you have to figure out why your num_rouge1.setText() code is not run.
You could try String.format, like this :
String numero = String.format(res.getString(R.string.num_e1_n1), 98);
But it should behave identically to your existing code.
Hope that helps.
Related
After login, I want to change text in TextView near profile on name_user.
But it doesn't change textView visually.
It is worth to mention, that when outputting (Toast), it gives out the data that is needed, but does not visually display it. Everything is fine with the TextView parameters (I think), because if you set the finished text in the parameters( i mean android:text="smth"), it visually displays it.
Java code:
`protected void onCreate(Bundle savedInstanceState) {
yourLayout = getLayoutInflater().inflate(R.layout.layout_navigation_header, null);
profileName = yourLayout.findViewById(R.id.profName); //
Intent intent = getIntent(); // Get data from previous activity.
String name_user = intent.getStringExtra("name");
String email_user = intent.getStringExtra("email");
String password_user = intent.getStringExtra("password");
profileName.setText(name_user); //0 changes, textView still don't change.
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu2);
DrawerLayout drawerLayout = findViewById(R.id.drawerLayout);
Toast toast = Toast.makeText(getApplicationContext(), profileName.getText().toString(),
Toast.LENGTH_SHORT); // for debug, it works and show profileName that contains name_user, but.
toast.show();
findViewById(R.id.imageMenu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
drawerLayout.openDrawer(GravityCompat.START);
}
});
}`
Part of main XML
`<com.google.android.material.navigation.NavigationView
android:id="#+id/navigationView"
android:layout_width="wrap_content"
android:layout_height="match_parent"
app:headerLayout="#layout/layout_navigation_header"// layour_navigation_header -here is TextView
app:menu='#menu/navigation_menu'
android:layout_gravity="start"/>`
Part of layour_navigation_header with TextView that I need to change.
`<TextView
android:id="#+id/profName"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="10dp"
android:textColor="#color/black"
android:textSize="18sp"
android:text="Temporary"
app:layout_constraintBottom_toTopOf="#id/viewSupporter"
app:layout_constraintStart_toEndOf="#id/imageProfile"/>`
Hope you could help me
I tried to move
`yourLayout = getLayoutInflater().inflate(R.layout.layout_navigation_header, null);
profileName = yourLayout.findViewById(R.id.profName); //
Intent intent = getIntent(); // Get data from previous activity.
String name_user = intent.getStringExtra("name");
String email_user = intent.getStringExtra("email");
String password_user = intent.getStringExtra("password");
profileName.setText(name_user); //0 changes, textView still don't change`
before
`super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu2);`
but final result remains the same. It contains data, but not visually displays it.
You're inflating layout_navigation_header layout and setting a value in one of its textviews. But you never seem to place the layout on screen, the layout instance simply gets discarded.
What gets displayed is the activity_menu2 layout you inflate and set as content view with setContentView(). If that layout includes layout_navigation_header or its look-a-like with some mechanism, it's not the same instance you inflated earlier.
To solve the issue, just call setContentView() to set your desired layout, call findViewById() to find the textview and set a text to it.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I'd like to create a TextView with the name of the person you've just tapped, but when I tap a name, it prints an error message to the console.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView parentView, View childView, int position, long id) {
System.err.println("clicked " + position);
System.err.println("clicked " + friendsIO.getPresentationText(position));
try {
JSONObject friendInformations = new JSONObject(friendsIO.getPresentationText(position));
String friendNames = friendInformations.getString("name");
System.err.println(friendNames);
TextView peopleName = (TextView) findViewById(R.id.peoplePerson);
peopleName.setText(friendNames);
String friendEmails = friendInformations.getString("email");
System.err.println(friendEmails);
String friendNumbers = friendInformations.getString("phone number");
System.err.println(friendNumbers);
String friendEmailsNumbers = friendNames + "\n" + friendEmails;
// TextView peopleInformations = (TextView) findViewById(R.id.peopleInfo);
// peopleInformations.setText(friendEmailsNumbers);
} catch (Exception e) {
e.printStackTrace();
}
final LayoutInflater peopleInflater = LayoutInflater.from(MainActivity.this);
final View peopleView = peopleInflater.inflate(R.layout.popup2, null);
final PopupWindow peoplePopup = new PopupWindow(peopleView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, true);
peoplePopup.showAtLocation(peopleView, Gravity.CENTER, 0, 0);
final Button peopleBack = (Button) peopleView.findViewById(R.id.cancel_button);
peopleBack.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
peoplePopup.dismiss();
}
}
);
I print the name to the console first, to make sure that it actually exists and I get the name I tapped (as well as the email and number, obviously), but instead of printing the name to the screen in a TextView, it gives me the following error message:
10-01 17:39:55.505 4259-4259/com.logit.data.returntosender W/System.err﹕ java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference
10-01 17:39:55.506 4259-4259/com.logit.data.returntosender W/System.err﹕ at com.logit.data.returntosender.MainActivity$1.onItemClick(MainActivity.java:60)
It says the error is at the line
System.err.println(friendNames);
But the TextView is only actually given afterwards, in line 61. I have tried around a bit, and not found what the problem could be. It's technically exactly how it should be, at least that's what I've been able to gather from other StackOverflow questions and a thorough google search.
The XML file of the popup with the name (and email and phone number, but that's not part of the question):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:background="#color/colorAroundPopups"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical|center_horizontal">
<TextView android:id="#+id/peoplePerson"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorOfPopups"
android:textStyle="bold"
android:text=""
android:textSize="52sp"/>
<TextView android:id="#+id/peopleInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/colorOfPopups"
android:textStyle="normal"
android:textSize="26sp"/>
<Button android:id="#+id/cancel_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cancel_it" />
</LinearLayout>
Thanks in advance
-Léon
EDIT: I added the part of the code where the popup, containing the TextView, is created.
EDIT: I found the found the solution. I had to put the name of the view containing the TextView before findViewById
Also, Frank N. Stein, thank you for not helping at all by sending me a question I had already looked through :)
You are retrieving the view from the activity, if the TextView was on the list item view, you would change...
TextView peopleName = (TextView) findViewById(R.id.peoplePerson);
to...
TextView peopleName = (TextView) childView.findViewById(R.id.peoplePerson);
instead of doing this:
TextView peopleName = (TextView) findViewById(R.id.peoplePerson);
do this:
TextView peopleName = (TextView) childView.findViewById(R.id.peoplePerson);
as your textview is a child of the listview.
I made a GIF from 2 JPGs photos, using the spin_animation.xml, according to the relative Android Developers tutorial. It works fine. But I want to change the GIF inside the ImageView in my layout. Basically, I want to change it to 50 different GIFs.
Is there a better and less silliest way to do that, instead of creating 50 spin_animation.xml, one for each GIF ?
For example, is there a way to use the id that I gave to the animation-list inside it ?
In my .java file, in the onCreate method, I call the spin_animation.xml in order to make a gif the 2 jpg pictures that I have in my drawables.
My .java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
// Load the ImageView that will host the animation and
// set its background to our AnimationDrawable XML resource.
ImageView img = (ImageView)findViewById(R.id.imageView1);
img.setBackgroundResource(R.drawable.spin_animation);
// Get the background, which has been compiled to an AnimationDrawable object.
AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground();
// Start the animation (looped playback by default).
frameAnimation.start();
}
My spin_animation.xml file in my drawable contains:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:id="#+id/selected" android:oneshot="false">
<item android:drawable="#drawable/barbellcurl1" android:duration="1000" />
<item android:drawable="#drawable/barbellcurl2" android:duration="1000" />
</animation-list>
And at last my ImageView in my .xml layout:
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView1"
android:layout_centerHorizontal="true"
android:layout_marginTop="106dp" />
You can create or modify animation drawables at runtime if you like:
AnimationDrawable createFrom(Context context, int id1, int id2) {
AnimationDrawable ad = new AnimationDrawable();
ad.addFrame(context.getResources().getDrawable(id1), 1000);
ad.addFrame(context.getResources().getDrawable(id2), 1000);
return ad;
}
Using above, you could do:
ImageView img = (ImageView)findViewById(R.id.imageView1);
img.setBackground(createFrom(this, R.drawable.barbellcurl1, R.drawable.barbellcurl2));
and you should still have the same result.
You can also define those drawables in a xml array: http://developer.android.com/guide/topics/resources/more-resources.html#TypedArray - the advantage is that you have to write less code and you can now define all your "gif"s in a single xml file.
Using a typed array should work like this:
AnimationDrawable createFromArray(Context context, int arrayId) {
TypedArray array = context.getResources().obtainTypedArray(arrayId);
AnimationDrawable ad = new AnimationDrawable();
for (int i = 0; i < array.length(); i++) {
ad.addFrame(array.getDrawable(i), 1000);
}
array.recycle();
return ad;
}
The content of the XML file would look like res/values/gifs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<array name="gif1">
<item>#drawable/barbellcurl1</item>
<item>#drawable/barbellcurl2</item>
</array>
<array name="gif2">
<item>#drawable/cat</item>
<item>#drawable/dog</item>
</array>
</resources>
And to get a drawable in code you would do createFromArray(this, R.array.gif1) etc.
The code in onCreate in the end would be
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_progress);
ImageView img = (ImageView)findViewById(R.id.imageView1);
AnimationDrawable ad = createFrom(this, R.drawable.barbellcurl1, R.drawable.barbellcurl2);
// OR
AnimationDrawable ad = createFromArray(this, R.array.gif1);
ad.setOneShot(false);
img.setBackground(ad);
ad.start();
}
Need some help debugging my code. I am very new to the Android SDK and am working on learning it. From what I can glean from several posts on SO and other google search results... I formulated this code.
public class MainMenu extends Activity {
private int str = 8, dex = 8, inte = 8, luk = 8, stats = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayShowHomeEnabled(false);
getActionBar().setDisplayShowTitleEnabled(false);
setContentView(R.layout.activity_main_menu);
}
As you can see, I have created a few private variables my app is going to use to store data. In order to interact with these values, I will redraw the TextView each time they are modified. *Feel free to correct me here if this is not an ideal strategy.
public void strup(View view) {
if(stats > 0) {
TextView tv = (TextView)findViewById(R.id.textView4);
TextView st = (TextView)findViewById(R.id.textView18);
str++;
stats--;
tv.setText(str);
st.setText(stats);
} else {
Toast.makeText(this, "Out of stats!", Toast.LENGTH_SHORT).show();
}
I use a button with the following format.
Str [X] [+1]
Where Str [X] is TextView with X a dynamic value.
Also where [+1] is a button with an Onclick function preset by the XML file.
<TextView
android:id="#+id/textView9"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Str [" />
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="8" />
<TextView
android:id="#+id/textView13"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="]" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="strup"
android:text="+1" />
Now for simplicity, I have altered the "android:text="" " lines to reflect their actual values instead of linking to #string/... I don't think this makes of much difference but I wanted to acknowledge it.
So my question is why does my Application crash when I click the "+1" button? All my app is trying to do is to redraw the TextView with a higher value (under str) and a lower value (under stats).
Thanks for any and all help!
You are passing integer value in settext. Either cast integer to string or you can try changing settext like this:
tv.setText(""+str);
st.setText(""+stats);
You tried to create this object:
TextView st = (TextView)findViewById(R.id.textView18);
where is textView18 in the xml?
u can caste using toString method like this:
tv.setText(str.toString());
st.setText(stats.toString());
Try this change the position of your setContentView(R.layout.activity_main_menu);
public class MainMenu extends Activity {
private int str = 8, dex = 8, inte = 8, luk = 8, stats = 20;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
getActionBar().setDisplayShowHomeEnabled(false);
getActionBar().setDisplayShowTitleEnabled(false);
}
I am trying to develop a chat room for an Android App. I have a created some area for EditText and a corresponding button to Enter the text that is typed by a user.
On clicking on Enter I want to display the typed text on the same screen i.e. whatever text is being typed, it is subsequently being displayed on the same screen. I am using Linear Layout(Horizontal) for my app.
How can I implement this ?? Can someone help me with the code. I am totally new to Android Development Framework. Thanks and Regards.
Its very simple. You create the xml file with one textView and one edittext and one button. Then you handle the event of button click in mainActivity and call onResume from it. Override the onResume so that you can update the textview.
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
TextView text = (TextView) findViewById(R.id.txtView1);
EditText editBox = (EditText)findViewById(R.id.txtBox1);
String str = text.getText().toString();
text.setText(str+" "+editBox.getText().toString());
editBox.setText("");
editBox.setHint("Type in here");
}
You can use 'Toast' to display the msg or use another 'TextView' which is set using 'setText()'
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<LinearLayout android:id="#+id/linearLayout1" android:layout_width="match_parent"android:orientation="vertical" android:layout_height="match_parent">
</LinearLayout>
<LinearLayout android:id="#+id/linearLayout2"android:orientation="horizontal" android:layout_width="fill_parent" android:layout_height="fill_parent">
<EditText...
<Button...
</LinearLayout>
</LinearLayout>
setContentView(R.Layout.main);
LinearLayout ll = (LinearLayout)findViewById(R.id.linearLayout1); //Layout where you want to put your new dynamic TextView.
String s=editText.getText().toString(); //Fetching String from your EditText
TextView tv = new TextView(this);
tv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
tv.setText(s);
ll.addView(tv); //Add TextView inside the Layout.
You can use an one editText for input and one TextView for displaying the typed message:
tvChatWindow = (TextView) findViewById(R.id.tvChatWindow);
etInputWindow = (EditText) findViewById(R.id.etInputWindow);
btnEnter = (Button) findViewById(R.id.btnEnter);
btnEnter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// send message to other chat clients here
//add a new line break character and the typed string to Chat Window
tvChatWindow.append("\n" + etInputWindow.getText().toString());
//clear the text you have typed on the edittext
etInputWindow.setText("");
}
});