How to change background colour of an Android activity - java

I want to change the background colour of an activity using AlertDialog. Here is what I have done:
private SharedPreferences prefs;
private static final String SELECTED_ITEM = "SelectedItem";
private Editor sharedPrefEditor;
btnchangeColor = (ImageButton) findViewById(R.id.btnchangeColor);
btnchangeColor.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final CharSequence[] items={"Red","Green","Blue", "Yellow", "#EE82EE"};
AlertDialog.Builder builder = new AlertDialog.Builder(
ContentView_2.this);
builder.setTitle("Pick a Color");
builder.setPositiveButton("ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {}
});
builder.setSingleChoiceItems(items, getSelectedItem(), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
wvContent = (WebView) findViewById(R.id.wvContent);
//LinearLayout ll=(LinearLayout)findViewById(R.id.wvContent);
if("Red".equals(items[which]))
{
wvContent.setBackgroundColor(Color.RED);
}
else if("Green".equals(items[which]))
{
wvContent.setBackgroundColor(Color.GREEN);
}
else if("Blue".equals(items[which]))
{
wvContent.setBackgroundColor(Color.BLUE);
}
else if("Yellow".equals(items[which]))
{
wvContent.setBackgroundColor(Color.YELLOW);
}
else if("#EE82EE".equals(items[which]))
{
wvContent.setBackgroundColor(Color.rgb(184,184,184));
}
saveSelectedItem(which);
}
});
builder.show();
}});
}
private int getSelectedItem() {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
return prefs.getInt(SELECTED_ITEM, -1);
}
private void saveSelectedItem(int which) {
if (prefs == null) {
prefs = PreferenceManager
.getDefaultSharedPreferences(this);
}
sharedPrefEditor = prefs.edit();
sharedPrefEditor.putInt(SELECTED_ITEM, which);
sharedPrefEditor.commit();
}
I also add this code to OnCreate:
wvContent = (WebView) findViewById(R.id.wvContent);
wvContent.setBackgroundColor(getSelectedItem());
The colour is selected and the web view (wvContent) changes to chosen colour, BUT this is not saved to and/or loaded from Shared Preferences. It returns to its default colour when the activity is relaunched.
So the question is: How can properly I save the selected colour to SharedPreferences and load it when activity relaunches?
Many thanks for help.

Currently you are saving position of selected item instead of color code in SharedPreferences. do it as:
wvContent = (WebView) findViewById(R.id.wvContent);
int bg_color=Color.TRANSPARENT;
if("Red".equals(items[which]))
{
wvContent.setBackgroundColor(Color.RED);
bg_color=Color.RED;
}
else if("Green".equals(items[which]))
{
wvContent.setBackgroundColor(Color.GREEN);
bg_color=Color.GREEN;
}
........
// save color in SharedPreferences
saveSelectedItem(bg_color);
Now getSelectedItem() method return color code for previously selected value from spinner.

Related

Shared Preferences ImageView

