Add an ImageView statically in Android Studio - java

I want to change the resource of an image view from a variable in android studio.
Let me explain you, i have first activity "selector activity" which has 21 images, on every image click, a variable god_name is changed to the particular god, now i am sending that variable using putExtra, now i want that to change the resource of an ImageView in MainActivity depending on the variable, for example if the variable is "two", then i want to change the resource to "R.drawable.two".
Something like that, I have some experience in python so I used f strings there, here can I do something?
MainActivity.class
(Note-I have not Included imports so the code is allowed to be uploaded.)
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String god_name = getIntent().getExtras().getString("chosen_god").toString();
ImageView god = findViewById(R.id.god);
god.setImageResource();
}
}
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"
android:background="#color/black"
tools:context=".MainActivity">
<ImageView
android:id="#+id/god"
android:layout_width="413dp"
android:layout_height="496dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.666"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"
app:srcCompat="#mipmap/hanuman" />
</androidx.constraintlayout.widget.ConstraintLayout>
I can use multiple if conditions and switch case statement but that would be so much large as I would have to write it 21 times so it is very difficult!
Thanks in advance for anyone kind of help!

That sounds like you need to use the resources.getIdentifier() to make this work.
I wrote once an answer to a related topic: https://stackoverflow.com/a/4865350/180538
Anyway what you need is to pass the name of the resource and then resolve the identifier to use it. So something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// make sure that god_name is the name of the resource, so AFTER R.mipmap.[resourceName]
// so for R.mipmap.two you need to pass "two" as "chosen_god" extra
String god_name = getIntent().getExtras().getString("chosen_god").toString();
ImageView god = findViewById(R.id.god);
int resId = getResources().getIdentifier(god_name, "mipmap", getPackageName());
god.setImageResource(resId);
}

Related

The button of a Android project simply does not work [duplicate]

