set ImageView depending on case - java

i have been looking for a while and could not find a solution for my problem. I am trying to set an imageView depending on the User logged in. The main problem is how do i rename R.drawable.stock into R.drawable.user1where the name of the imageView varies with the name of the user. I tried setting it to a string like String temp="R.drawable."+userNameStore; but did not have luck.
Here is what i am doing:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
SharedPreferences app_preferences =
PreferenceManager.getDefaultSharedPreferences(this);
String userNameStore =
app_preferences.getString("userNameStore", null);
String temp="R.drawable."+userNameStore;
TextView textName=(TextView) findViewById(R.id.username);
textName.setText("Username: "+ userNameStore);
ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setImageResource(temp);
}

I use 2 methods in my utility class for this:
public static int getImageId(Context context, String imageName) {
return context.getResources().getIdentifier("drawable/" + imageName, null, context.getPackageName());
}
public static int getRawResourceId(Context context, String rawName) {
return context.getResources().getIdentifier("raw/" + rawName, null, context.getPackageName());
}
So if you have an image resource in your drawable folder named user1, you could get and use its ID like this:
imageView.setImageResource(getImageId(this, "user1"));

You can use getIdentier, for example:
getResources().getIdentifier("star_off", "string", getPackageName());
Check the documentation here
In your case it should be something like:
int resID = getResources().getIdentifier(temp, "drawable", getPackageName());
...
image.setImageResource(resID);

You can construct your string identifier like this...
int id = getResources().getIdentifier("name_of_resource", "id", getPackageName());
It's covered here

Related

Different Behaviors of Activity when Opened from two Different Activities in Android

Before I asked this question I really looked at different answers on StackOwerflow for days, but I couldn't find an answer.
This is my what I am doing - I have an app that has UserProfileActivity, which I want to be able to open from 2 different activities - from myContactsListActivity and from messageActivity. Data I want sent in my UserProfileActivity contains userId, userName, profilePhooto, and aboutUser.
In the first case I want to pass this data via intent from myContactsListActivity, and in the second I want to pass only userId from myContactsListActivity and make a call to get data from the server.
This is how I do it right now. When it is open from myContactsListActivity, I use intents to pass the data to UserProfileActivity, and pass only userId from messageActivity, and use if else to determine what intent is called.
In short: Activity A can be opened from activity B and C. I need two different behaviors. If it is opened form B everything is passed via intent, and if it is opened from C only userId is passed and there is a call to server. How would I determine from which activity was opened, and what is the best way to set different behaviors.
Here is my code, IT WORKS, but I am not happy with it, and I am looking for a better solution:
TextView textViewUserName, textViewAbout;
ImageView imageView;
Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_profile);
Intent intent = getIntent();
final String userId = intent.getStringExtra("userId");
String userName = intent.getStringExtra("userName");
String about = intent.getStringExtra("about");
String image = intent.getStringExtra("image");
toolbar = (Toolbar) findViewById(R.id.toolbar);
if (toolbar != null) {
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
}
textViewUserName = (TextView) findViewById(R.id.contactUsername);
textViewAbout = (TextView) findViewById(R.id.aboutMe);
ColorGenerator generator = ColorGenerator.MATERIAL;
final int color = generator.getColor(userId);
TextDrawable.IBuilder builder = TextDrawable.builder()
.beginConfig()
.withBorder(1)
.endConfig()
.rect();
if (userName != null) {
String firstLetter = intent.getStringExtra("userName").substring(0, 1);
TextDrawable textDrawable = TextDrawable.builder().buildRect(firstLetter, color);
imageView = (ImageView) findViewById(R.id.profile_image);
imageView.setImageDrawable(textDrawable);
Picasso.with(this)
.load("http://192.168.0.13/mynewapp/profilephotos/" + image)
.placeholder(textDrawable)
.error(textDrawable)
.centerCrop()
.fit()
.into(imageView);
getSupportActionBar().setTitle(userName);
Intent commentDescriptionIntent = new Intent(this, AboutFragment.class);
commentDescriptionIntent.putExtra("userId", userId);
commentDescriptionIntent.putExtra("userName", userName);
commentDescriptionIntent.putExtra("about", about);
setIntent(commentDescriptionIntent);
} else {
ApiInterface apiService =
ApiClient.getClient().create(ApiInterface.class);
Call<ContactResponse> call = apiService.userExists(userId);
call.enqueue(new Callback<ContactResponse>() {
#Override
public void onResponse(Call<ContactResponse> call, retrofit2.Response<ContactResponse> response) {
Contact contact = response.body().getResults();
String firstLetter = contact.getUserName().substring(0, 1);
TextDrawable textDrawable = TextDrawable.builder().buildRect(firstLetter, color);
imageView = (ImageView) findViewById(R.id.profile_image);
imageView.setImageDrawable(textDrawable);
Picasso.with(getApplicationContext())
.load("http://localhost/mynewapp/profilephotos/" + contact.getThumbnailUrl())
.placeholder(textDrawable)
.error(textDrawable)
.centerCrop()
.fit()
.into(imageView);
CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.collapsing_toolbar);
String userName = contact.getUserName();
collapsingToolbarLayout.setTitle(userName);
}
#Override
public void onFailure(Call<ContactResponse> call, Throwable t) {
// Log error here since request failed
Log.e(TAG, t.toString());
}
});
}
Try using an another extra value with your Intent.
For example:
From ActivityB:
Intent intent = new Intent(ActivityB.this, ActivityA.class);
intent.putExtra("FROM_ACTIVITY", "B");
// Others extra values
startActivity(intent);
From ActivityC:
Intent intent = new Intent(ActivityC.this, ActivityA.class);
intent.putExtra("FROM_ACTIVITY", "C");
// Others extra values
startActivity(intent);
Do this in your ActivityA:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_profile);
String fromActivity = getIntent().getStringExtra("FROM_ACTIVITY");
if(fromActivity.equals("B")) {
// Do something
} else if(fromActivity.equals("C")) {
// Do something
}
}
Hope this will help~
This is how I would go on doing this, We can use fragments to load on activities, depending on the different state of the activity,
So you can have 2 different fragments. Will probably load the same UI/xml view, But behave differently, One just set the values coming from the intent. and Other loading stuff from an external api.
Note:
Try to use a loader to load stuff from an external api. that has its own call backs that you can use to load data after they are being received.
This is more of a high level idea, Let me know if you have any further questions

