Set ImageView based on user selection in settings android - java

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);
}
}
}

Related

Passing an Integer to a different activity to add to main score via textview (android studio)

This is my first project in Android studio. code is a little messy. Im creating a score keeping app for a card game I play with family members.
Im having a problem adding score to main activity from bid activity. how would you store the textview to continue to add to?
Score_activity java code:
public class score_activity extends AppCompatActivity {
// creating an object of the text view
TextView scoreA;
TextView scoreB;
TextView tvA;
TextView tvB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_score);
// assigning the outputs of the user to the object
scoreA = (TextView) findViewById(R.id.scoreA);
scoreB = (TextView) findViewById(R.id.scoreB);
tvA = (TextView) findViewById(R.id.nameA);
tvB = (TextView) findViewById(R.id.nameB);
Bundle bundle = getIntent().getExtras();
String text1 = bundle.getString("Team A");
String text2 = bundle.getString("Team B");
String text3 = getIntent().getStringExtra("ScoreA");
String text4 = getIntent().getStringExtra("ScoreB");
// setting the fetched data to the corresponding text views
tvA.setText(text1);
tvB.setText(text2);
scoreA.setText(text3);
scoreB.setText(text4);
// this method is the logic that increases the value in the text
view by one on every click for team A
}
Bid Activity code
public void scoreTotal(View view) {
String nameA = tvTeamA.getText().toString();
String nameB = tvTeamB.getText().toString();
int bida = Integer.parseInt(bidA.getText().toString());
int tricksTotalA =
Integer.parseInt(tricksA.getText().toString());
int totalB = 25 - tricksTotalA;
int totalScoreBA = mentionteamA + tricksTotalA;
int totalScoreBB = mentionteamB + totalB;
if (bida > totalScoreBA) {
scoreA2 = (bida * -1);
String scoreBoardA = String.valueOf(scoreA2);
String scoreBoardB = String.valueOf(totalScoreBB);
Intent i = new Intent(bid_activity.this,
score_activity.class);
i.putExtra("Team A", nameA);
i.putExtra("Team B", nameB);
i.putExtra("ScoreA", scoreBoardA);
i.putExtra("ScoreB", scoreBoardB);
// starting the activity
startActivity(i);
}
if (bida <= totalScoreBA) {
scoreA2 = totalScoreBA;
String scoreBoardA = String.valueOf(scoreA2);
String scoreBoardB = String.valueOf(totalScoreBB);
Intent i = new Intent(bid_activity.this,
score_activity.class);
i.putExtra("Team A", nameA);
i.putExtra("Team B", nameB);
i.putExtra("ScoreA", scoreBoardA);
i.putExtra("ScoreB", scoreBoardB);
// starting the activity
startActivity(i);
}
if (tricksTotalA == 25) {
scoreA2 = totalScoreBA;
int displayB = 0;
String scoreBoardA = String.valueOf(scoreA2);
String scoreBoardB = String.valueOf(displayB);
Intent i = new Intent(bid_activity.this,
score_activity.class);
i.putExtra("Team A", nameA);
i.putExtra("Team B", nameB);
i.putExtra("ScoreA", scoreBoardA);
i.putExtra("ScoreB", scoreBoardB);
// starting the activity
startActivity(i);
}
One idea is to call
startActivityForResult(i)
instead of
startActivity(i)
Then you can pass a result in BidActivity and capture it in ScoreActiivty's onActivityResult call.
I am just showing how to pass data from your bid activity to score activity.
bid activity
Intent i = new Intent(bid_activity.this, score_activity.class);
i.putExtra("ScoreA2", scoreA2);
i.putExtra("ScoreB2", scoreB2);
startActivity(intent);
score activity
int scoreA2 = getIntent().getIntExtra("ScoreA2");
int scoreB2 = getIntent().getIntExtra("scoreB2");
And for double click, you can follow this thread.

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;
}
}
}

Customize Image referred From Html string

One of my project activities including long text written in string.xml ,i add some images from resource within textview ,as after each phrase there is image then next the text phrase then image and so on ,
i getting that images from string using this code :
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView htmlTextView = (TextView) findViewById(R.id.day_tv);
htmlTextView.setText(Html.fromHtml(getString(R.string.day), new ImageGetter(), null));
}
private class ImageGetter implements Html.ImageGetter {
public Drawable getDrawable(String source) {
int id = 0;
if (source.equals("image1.jpg")) {
id = R.drawable.a;
} else if (source.equals("image2.jpg")) {
id = R.drawable.b;
} else if (source.equals("image3.jpg")) {
id = R.drawable.c;
} else if (source.equals("image4.jpg")) {
id = R.drawable.d;
} else if (source.equals("image5.jpg")) {
id = R.drawable.e;
}
Drawable d = getResources().getDrawable(id);
d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
return d;
}
};
}
and writing html img tag in string.xml as:
<img src="image1.jpg">
i want to be able to customize each image by changing its width and height or refer it to drawable style to add border around images for example .
i tried using the bellow code foe changing width and height :
<img src="image1.jpg" width="100" height="150">
but it doesn't work .
any advice to achieve that will be appreciated , thanks .
I finally end up to this solution which allow to change width and height for each image but still one point not achieved which is referring image to drawable shape as background ,
still work on it :
private class ImageGetter implements Html.ImageGetter {
public Drawable getDrawable(String source) {
int id,id1,id2,id3,id4 = 0;
if (source.equals("image1.jpg")) {
id = R.drawable.a;
Drawable d = getResources().getDrawable(id);
d.setBounds(0, 0, 80, 20);
return d;
}
else if (source.equals("image2.jpg")) {
id1 = R.drawable.b;
Drawable d1 = getResources().getDrawable(id1);
d1.setBounds(0, 0, 100, 40);
return d1;
}
else if (source.equals("image3.jpg")) {
id2 = R.drawable.c;
Drawable d2 = getResources().getDrawable(id2);
d2.setBounds(0, 0, 120, 60);
return d2;
}
else if (source.equals("image4.jpg")) {
id3 = R.drawable.d;
Drawable d3 = getResources().getDrawable(id3);
d3.setBounds(0, 0, 140, 80);
return d3;
}
else if (source.equals("image5.jpg")) {
id4 = R.drawable.e;
Drawable d4 = getResources().getDrawable(id4);
d4.setBounds(0, 0, 160, 100);
return d4;
}
return null;
};
}
}
The problem comes from Html.fromHtml(), which supports only a very limited set of tags and attributes. <img> is supported, but setting the width and height of the image is not. It's possible to achieve it with a TextView (by using SpannableString and ImageSpan), but it's more complicated and not very flexible.
Instead, you should use a WebView which handles HTML properly.
It's easy to load a string :
WebView webView = (WebView) findViewById(R.id.web_view);
webView.loadData(getResources(R.string.day), "text/html", null);
You can find more examples in the documentation.
Just for comparison, here is an example without using a WebView :
protected void onCreate(Bundle savedInstanceState) {
...
TextView textView = (TextView) findViewById(R.id.text_view);
SpannableString ss = new SpannableString("Hello :)");
// Draw the image with a size of 50x50
Drawable d = getResources().getDrawable(R.drawable.happy_face);
d.setBounds(0, 0, 50, 50);
// Replace the ":)" in the string by our drawable
ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BASELINE);
ss.setSpan(span, 6, 8, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
textView.setText(ss);
}
It will load much faster, but you can't use HTML.

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).

set ImageView depending on case

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

Categories