I want to select an image id every 24 hours . for example at special time like 12 a.m , i able to select a random id to set it to my imageview.
I know to use alarm manager , but I do not know how to use it.
here I just selected my random id like this ans set to SharedPreferences and finally it get it.
i want to this every 24 hours.
would you please help?
I am new with android.
private void setBG(int bg) {
SharedPreferences.Editor share1 = getSharedPreferences("share1", Context.MODE_PRIVATE).edit();
share1.putInt("bg", bg);
share1.commit();
}
private int getBG() {
SharedPreferences share1 = getSharedPreferences("share1", Context.MODE_PRIVATE);
return share1.getInt("bg", R.drawable.pg19);
}
private void showBGS() {
Random rand = new Random();
int rndInt = rand.nextInt(18) + 1;
String drawableName = "pg"+ rndInt;
int resID = getResources().getIdentifier(drawableName, "drawable", getPackageName());
setBG(resID);
}
Related
I'm trying to save marker with Latlng and two strings with SharedPreferences and i'm doing a for loop to retrieve it when the activity is lunched again i had another question before because i couldn't delete the marker from the SharedPreferences So my mind is so missed up i can't figure it out what is the issue now please check the code below and any suggestions that could help i appreciated
I'm Using the et String so i match it to Marker title and on Marker Click i delete the Marker from sharedPreferences according to its title and already initilized the SharedPreferences in onCreated Method like so SharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
So I save the values like this,
int Int,cycler,IncreaseAmount;
String testSample;
private static final String StringLat= "Latitude",StringLng="Longitude",StringDis="Dis",StringName="Name";
String SinputNames = inputName.getText().toString();
Sinputdiscription = inputdiscription.getText().toString();
dLatitude = AddedLatLng.latitude;
dLongitude = AddedLatLng.longitude;
SharedPreferences.Editor editor = SharedPrefs.edit();
IncreaseAmount++;
editor.putInt("IJSS",IncreaseAmount);
IncreaseAmount = SharedPrefs.getInt("IJSS",0);
//SJSS = SinputNames;
//SJSS = Double.toString(dLatitude);
editor.putString("ErrorTest","Pulling up the info is working");
editor.putLong(SJSS+StringLat,Double.doubleToLongBits(dLatitude));
editor.putLong(SJSS+StringLng,Double.doubleToLongBits(dLongitude));
editor.putString(SJSS+StringName,SinputNames);
editor.putString(SJSS+StringDis,Sinputdiscription);
// editor.putString("lat"+ Integer.toString((IntCoords)), Double.toString(point.latitude));
editor.putString("ForLooper"+Integer.toString((IncreaseAmount)),SinputNames);
editor.apply();
and then pull it off from sharedPreferences
String CheckErrortest = SharedPrefs.getString("ErrorTest","Not working!");
Log.i("AlertSinput:",CheckErrortest);
cycler = SharedPrefs.getInt("IJSS",0);
if(cycler !=0) {
String Name="";
double Lat321,Lng321;
// Log.i("ifCycler","if Cycler != 0 is working");
Int = SharedPrefs.getInt("IJSS",0) +1;
for(int i=0; i< Int ; i++ ) {
Log.i("ForLoop:","The for loop is also working");
// editor.putString("ForLooper"+Integer.toString((IncreaseAmount)),SJSS+StringLat);
//Here i can't pull up the info
String iCheck = SharedPrefs.getString("Forlooper"+Integer.toString((Int)),"");
Log.i("TheMarkerName:","Should be"+iCheck);
Name = SharedPrefs.getString(iCheck+StringName,"Marker");
Lat321 = Double.longBitsToDouble(SharedPrefs.getLong(iCheck+StringLat,0));
Lng321 = Double.longBitsToDouble(SharedPrefs.getLong(iCheck+StringLng,0));
Log.i("Markertitle:#",Name);
Log.i("TestTheInteger:#",Integer.toString((Int)));
if(Lat321 !=0) {
AddedLatLng = new LatLng(Lat321,Lng321);
drawMarker(AddedLatLng,Name);
}
}
}
So the CheckErrortest and Log.i("ForLoop:","The for loop is also working");
are working Just fine but the String String iCheck = SharedPrefs.getString("Forlooper"+Integer.toString((Int)),"");
Is not working when i pull up the info for some reason and i couldn't figure out what is the issue anything that could help is appreciated thank you very much
I don't see you're commiting your changes. You need to do
editor.apply();
or
editor.commit();
All changes you make in an editor are batched, and not copied back to the original SharedPreferences until you call commit() or apply()
You need to apply your changes after work with editor.
editor.commit();
or
editor.apply();
I want do something like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
int i = (int) (new Date().getTime()/1000);
if( ) // next day
{
mymethod();
}
}
When in system date is a new day, then I want to call mymethod()
With new day do you mean after midnight? So you want to detect if the date is different from last time?
#Override
protected void onResume() {
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this);
int lastTimeStarted = settings.getInt("last_time_started", -1);
Calendar calendar = Calendar.getInstance();
int today = calendar.get(Calendar.DAY_OF_YEAR);
if (today != lastTimeStarted) {
//startSomethingOnce();
SharedPreferences.Editor editor = settings.edit();
editor.putInt("last_time_started", today);
editor.commit();
}
}
It is recommended to use Calendar class instead of Date. You can check whether a day passed like this:
On some event, e.g. button click, app first start, save the time in sharedPreferences
Retrieve that value and compare it to the current time
Just an illustration on how to do this:
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
Calendar c = Calendar.getInstance();
int currentTimeSeconds = c.get(Calendar.SECOND);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int secondsPreviousDay = prefs.getInt("seconds", 0);
if (secondsPreviousDay != 0){ //means there was an earlier set value from previously entering the activity
//compare if more than 3600*24 = 86400 (1 day in seconds) had passed
if (currentTimeSeconds - secondsPreviousDay > 86400){
mymethod();
}
}
else {
prefs.edit().putInt("seconds", currentTimeSeconds).apply();
}
}
In my code I've presumed that you want to see if a day has passed from the first time you've started this activity until the second time. You can tweak this to your preference, but I hope the idea is understandable.
I know I could've compacted those 2 if's into one, but I just wanted it to be more clear what I was after.
Great idea!
In my first activity I set something like this inside onCreate :
Calendar c = Calendar.getInstance();
int currentTimeSeconds = c.get(Calendar.SECOND);
SharedPreferences share = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edittime = share.edit();
edittime.putInt("timevalue",currentTimeSeconds);
edittime.commit();
and use your code in another activity inside onCreate:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int secondsPreviousDay = prefs.getInt("seconds", 0);
if (secondsPreviousDay != 0){ //means there was an earlier set value from previously entering the activity
//compare if more than 3600*24 = 86400 (1 day in seconds) had passed
if (currentTimeSeconds - secondsPreviousDay > 86400){
// mymethod();
mymethod();
}
}
else {
prefs.edit().putInt("seconds", currentTimeSeconds).apply();
}
}
I'm sorry for that but I'm still learning
I have an android imageView.
I have set an OnClickListener to pick an image from Photo Gallery to be its src.
I now want to change the OnClick open this specific image in the photo gallery.
how do I do this? how to open a specific image in the photo gallery ?
You can query with particular photoID, from below code you got all image and it's id and from id you can find particular image.
final String[] columns = { MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID };
final String orderBy = MediaStore.Images.Media._ID;
imagecursor = getActivity().managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, columns, null, null, orderBy);
int image_column_index = imagecursor.getColumnIndex(MediaStore.Images.Media._ID);
this.count = imagecursor.getCount();
this.arrPath = new String[this.count];
ids = new int[count];
for (int i = 0; i < this.count; i++) {
imagecursor.moveToPosition(i);
ids[i] = imagecursor.getInt(image_column_index);
int dataColumnIndex = imagecursor.getColumnIndex(MediaStore.Images.Media.DATA);
arrPath[i] = imagecursor.getString(dataColumnIndex);
}
find adapter code and set it in gridview from
get full photogallery code
I have an application that has 2 screens. The first screen has a ListView of movies with a row consisting of 3 Elements: Title, Date and Gross declared in strings.xml. The user has the option of adding a movie by clicking the menu button, which sends him to another screen. The second screen has 3 Edit texts that correspond to Title Date and Gross, which is alphabetically sorted straight away when it returns to screen 1.
Similarly, the user can also Edit/Delete entries by long clicking a row thatbrings up a context menu. The Edit function works like this:
a.) User long clicks Titanic and chooses Edit
b.) Row gets deleted, and user is brought to screen 2
c.) Edit texts are populated with the initial data from the deleted Row
d.) When user edits data, new movie is added at the bottom of the ListView.
The problem arises when the user deletes this new movie at the bottom of the ListView. Logcat gives a
java.lang.IndexOutOfBoundsException: Invalid index 50, size is 50
Here is my code (Take note I am using Perst to persist data, but I don;t think that won't really matter with my problem):
case R.id.contextedit:
Lab9_082588FetchDetails row = (Lab9_082588FetchDetails) getListView()
.getItemAtPosition(info.position);
Intent editData = new Intent(MovieList.this, Lab9_082588Edit.class);
String startTitle = row.getTitle();
String startGross = row.getGross();
String startDate = row.getDate();
editData.putExtra(Lab9_082588Edit.TITLE_STRING, startTitle);
editData.putExtra(Lab9_082588Edit.GROSS_STRING, startGross);
editData.putExtra(Lab9_082588Edit.DATE_STRING, startDate);
startActivityForResult(editData, MovieList.EDIT_MOVIE);
int posEdit = info.position;
String editTitle = results.get(info.position).getTitle();
results.remove(posEdit);
adapter.notifyDataSetChanged();
//Perst
Index<Lab9_082588FetchDetails> rootEdit = (Index<Lab9_082588FetchDetails>) db
.getRoot();
rootEdit.remove(editTitle, results.get((int) info.id));
db.setRoot(rootEdit);
return true;
Edit Class:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection using item.getItemId()
switch (item.getItemId()) {
case R.id.edit:
next();
break;
}
return true;
}
private void next() {
// TODO Auto-generated method stub
EditText movieTitle = (EditText) findViewById(R.id.etTitle);
EditText movieGross = (EditText) findViewById(R.id.etGross);
EditText movieDate = (EditText) findViewById(R.id.etDate);
String title = movieTitle.getText().toString();
String gross = movieGross.getText().toString();
String date = movieDate.getText().toString();
if ((title.length() > 0) && (gross.length() > 0)
&& (date.length() == 4)) {
Intent hobby = getIntent();
hobby.putExtra(Lab9_082588Edit.TITLE_STRING, title);
hobby.putExtra(Lab9_082588Edit.GROSS_STRING, gross);
hobby.putExtra(Lab9_082588Edit.DATE_STRING, date);
setResult(RESULT_OK, hobby);
finish();
}
}
Delete function:
int posDelete = info.position;
String deleteTitle = results.get(
info.position).getTitle();
results.remove(posDelete);
adapter.notifyDataSetChanged();
Index<Lab9_082588FetchDetails> rootDelete = (Index<Lab9_082588FetchDetails>) db
.getRoot();
rootDelete.remove(deleteTitle,
results.get(info.position));
db.setRoot(rootDelete); //Perst
return;
OnActivityResult (Edit):
case EDIT_MOVIE:
Lab9_082588FetchDetails edittedMovie = new Lab9_082588FetchDetails();
NumberFormat formatterEdit = new DecimalFormat("###,###,###");
edittedMovie.setTitle(data
.getStringExtra(Lab9_082588Add.TITLE_STRING));
edittedMovie.setGross("$"
+ formatterEdit.format(Double.parseDouble(data
.getStringExtra(Lab9_082588Add.GROSS_STRING))));
edittedMovie.setDate(data
.getStringExtra(Lab9_082588Add.DATE_STRING));
results.add(edittedMovie);
adapter.notifyDataSetChanged();
Populating the Listview:
for (int i = 0; i < items.size(); i++) {
Lab9_082588FetchDetails sr = new Lab9_082588FetchDetails();
sr.setTitle(items.get(i).getTitle());
sr.setGross(items.get(i).getGross());
sr.setDate(items.get(i).getDate());
results.add(sr);
Collections.sort(results, ignoreCaseStart);
}
How do I remedy this?
This problem occurs because in your delete function, you first remove the element from the results collection("results.remove(posDelete);"), and then, a few lines later, you call "results.get(info.position)" to fetch a parameter for the rootDelete.remove call, but which is already removed.
If the element is the last element of your collection, let's say the 50th element, the value for "info.position" is 50. You remove one element, so the number of elements is now 49. In the rootDelete.remove line you call results.get(50), which produces the error.
I've created a timetable app, which allows the user to enter data and then view it.However if the user enters an entry, on a day and time where there already is one, my emulator crashes(forces a close).
Basically I'm pulling back data to a linear layout- which contains 10 TextViews, each representing the times 9-15.
Here's the code:
public void addMondayGrid() {
// TODO Auto-generated method stub
for (int index = 0; index < info.mon.size(); index++) {
// int entryId = info.monIds.get(index);
int time = info.monTimes.get(index);
int id = info.monIds.get(index);
int duration = info.monDuration.get(index);
String dayOfWeek = "mon";
timeId = getResources().getIdentifier("mon" + time, "id",
getPackageName());
if (duration == 1) {
SpannableString text = new SpannableString(info.mon.get(index));
setEntryColour(text);
final TextView textV = (TextView) findViewById(timeId);
textV.setTextSize(10);
textV.setText(text, BufferType.SPANNABLE);
textV.setId(id);
deleteGridEntry(textV);
} else {
longerDuration(time, index, id, info.mon, dayOfWeek);
}
}
}
The thing is is works fine as long as there isn't two entries for the same day and time, eg. monday at 9 oclock.
Anyone have any ideas?I'm quite new to this and any help would be much appreciated!
I have to reference the id this way as there are too many ids to reference any other way,is there not a simple way to overwrite the old textView with new data pulled back from the database? I want the id to be the same one as that is the textView I want to deal with, but it just keeps crashing, is it something to do with instances?
change:
final TextView textV = (TextView) findViewById(timeId);
to:
final TextView textV = (TextView) findViewById(R.id.timeId);