I'm working in android studios and I have this app that displays an imageView and has seekbars that allow you to edit the RGB values of the photo, but when I rotate from portrait to landscape (or vice versa) the imageView doesnt save and goes back to the original imageView and not the one that I selected. The Seekbars keep their values though. Any ideas on how I can used shared preferences to save the image? Thanks
public class MainActivity extends AppCompatActivity {
////////////////////////////////////////////////////////////////////////////
TextView textTitle;
ImageView image;
SeekBar barR, barG, barB, barAlpha;
int ColorValues;
private static final int SELECT_PHOTO = 100;
private static final int CAMERA_PIC_REQUEST = 101;
private static final String PREFS_NAME = "PrefsFile";
private static final String COLOR_VALUES = "ColorVals";
private static final String PICTURE = "Picture";
///////////////////////////////////////////////////////////////////////////
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textTitle = (TextView)findViewById(R.id.title);
image = (ImageView)findViewById(R.id.image);
barR = (SeekBar)findViewById(R.id.red);
barG = (SeekBar)findViewById(R.id.green);
barB = (SeekBar)findViewById(R.id.blue);
barAlpha = (SeekBar)findViewById(R.id.alpha);
barR.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
barG.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
barB.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
barAlpha.setOnSeekBarChangeListener(myOnSeekBarChangeListener);
//default color
ColorValues = barAlpha.getProgress() * 0x1000000
+ barR.getProgress() * 0x10000
+ barG.getProgress() * 0x100
+ barB.getProgress();
image.setColorFilter(ColorValues, Mode.MULTIPLY);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
ColorValues = settings.getInt(COLOR_VALUES, ColorValues);
}
//menu/////////////////
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.savePicture:
Bitmap bitmap = ((BitmapDrawable)image.getDrawable()).getBitmap();
MediaStore.Images.Media.insertImage
(getContentResolver(), bitmap, "yourTitle", "yourDescription");
}
return true;
}
//on click function////////////////
public void selectPicture(View view) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}
public void takePicture(View view){
try{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
} catch(Exception e){
e.printStackTrace();
}
}
//activity///////////////
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
Uri selectedImage = data.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
image.setImageURI(selectedImage);// To display selected image in image view
break;
}
case CAMERA_PIC_REQUEST:
try {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
thumbnail = Bitmap.createScaledBitmap(thumbnail, 700, 500, true);
ImageView imageView = (ImageView) findViewById(R.id.image);
image.setImageBitmap(thumbnail);
} catch (Exception ee) {
ee.printStackTrace();
}
break;
}
}
//warning before exit
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Closing Activity")
.setMessage("Are you sure you want to close\nthis activity? \n\nProgress will NOT be saved ")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null);
AlertDialog dialog = builder.show();
TextView messageText = (TextView)dialog.findViewById(android.R.id.message);
messageText.setGravity(Gravity.CENTER);
dialog.show();
}
//edit picture
OnSeekBarChangeListener myOnSeekBarChangeListener = new OnSeekBarChangeListener(){
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
//Colorize ImageView
int newColor = barAlpha.getProgress() * 0x1000000
+ barR.getProgress() * 0x10000
+ barG.getProgress() * 0x100
+ barB.getProgress();
image.setColorFilter(newColor, Mode.MULTIPLY);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
ColorValues = newColor;
editor.putInt(COLOR_VALUES, ColorValues);
// Commit the edits
editor.commit();
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {}
};
#Override
protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
icicle.putInt(COLOR_VALUES, ColorValues);
}
this is what it would look like if I saved the colorvalues(which are somehow already being saved without this code)
if (savedInstanceState != null) {
colorvalues = savedInstanceState.getInt("COLOR_VALUES");
image = savedInstanceState.get??????????????????????
}
image is not an Int so what values should be put there?
also to get the exact RGB values like RBar = savedInstanceState.getInt doesnt works becuase Rbar is a seekbar not an int???

Save Dialog Input

I have some buttons in my application, which open up a dialog when clicked on them.
In those dialogs a user can fill in his homework in an edittext.
Anyway i would like to save that user input, so that if I close the dialogs or the application I am able to recall that data and because I am new to eclipse and programming i don't know how to do it.
This is my MainActivity
public class MainActivity extends ActionBarActivity {
protected static final String TAG = null;
private Button bthomeWork;
private Button bthomeWork1;
private Button bthomeWork2;
private Button bthomeWork3;
private Button bthomeWork4;
private AlertDialog.Builder dialogbuilder;
private String strName="";
private void homeworkdialog(){
dialogbuilder = new AlertDialog.Builder(this);
final EditText txtinput = new EditText(this);
dialogbuilder.setTitle("Homework");
dialogbuilder.setMessage("Was sind deine Hausaufgaben?");
dialogbuilder.setView(txtinput);
dialogbuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#SuppressLint("ShowToast") #Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
strName+= txtinput;
Toast.makeText(getApplicationContext(), "Eingetragen", Toast.LENGTH_SHORT);
}
});
dialogbuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#SuppressLint("ShowToast") #Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Kein Eintrag", Toast.LENGTH_SHORT);
}
});
dialogbuilder.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
bthomeWork = (Button)findViewById(R.id.bthomeWork);
bthomeWork1= (Button)findViewById(R.id.bthomeWork1);
bthomeWork2= (Button)findViewById(R.id.bthomeWork2);
bthomeWork3= (Button)findViewById(R.id.bthomeWork3);
bthomeWork4= (Button)findViewById(R.id.bthomeWork4);
bthomeWork.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
homeworkdialog();
}
});
bthomeWork1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
homeworkdialog();
}
});
Hope you can help me:)
You can get the text and save the value of the editText into a String
String MyText = txtinput.getText().toString();
Then you can save the value either using sharedPreferences or into your Database depending on what you want to do
you can save the value in shared preferences like this
SharedPreferences sp = getSharedPreferences("key", 0);
SharedPreferences.Editor sedt = sp.edit();
sedt.putString("textvalue", txtInput.getText().toString());
sedt.commit();
Then you can retrieve the saved text in another activity or anywhere in your project like this
SharedPreferences sp = getSharedPreferences("key", 0);
String textValue = sp.getString("textvalue","");
for more information about using shared preferences check out this link http://www.tutorialspoint.com/android/android_shared_preferences.htm
And also note that sharedpreferences are stored as simple xml values...so anyone with a rooted android phone can easily have accesss to the saved value...so if you want to keep the data safe you can check out ways of keeping data safe in android programming http://www.androidsnippets.com/encryptdecrypt-strings

Custom Dialog with game score android