Random background in Android

I'm a beginner on Android Studio, and java, i want to create a random background of view images, i try to use this How To Display Random images on image view , but not working, this code doesn't generate any image
Please, can someone help me to resolve this code or to create another code to random background.
I use this code to generate images
final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.rnd_images);
final ImageView img = (ImageView) findViewById(R.id.imgRandom);
// I have 3 images named img_0 to img_2, so...
final String str = "img_" + rnd.nextInt(2);
img.setImageDrawable
(
getResources().getDrawable(getResourceID(str, "drawable",
getApplicationContext()))
);
}
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
}

How do I randomize images in android studio? The code I wrote isn't working

I want to randomize the the back images that will be brought from a database(code still not added), but the code I wrote isn't working. I have originally just added the flip function. I searched up how to randomize images and tried to follow the code given. Sadly its not working for me.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get references to the imageView objects
imgUpperLeft = (ImageView) findViewById(R.id.imgUpperLeft);
imgUpperRight = (ImageView) findViewById(R.id.imageView2);
imgLowerLeft = (ImageView) findViewById(R.id.imageView3);
imgLowerRight = (ImageView) findViewById(R.id.imageView4);
// Setting the initial image (First face of cards)
imgUpperLeft.setImageResource(R.drawable.img_waterfall);
imgUpperRight.setImageResource(R.drawable.img_waterfall);
imgLowerLeft.setImageResource(R.drawable.img_waterfall);
imgLowerRight.setImageResource(R.drawable.img_waterfall);
imgUpperLeft.setVisibility(View.VISIBLE);
imgUpperRight.setVisibility(View.VISIBLE);
imgLowerLeft.setVisibility(View.VISIBLE);
imgLowerRight.setVisibility(View.VISIBLE);
}
ImageView imgView = new ImageView(this);
Random rand = new Random();
int rndInt = rand.nextInt(4) + 1; // n = the number of images, that start at idx 1
String imgName = "img" + rndInt;
int id = getResources().getIdentifier(imgName, "drawable", getPackageName());
// Shows the second face of the cards
public void showUpperLeftImage(View v){
imgView.setImageResource(id);
}
public void showUpperRightImage(View v){
imgView.setImageResource(id);
}
public void showLowerLeftImage(View v){
imgView.setImageResource(id);
}
public void showLowerRightImage(View v){
imgView.setImageResource(id);
}
Two things in your code stand out to me:
ImageView imgView = new ImageView(this);
This ImageView is not part of the view hierarchy, meaning it is not on screen. Was it ever meant to be on screen? If not, then I don't think you need this.
public void showUpperLeftImage(View v){
imgView.setImageResource(id);
}
You have four methods like this one that change the image of the view that is not on screen. Judging by their method names, I think you want to change the image of the four ImageViews you found earlier with findViewById().
I think you want to do this:
public void showUpperLeftImage(int id) {
imgUpperLeft.setImageResource(id);
}
public void showUpperRightImage(int id) {
imgUpperRight.setImageResource(id);
}
public void showLowerLeftImage(int id) {
imgLowerLeft.setImageResource(id);
}
public void showLowerRightImage(int id) {
imgLowerRight.setImageResource(id);
}

