Set image resource in onCreate method - android

Is it possible to set image resource in onCreate method before loading layout.
For example:
On main layout I have images instead of buttons, so there is no button "Play", instead there is an image on which "Play" is drawn.
But, on other hand, user can change languages, so if user choses German there has to be different image on main layout.
I know how to change picture on some event, but is it possible to do it in onCreate method.
Logic would probably be something like:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences options= PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
String language= options.getString("language", "en");
setLocal(language);
setContentView(R.layout.activity_main);
ImageView play= (ImageView)findViewById(R.id.play);
if(language=="en")
play.setImageResource(R.drawable.play_en);
else if(language=="de")
play.setImageResource(R.drawable.play_de);
}
Of course, this doesn't change the picture because image is already loaded, but I hope you get what I want to achieve.

What you wan't to do can be done using localization on your resources, I think this is te correct and easily way to do it.
You can check how, here: http://developer.android.com/guide/topics/resources/localization.html

Related

Saving whole instance of an activity

Is there any simple way to save the whole activity instance and restoring it ?
After spending 1 hour of searching all corners of internet, I ended up here. I still don't know how to make this.
Yes, I know how to save current instance using onSaveInstanceState and onRestoreInstanceState
but no one in the internet explained it with a large complex coding like dynamically created views, many textviews and calculations,etc. Everyone explaining this with only one or two textViews and I was like "How someone can create an app with only few TextViews!?!" like below:
onSaveInstanceState()
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.i(TAG, "onSaveInstanceState");
final EditText textBox =
(EditText) findViewById(R.id.editText);
CharSequence userText = textBox.getText();
outState.putCharSequence("savedText", userText);
}
onRestoreInstanceState()
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.i(TAG, "onRestoreInstanceState");
final EditText textBox =
(EditText) findViewById(R.id.editText);
CharSequence userText =
savedInstanceState.getCharSequence("savedText");
textBox.setText(userText);
}
I can totally understand this above method. But What to do if we complete a quite complicated coding and want to save & restore the state I have completed all my complex coding stuff and landed in this problem.
I'm sure there will be a simple way to achieve this. Please understand my problem. Help me.
If I understand correctly, you want to save the current state of the page even the page changes, if this is the case, it can be solved by data binding as follows:
1.enable data binding in Gradle
2. in XML file put your layout into layout tag
<layout>
...// your activity view layout
</layout>
then define it in your activity :
private lateinit var binding: FragmentNameBinding
4.add this expression in onCreate or onCreateView(for fragment)
if (!(::binding.isInitialized)) {
//initialize you layout file and what ever you want
}
//then initialize what you want to not change after the layout
changed and back to it

How to show two images one by one in android?

I am developing an app in which i have two images namely "a" and "b" when user open activity i want to show image "a" and second time when user again open activity want to show image"b" same for 3 4 5 6. I have tried a lot and also googled but can't found any solution.
Below code will help you.
Create a Shared Preferences for store the value of index.Every time Activity will create index will increment and accordingly image would change.
public class ImageShow extends Activity{
Integer image[]={R.drawable.icon,R.drawable.ic_launcher,R.drawable.icon_audio};
int index=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
SharedPreferences sharedpreferences=this.getSharedPreferences("imagevalue", 0);
index=sharedpreferences.getInt("key", 0);
ImageView imv=new ImageView(this);
imv.setImageResource(image[index]);
Editor editor = sharedpreferences.edit();
editor.putInt("key", ++index);
editor.commit();
}
}
for this first you should put your images in your Drawble or assets folder after that you can show images in imageview and save its name in sharedpreferences as string...when user again open this activity you should check the sharedpreferences to find that which images seen with user and according that data decide to show next image to user...

EditText not automatically saved on screen orientation change