I am developing a small project of test, and I wrote the following code.
I already created in the xml file, a button with id called "registerBtn".
I erased the imports of this source code to shorten space of this source code.
In the java file, I created a variable called mRegisterBtn, in the type of Button.
Inside the method called onCreate(Bundle savedInstanceState) the mRegisterBtn receives the method called findViewById(R.id.registerBtn);
However, in the mRegisterBtn.setOnClickListener, the part of new View.OnClickListener appears in gray color, and it is not working when trying to test this code.
This image shows what I really mean. Please, perceive that the the part of new View.OnClickListener appears in gray color. It means a error. But trying to compile, this code runs, but the button simply does not work.
Can anyone know how to fix this error, please?
public class Register2 extends AppCompatActivity {
Button mRegisterBtn;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register2);
mRegisterBtn = findViewById(R.id.registerBtn);
mRegisterBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Testing", Toast.LENGTH_LONG).show();
}
});
}
}```
<?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"
android:background="#007FFF"
tools:context=".Register">
<Button
android:id="#+id/registerBtn"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:backgroundTint="#color/white"
android:text="Register"
android:textColor="#color/black"
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.499" />
</androidx.constraintlayout.widget.ConstraintLayout>
Try using the Activity itself as the Context.
If you want a log, then make one
If you want the gray to go away, use a lambda
Log.d("REGISTER", "Setting listener");
mRegisterBtn.setOnClickListener(view -> {
Log.d("REGISTER", "Clicked!");
Toast.makeText(Register2.this, "Testing", Toast.LENGTH_LONG).show();
});

How to change the gravity of a TextView in another xml file from Main Activity?

I have an XML file that has a TextView, and I want to change its gravity from the main activity.
I used this code in the main activity:
// I just coppied the related codes
TextView tvValue;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvValue = findViewById(R.id.tv_value);
// the tv_value id is from the (word_item.xml) file
}
private void OnClickFunc(View view) {
tvValue.setGravity(Gravity.RIGHT);
}
and the problem is that I get a NullPointerException error on a null object reference.
I know that I should somehow connect the xml file with the main activity.
word_item.xml file:
<?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="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<TextView
android:id="#+id/tv_value"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Word" />
</LinearLayout>
Thank you and I appreciate your help.
if you havent included the word_item.xml in your activity_main.xml then the error is obvious
so this is how you can include another file in any xml file in android
<include layout="#layout/word_item.xml" />
then things ll work as you expect
Try to first inflate the other layout as follows the initialize the view
LayoutInflater inflater = LayoutInflater.from(MainActivity.this); final View v = inflater.inflate(R.layout.word_item, null);
Then
Textview tvValue = findViewById(R.id.tv_value); private void OnClickFunc() { tvValue.setGravity(Gravity.RIGHT);
Where did you initialize textView variable?? Variable must be initialize after setContentView in OnCreate method in Activity.

getApplicationContext causes a NullPointerException

I just started trying to learn development in Android Studio, and while I was trying to make my first application work ( I'm also new to stackoverflow, so sry if the way I present this thread isn't satisfactory ), I ran into a brickwall of nullpointerexceptions.
I just wanted to make a button that displays a text message (toast) when I click on it.
It probably is a typical newbie mistake, but I just can't seem to find out what the problem is exactly. Can somebody enlighten me please?
The relevant part of the error message as far as I can tell is:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
Heres the code:
public class FirstActivity extends AppCompatActivity {
private static FirstActivity instance;
Context context = getApplicationContext();
CharSequence text = "A text that appears for a short time";
int duration = Toast.LENGTH_SHORT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
}
public void buttonclick(View view){
Toast toast1 = Toast.makeText(context,text,duration);
}
}
and the 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.rayaqin.myfirstandroidapp.FirstActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="259dp"
android:text="Press Me"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Me"
tools:layout_editor_absoluteX="-498dp"
tools:layout_editor_absoluteY="527dp"
android:onClick="buttonclick"/>
</android.support.constraint.ConstraintLayout>
getApplicationContext() is an instance method and you're trying to call it from a static context.
Simply move it to onCreate().
But Activity doesn't need application Context as itself it extends it. Use this in
Toast toast1 = Toast.makeText(this,text,duration);
and to show it
Toast.makeText(this,text,duration).show();
You should do that assignment in onCreate().
And use context = this;.
Just replace your toast with
Toast toast1 = Toast.makeText(this,text,duration).show();

Cannot Change Layout Content In Java Code

Very simple question but very weird as well :
I have a class PanelGlobalActivity that extends Activity and it is set to the layout panel_view_activity. I have a button and a text view, both have IDs.
When I do findViewById(R.id.*) it can see my button and my text view but there is no way I can change their values or anything. Like button.setText("Hello") would compile but wouldn't change it.
Any ideas ?
Here is my xml file (panel_view_activity):
<?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="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/text1"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
And here is my java class :
public class PanelGlobalActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.panel_view_activity);
TextView label = (TextView)findViewById(R.id.text1);
label.setText("Test");
}
}
Thanks.
Nic.
You can try something like this:
public class PanelGlobalActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button someButton = (Button) findViewById(R.id.yourButtonId);
someButton.setText("text changed");
}
}
some tips in coding if your using eclipse:
1.Use Ctrl + Shift + O (Imports necessary libraries or whatsoever automatically)
2.Use Ctrl + W (this lists all the possible methods for an object) just like when you're typing the "someButton.s" then press Ctrl + W, all available methods will be showed
You don't have any problem on your sample code ... I've run it it's perfectly fine . ..

android setContentView not working

Not a duplicate: my question is simpler than all of the others.
I've been trying to follow the android hello world tutorial, and I can't get the very first example to work.
This is my code:
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setText("Hello, Android");
setContentView(tv);
}
}
As you can see, I copied and pasted directly out of the tutorial.
The problem is, that instead of displaying Hello, Android, it displays whatever is in the layout/main.xml file. If that file doesn't exist, it closes without displaying anything.
WHY IS THIS NOT WORKING?
As I've copied this directly from the official docs, I have no idea where to even start trying to debug it. Any pointers or suggestions you can give will be greatly appreciated!
Edit: posting my main.xml as requested
<?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"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, HelloAndroid"
/>
</LinearLayout>
Note that this was created automatically when I started the project, I didn't put it there.
Why do you have two TextViews with the same text? You shouldn't be doing this, if you're only going to use one, then only use one.
You XML is fine as is, but your Activity code needs to change:
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
Heres an explanation of what you were doing...
You were building a TextView dynamically and setting the ContentView to that TextView is fine, but it was not your original intention. Your original intention or the original intention of the sample was to use the layout file and then set the contentview of that activity to that layout file, not just that textview.
Update
In lieu of what the OP said, he does want to build a TextView instance dynamically and apply it to the screen. If this is the case then you have to...:
public class HelloAndroid extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView tv = new TextView(this);
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.FILL_PARENT));
tv.setText("Hello, Android");
setContentView(tv);
}
}
The only difference here is that the TextView has properties that are defining how it will appear on the screen. You can either user FILL_PARENT or WRAP_CONTENT.
you haven't set the xml file or layout in your application. You are directly calling the view.You need to call your view under layout.
Syntax: setContentView(R.layout.your xml file name);
Regarding the question about logcat, you'll find it in the Debug perspective in Eclipse. It's the log of error messages from system and user code.
Try this: You don't need to do setContentView at end. If you do that, it will override with what you have in XML.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourxmlfile);
TextView tv = (TextView)findViewById(R.id.helloText);
tv.setText("Hello, Android");
}
<TextView
android:id="#+id/helloText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Hello World, HelloAndroid" />

Categories

Resources