Set ImageView based on user selection in settings android

I am attemping to make an app that would change a Image based on a users selection of a ListPreference in the settings of my application. There are two pictures, a forest,and an Ocean. When Ocean is selected the value sent to the string is 1, and 2 for the forest, but when I run this code it throws an error saying "Source not found." Any siggestions?
public void showUserSettings() {
String name;
String pic;
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
name = sharedPrefs.getString("your_name", "NULL");
pic = sharedPrefs.getString("pic_what", "for");
int whatPic = Integer.parseInt(pic);
TextView tvName = (TextView) findViewById(R.id.tvName);
tvName.setText(name);
if(whatPic==1) {
ImageView img = (ImageView) findViewById(R.id.iView);
img.setImageResource(R.drawable.ocean);
}else if(whatPic==2); {
ImageView img = (ImageView) findViewById(R.id.iView);
img.setImageResource(R.drawable.forest);
}
}
}

Android, How to pass the name of int variable to a popupwindow?

How can I pass the name of an int variable to a popupwindow when an image is clicked? I have set an int per image and I have a lot of images that I had set.
This is how I'm using the int in a textView on a PopupWindow.
public boolean onLongClick(View v) {
// v.setTag(v);
case R.id.hsv1iv1:
ImageView ivpopup = (ImageView) popupView.findViewById(R.id.pv1);
intcount1++; // I would like to pass this int name to the popup window.
break;
case R.id.hsv2iv1:
ImageView ivpopup = (ImageView) popupView.findViewById(R.id.pv1);
intcount2++; // I would like to pass this int name to the popup window.
break;
LayoutInflater layoutInflater
= (LayoutInflater)getBaseContext()
.getSystemService(LAYOUT_INFLATER_SERVICE);
View popupView = layoutInflater.inflate(R.layout.popup, null);
final PopupWindow popupWindow = new PopupWindow(
popupView,
LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT);
popupWindow.update(0, 0, 800, 500);
ColorDrawable dw = new ColorDrawable(-005500);
popupWindow.setBackgroundDrawable(dw);
tvpwlikectr = (TextView) popupView.findViewById(R.id.liketv);
Button pwlikebtn = (Button) popupView.findViewById(R.id.pwlikebtn);
Button btnDismiss = (Button)popupView.findViewById(R.id.cancel);
pwlikebtn.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
intcount1++;
tvpwlikectr.setText(Integer.toString(intcount1)); // this code doesn't work with the intcount1
}});
btnDismiss.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
popupWindow.dismiss();
popupWindow.setTouchable(true);
popupWindow.setFocusable(true);
popupWindow.setOutsideTouchable(true);
}
}
Could you explain how you are setting the INT per image? Copying and pasting the code on how you set an INT per image would be helpful, because it's unclear what you mean by you are setting an INT per image.
Also, are you interested in the value of the int variable or the name of the variable? Showing how you are settings lots of images with int per image would help clarify what you are trying to do.
-- adding answer after seeing the updated post with code --
I would create an object that has the name you are interested in (i.e. intcount1) and an int to keep the actual value. After that, you can associate each button/ImaveView with that object with the view.setTag method, and get the value via view.getTag method. Here's an example:
private class MyTag {
String mTagName;
int mCount;
MyTag(String tagName) {
mTagName = tagName;
mCount = 0;
}
}
// in your onCreate or initializaion code somewhere
ImageView view1 = (ImageView) popupView.findViewById(R.id.hsv1iv1);
MyTag imageTag = new MyTag("intcount1");
view1.setTag(imageTag);
ImageView view2 = (ImageView) popupView.findViewById(R.id.hsv1iv1);
// this will go wherever you handle the onLongClick
public boolean onLongClick(View v) {
Object tag = v.getTag();
if (tag instanceof MyTag) {
MyTag myTag = (MyTag) tag;
myTag.mCount++;
}
}
// I'm assuming you are setting the text from the actual clicked object
// so this will go wherever you are setting the text/handling the click
public void onClick(View v) {
Object tag = v.getTag();
if (tag instanceof MyTag) {
MyTag myTag = (MyTag) tag;
myTag.mCount++;
tvpwlikectr.setText(myTag.mTagName);
}
}
The bottom line is, creating an object with name/count value, associate each View with its own object using the view.setTag() function, and when you need to read the values, use the view.getTag() to get the object and read the mTagName (the "variable" name) and the mCount (the "variable" value).

Categories