I've got a huge problem. When I had AlertBox everything was OK, but I would change it to custom dialog box with pretty good graphic.
With AlertBox it was displaying the current scores and highscore.
When I changed it to Custom Dialog box it's showing nothing.
CustomDialogClass.java
public class CustomDialogClass extends Dialog
{
public CustomDialogClass(Context context) {
super(context);
// TODO Auto-generated constructor stub
/** It will hide the title */
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_dialog);
}
}
GameActivity.java (fragments with custom dialog box)
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
surfaceCreated = false;
stopDrawingThread();
}
public void customizeDialog() {
int highest = PrefUtil.getHighestScore(this);
String text = null;
if (currentPoint > highest) {
highest = currentPoint;
PrefUtil.setHighestScore(this, currentPoint);
} else {
}
text = "Current Points: " + currentPoint + "\nThe Best Score: " + highest;
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Game Over");
builder.setMessage(text);
builder.setPositiveButton("Try Again", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
playSwooshing();
restart();
}
});
builder.setNegativeButton("Exit Game", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(GameActivity.this,Bye.class);
startActivity(intent);
playSwooshing();
finish();
}
});
builder.setCancelable(false);
alertDialog = builder.show();
}
and the other fragment:
private void onGameOver() {
runOnUiThread(new Runnable() {
#Override
public void run() {
if (!isFinishing()) {
soundPool.play(soundIds[SOUND_DIE], 0.5f, 0.5f, 1, 0, 1);
CustomDialogClass customizeDialog = new CustomDialogClass(GameActivity.this);
customizeDialog.show(); }
}
});
}
Where is a problem? Can someone fix it?
Now it's showing only my layout file, without any data.
Thanks!
It's not displaying your data because you're not setting your data. In your middle code fragment where you're creating your dialog using a Builder you're not using your custom dialog, so apparently that code is no longer being called. Likewise in your last fragment where you do create a custom dialog, you're not setting any the data.
See the documentation:
If you want a custom layout in a dialog, create a layout and add it to an AlertDialog by calling setView() on your AlertDialog.Builder object.
By default, the custom layout fills the dialog window, but you can still use AlertDialog.Builder methods to add buttons and a title.

My code seems to be sound but any time I click the submit button it does nothing