I read that Android automatically saves the content of EditText objects when an application is about to be stopped or killed. However, in my app the content of an EditText is lost when screen orientation changes.
Is it normal behaviour? Do I then have to manually save/restore its content with onSaveInstanceState/onRestoreInstanceState? Or is there an easier method to tell Android to save it end restore it?
Edit:
I create the EditText object programmatically, not in XML. This turns out to be related to the problem (see accepted answer below).
This is not normal behavior.
First and foremost, ensure that you have IDs assigned to your EditText controls in the layout XML.
Edit 1: It just needs an ID, period. If you're doing this programmatically, it will lose state unless it has an ID.
So using this as a quick & dirty example:
// Find my layout
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.ll1);
// Add a new EditText with default text of "test"
EditText testText = new EditText(this.getApplicationContext());
testText.setText("test");
// This line is the key; without it, any additional text changes will
// be lost on rotation. Try it with and without the setId, text will revert
// to just "test" when you rotate.
testText.setId(100);
// Add your new EditText to the view.
mLinearLayout.addView(testText);
That will solve your problem.
Should that fail, you'll need to save and restore state yourself.
Override onSaveInstanceState like so:
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString("textKey", mEditText.getText().toString());
}
And then restore in OnCreate:
public void onCreate(Bundle savedInstanceState) {
if(savedInstanceState != null)
{
mEditText.setText(savedInstanceState.getString("textKey"));
}
}
Also, please don't use android:configChanges="orientation" to try to accomplish this, it's the wrong way to go.
could you use android:freezesText="true" in the xml layout?
The easiest way I found to save an object on onSaveInstanceState is to implement serializable and put in bundle
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putSerializable("myObj", myObj);
}
where myObj class implements serializable and in onCreate() method
if (savedInstanceState != null && savedInstanceState.getSerializable("myObj") != null) {
myObj = ((MyObj) savedInstanceState.getSerializable("myObj"));
}
One possible cause is that you override onSaveInstanceState but you forget to call the same for super class
super.onSaveInstanceState(outState);
State of all views in activity is auto saved UNLESS you override this functionality. Even if this is obvious, mistakes are possible.
You just need UNIQUE ID for the edit text. Make sure if you dynamically add edit text, chances of having same id can cause not restoring the text.
Same way if you add in xml, use unique id. Hope it will help someone.
FYI: EditText by default having setFreezesText as true

Changing default xml image on application load

I have an android application that displays, by default, a series of ImageButtons using xml. The user changes the image based on their input. I am trying to display the changed ImageButtons the next time the user loads the app.
Example:
ImageButton starts as Android.png (loaded from default xml page)
User enters text
ImageButton is changed to Correct.png
The next time that the app loads I want Correct.png to display instead of Android.png. Is there a way to iterate through the ImageButtons before the app starts (the buttons are NOT created programatically) to set the source value for each one before the application loads?
You can use findViewById(R.id.button_1) for each button and set it as needed. You'll then need to store which values it should have so that you can load these values and set the ImageButton source for each one. You can store it with either SharedPreferences or a SQLite database, depending on how much you have to change.
So, for example:
ImageButton b = (ImageButton)findViewById(R.id.button_1);
b.setImageDrawable(drawable);
You can load a drawable up for the checkbox so that you do it only once, which is more efficient, or you could setImageResource to R.drawable.correct, which would be a bit slower since I assume that the checkbox would probably be set for multiple images.
A better way to perform this by using SharedPreferences.
SharedPreferences sharedPref = getSharedPreferences("userpref", Activity.MODE_PRIVATE);
String image = pref.getString("userchoice","no-image");
if(image.equeals("no-image")
{
imageView.setBackgroundResource(R.drawable.android);
}
else
{
//compare here your image
imageView.setBackgroundResource(R.drawable.Correct);
}
And whenever user selects any other image, just edit your preference file by using following code.
SharedPreferences.Editor editor = pref.edit();
editor.putString("userchoice","Correct.png");

"Force Close" Error on declaring TextView and ToggleButton

Well basicly I have a textview and when the application is created it sets a string as the textviews text not hard, but I get a force close error when I run the app on my phone.
TextView sdcard=(TextView)findViewById(R.id.sd_textview);
sdcard.setText(R.string.not_mounted);
Then I have a error on a togglebutton also
ToggleButton silent=(ToggleButton)findViewById(R.id.silentbutton);
silent.setChecked(false);
And I have errors for all my other buttons/textviews can anyone help, please?!
EDIT:
I cant post pics because I am a new member, :(
Link to imgshack http://imageshack.us/photo/my-images/849/unledggp.png/
If code for the whole textview snippet.
if (android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_UNMOUNTED)) {
TextView sdcard=(TextView)findViewById(R.id.sd_textview);
sdcard.setText(R.string.not_mounted);
}
OnCreate Function
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
checkSD();
checkRing();
checkWifi();
checkBt();
}
Look for all instances of sd_textview and make sure the one that you're trying to reference is a TextView. If you want more clarity you can debug your code and see what object is actually being returned by not casting into a TextView:
View sdcard = findViewById(R.id.sd_textview); //debug this
//you can also log the View object to see the type
Log.d("Test", "" + sdcard);
Looking at your error log (assuming its the right error log) you have a ClassCastException in the checkWifi method. Edit your question and include ALL of the onCreate method and all of the checkWifi method, but I expect you are using the same id for multiple views.
Two things I can think of (although seeing more code would help).
Make sure you have called setContentView(R.layout.main) (or whatever your layout file is called). Do this BEFORE any attempt to use findViewById(...).
Secondly sdcard.setText(R.string.not_mounted); in this statement R.string.not_mounted is a resource ID (int) and not a string. You would need to use...
sdcard.setText(getString(R.string.not_mounted));

Categories

Resources