Alright I am comparing the text that the user has input to the edittext and comparing to the answer that is there in the String.xml. The code seems completely sounds and error-less but it doesn't work at all. Any help would be appreciated.
package com.example.italianapp;
public class Pictures<sButton> extends MainActivity
{
int level=0; // integer that will keep track of users progress
Button sButton; // represents the submit button
EditText mEdit; // text area where the user types answer
private SensorManager mSensorManager; // new sensor
private ShakeEventListener mSensorListener; // variable that listens for movement
// if the back button is pressed, return to easy menu
public void onBackPressed()
{
Intent backIntent = new Intent(Pictures.this, Learningmenu.class);
startActivity(backIntent);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.words); // uses easy_mode1 xml
// shared preferences variable that will act as a holder of users progress
final SharedPreferences app_preferences = PreferenceManager.getDefaultSharedPreferences(this);
AlertDialog.Builder hint = new AlertDialog.Builder(this); // hint alert dialog box
hint.setMessage("Would you like a hint?");
hint.setCancelable(false);
hint.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
// if user clicks yes, toast pops up providing a hint
public void onClick(DialogInterface dialog, int id)
{
Toast.makeText(Pictures.this, "You have two of these on your body", Toast.LENGTH_LONG).show();
}
});
hint.setNegativeButton("No", new DialogInterface.OnClickListener()
{
// if the user clicks no the level is loaded again
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(Pictures.this, Pictures.class);
startActivity(intent);
dialog.cancel();
}
});
final AlertDialog hintAlert = hint.create();
hintAlert.setTitle("Hint");
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mSensorListener = new ShakeEventListener();
mSensorListener.setOnShakeListener(new ShakeEventListener.OnShakeListener()
{
// when the user shakes the device, alert them if they want a hint
public void onShake()
{
hintAlert.show();
}
});
getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
TextView plot; // text view which will hold the plot
plot = (TextView)findViewById(R.id.question1); // look for text called question1 in xml
plot.setMovementMethod(new ScrollingMovementMethod());
AlertDialog.Builder alt_bld = new AlertDialog.Builder(this); // alert dialog box
alt_bld.setMessage("Correct! Proceed to next level?");
alt_bld.setCancelable(false);
alt_bld.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
// if user decides to continue to the next level, load the second easy level
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(Pictures.this, Pictures.class);
startActivity(intent);
}
});
alt_bld.setNegativeButton("No", new DialogInterface.OnClickListener()
{
// if the user does not want to continue, load the easy mode levels
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(Pictures.this, Pictures.class);
startActivity(intent);
dialog.cancel();
}
});
final AlertDialog alert = alt_bld.create();
alert.setTitle("Yes! Mano means Hand");
sButton = (Button)findViewById(R.id.ansSubmit1); // submit button will find ansSubmit button in xml
sButton.setOnClickListener(new View.OnClickListener()
{
// if the submit button is clicked check text entered to actual answer
public void onClick(View view)
{
mEdit = (EditText)findViewById(R.id.ansField1);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
Context context = getApplicationContext();
String text = getResources().getString(R.string.answer1);
// if the text that was entered matches the answer, alert dialog box will appear
if(mEdit.getText().toString().replaceAll(" ", "").replaceAll("-", "").toLowerCase().equals(text))
{
int level = app_preferences.getInt("level", 0);
if (level > 0)
{
level=level-1;
}
level++;
SharedPreferences.Editor editor = app_preferences.edit();
editor.putInt("level", level);
editor.commit();
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.correct);
mediaPlayer.start();
alert.show();
}
else
{
// if the text that was entered does not match the answer, toast pop up = "Incorrect"
CharSequence message = "Incorrect!";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, message, duration);
toast.show(); // show toast alert
v.vibrate(250); // vibrate device for 250ms
}
}
});
}
#Override
protected void onResume()
{
super.onResume();
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
#Override
protected void onPause()
{
mSensorManager.unregisterListener(mSensorListener);
super.onStop();
}
}
public class Pictures<sButton> extends MainActivity
{
int level=0; // integer that will keep track of users progress
Button sButton; // represents the submit button
It appears your class is a Generic of type sButton - and sButton isn't a type.

Simple EditText Alert dialog ran before main activity created

Trying to display simple edit text dialog, requesting a string be provided before the rest of my application starts. Currently im trying to make it so the APIKEY of my app is request first thing, then once entered its saved a shared preference and then the dialog will not display. The current code is being reused from a old project of mine. If anybody can help point me in the right direct to making this simple dialog.
public void getapikey() {
AlertDialog.Builder adb = new AlertDialog.Builder(this);
LayoutInflater adbInflater = LayoutInflater.from(this);
View eulaLayout = adbInflater.inflate(R.layout.custom_dialog, null);
editText = (EditText) eulaLayout.findViewById(R.id.editText1);
adb.setView(eulaLayout);
adb.setTitle("Api Key");
adb.setMessage("Welcome to the app, Please input your APIkey below");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
// CheckBox Confirm for Alert Dialog
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString();
if (editText !=null)
//Unsure about this part above and below
editText = "0"
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("apikey", value);
// Commit the edits!
editor.commit();
return;
}
});
// Preferences For Alert Dialog
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
String apikey = settings.getString("apikey", "0");
if (apikey!=null )
adb.setIcon(R.drawable.ic_launcher);
adb.show();
}
}
RECOMMENDED CHANGES
public class Welcome extends Activity {
public static final String PREFS_NAME = "MyPrefsFile";
public EditText editText;
public String value;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getapikey();
}
public void getapikey() {
// Alert Dialog
AlertDialog.Builder adb = new AlertDialog.Builder(this);
LayoutInflater adbInflater = LayoutInflater.from(this);
View eulaLayout = adbInflater.inflate(R.layout.custom_dialog, null);
// dontShowAgain = (CheckBox) eulaLayout.findViewById(R.id.checkBox1);
editText = (EditText) eulaLayout.findViewById(R.id.editText1);
adb.setView(eulaLayout);
adb.setTitle("Api Key");
adb.setMessage("Welcome to the app, Please input your APIkey below");
adb.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
//String checkBoxResult = "NOT checked";
String value = editText.getText().toString();
// if (dontShowAgain.isChecked())
// checkBoxResult = "checked";
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
//editor.putString("skipMessage", checkBoxResult);
editor.putString("apikey", value);
// Commit the edits!
editor.commit();
return;
}
});
// Preferences For Alert Dialog
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
//String skipMessage = settings.getString("skipMessage", "NOT checked");
String apikey = settings.getString("apikey", value);
if(!value.equals(""))
adb.setIcon(R.drawable.ic_launcher);
adb.show();
setContentView(R.layout.splash_screen);
Thread splashThread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
// changed from 5000 to 4000 11.29
while (waited < 3000) {
sleep(100);
waited += 100;
}
} catch (InterruptedException e) {
// do nothing
} finally {
Intent i = new Intent();
i.setClassName("com.example.app",
"com.example.app.CardsTesting");
startActivity(i);
finish();
}
}
};
splashThread.start();
}
}
Still doesnt save the preference after the first time then never displays
//try this one i think it may be work
SharedPreferences settings = PreferenceManager.getSharedPreferences(PREFS_NAME, 0);

Categories

Resources