I have a problem with my camera app, which is that when I take a photo I can see it in the imageview, but when I turn my phone or close the app and reopen it, the image disappears.
My code->
public class semana1 extends Activity {
Button btnfoto1;
ImageView imgs1;
static final int CAM_REQUEST=1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.semana1);
btnfoto1= (Button) findViewById(R.id.btnfoto1);
imgs1= (ImageView) findViewById(R.id.imgs1);
btnfoto1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent int1=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file=getfile();
int1.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
startActivityForResult(int1,CAM_REQUEST);
}
});
}
private File getFile()
{
File folder=new File("sdcard/Progress");
if(!folder.exists())
{
folder.mkdir();
}
File image_file=new File(folder,"image1.jpg");
return image_file;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String path = "sdcard/Progress/image1.jpg";
imgs1.setImageDrawable(Drawable.createFromPath(path));
}
}
Read up on the activity lifecycle of an app.
Now to point you in somewhat the right direction. When you close your app, the system stops the app and might later kill it. The reason why your image disappears is because you haven implemented a way for your app to save the state it was in before hand.
Therefore, you should probably implement:
public void onStop() {
super.onStop();
// code where you tell the app to save the image
}
public void onDestroy() {
super.onDestroy();
// code where you tell the app to save the image
}
Related
My question here is about playing the music after the user closes the app (the app tab is not showing on the list of currently open apps).
I have created a class to handle the service that targets the media player to play the ring-tone music:
public class RingService extends Service {
private MediaPlayer player;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
player = MediaPlayer.create(this,
Settings.System.DEFAULT_RINGTONE_URI);
player.setLooping(true);
player.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
player.stop();
}
}
in my MainActivity I use a button to start playing music. And it works fine till I close the app.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
}
public void onRing(View view) {
Intent intent = new Intent(this, RingService.class);
startService(intent);
}
public void onStop(View view) {
Intent intent = new Intent(this, RingService.class);
stopService(intent);
}
}
Is there anyone who could tell me, what I'm doing wrong? I would be extremely grateful.
And just not to start another topic for this app, I will ask it here - is it possible to relaunch the activity in 10 seconds after it has been closed by the user?
I think you missed the onCreate to implement
My app is doing good with this code:
public class BackgroundMusicService extends Service {
MediaPlayer musicPlayer;
public IBinder onBind(Intent arg) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
musicPlayer = MediaPlayer.create(this, R.raw.your_music_file);
musicPlayer.setLooping(true); // Set looping
musicPlayer.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
musicPlayer.start();
return 1;
}
#Override
public void onDestroy() {
musicPlayer.stop();
musicPlayer.release();
}
and in you manifest:
<service android:enabled="true" android:name=".BackgroundSoundService" />
So after closing your app you want to play some ringtone using RingService but when user close the app the onStop() method is called in your MainActivity with this code Intent intent = new Intent(this, RingService.class);
stopService(intent);. How service can play your music if you stopping your service at same time.
Try to delete this code from onStop() (not sure it will solve the problem but it worth trying).
Additionally I am recommending using Logcat for testing your code.
https://developer.android.com/studio/command-line/logcat
You need to put your service in foreground with startForeground(id, notification), check the official docs for reference.
When you have a service in foreground, the chances of your process being killed are reduced drastically because your process won't be considered as in background. The downside is that you must show a permanent notification, which in your case might even be desirable because you might need controls for the player.
Hello fellow programmers,
I'm experiencing some issues regarding my Android App, i'm currently
working on. For this purpose, I only need to mention that I have two
Activities (One is called MainActivity.class and the second is called
FilterActivity.class).
The purpose of my MainActiviy class is to display a movie (Genres,
year, rating etc) + a trailer of the specifik video.
In the OnCreate method for MainActiviy, im initializing the
YouTubePlayerView (since I want a random movie to pop up as soon as
you open the application).
The purpose of my FilterActivity class is to choose some specfik
search criterias for a movie.
I'm opening FilterActivity from MainActivity like this:
public void openFilter(){
Intent askIntent = new Intent(this, FilterActivity.class);
startActivityForResult(askIntent, 1); }
And in my FilterActivity im sending the information from a newly
created movie like this:
movieIntent.putExtra("url", a.getUrl());
movieIntent.putExtra("title", a.getTitle());
movieIntent.putExtra("rating", (String.valueOf(a.getRating())));
movieIntent.putExtra("plot", a.getDesc());
movieIntent.putExtra("year", (String.valueOf(a.getYear())));
movieIntent.putExtra("genre", a.getGenres());
setResult(RESULT_OK, movieIntent);
finish();
And this is how I fetch data from MainActivity:
protected void onActivityResult(int requestCode, int resultCode, final Intent data){
if(resultCode == RESULT_OK){
titleView.setText(data.getStringExtra("title"));
ratingView.setText(data.getStringExtra("rating"));
plotView.setText(data.getStringExtra("plot"));
yearView.setText(data.getStringExtra("year"));
genreView.setText(data.getStringExtra("genre"));
url = data.getStringExtra("url"); }
This is basically what I need to show. (This is all works by the way):
I'm getting a newly created movie and the criterias match.
However, in the OnActivityResult, I can't get my YoutubePlayerView to
re-load the video with the specific URL. The old video is still there,
and playable. I have checked and I am indeed getting a new URL from
the FilterActivity.
The only way I'm coming around this issue is by basically reloading
the activity, and then (since im creating a random movie in my
OnCreate method), the criteria don't match.
Any suggestions would be appreciated!
Sincerely
In onActivityResult, release current player and re-initialize YoutubePlayerView :
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (resultCode == RESULT_OK) {
mVideoId = getVideoId(data.getStringExtra("url"));
mPlayer.release();
mYoutubeplayerView.initialize(mApiKey, this);
}
}
A complete example of MainActivity is :
public class MainActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
String mVideoId = "5xVh-7ywKpE";
String mApiKey = "YOUR_API_KEY";
YouTubePlayerView mYoutubeplayerView;
YouTubePlayer mPlayer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mYoutubeplayerView = (YouTubePlayerView) findViewById(R.id.player);
mYoutubeplayerView.initialize(mApiKey, this);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openFilter();
}
});
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer youTubePlayer, boolean b) {
mPlayer = youTubePlayer;
mPlayer.loadVideo(mVideoId);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult youTubeInitializationResult) {
}
#Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if (resultCode == RESULT_OK) {
mVideoId = getVideoId(data.getStringExtra("url"));
mPlayer.release();
mYoutubeplayerView.initialize(mApiKey, this);
}
}
private String getVideoId(String url) {
String pattern = "(?<=watch\\?v=|/videos/|embed\\/)[^#\\&\\?]*";
Pattern compiledPattern = Pattern.compile(pattern);
Matcher matcher = compiledPattern.matcher(url);
if (matcher.find()) {
return matcher.group();
}
return "";
}
public void openFilter() {
Intent askIntent = new Intent(this, FilterActivity.class);
startActivityForResult(askIntent, 1);
}
}
Note that I've used this post to extract Youtube videoId from url path
Is there a way to make an alert only appear when the app is opened? I'm creating an alert in onStart() in my MainActivity and whenever I go back to that activity in the app, it shows the alert again which can be annoying to the user. Or is there a way to create a "got it" button and then turn off the alert? Here is my code:
protected void onStart() {
super.onStart();
new AlertDialog.Builder(this)
.setTitle("Instructions")
.setMessage("Hello! To begin, select a map from the list to train with. Make sure" +
" you are on the correct floor.")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
})
.setIcon(R.drawable.ic_launcher)
.show();
}
This is because when another activity comes to foreground upon your MainActivity makes your activity goes to OnPause().
Then when you go back to your MainActivity. The system calls
onStart() again. See The activity life cycle
-First Solution
public class TestActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null) {
showAlertDialog();
}
}
private void showAlertDialog() {
// code to show alert dialog.
}
}
-Second Solution
public class TestActivity extends ActionBarActivity {
private static boolean isAlertDialogShownBefore = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isAlertDialogShownBefore) {
showAlertDialog();
isAlertDialogShownBefore = true;
}
}
private void showAlertDialog() {
// code to show alert dialog.
}
#Override
public void onBackPressed() {
isAlertDialogShownBefore = false;
super.onBackPressed();
}
}
Put that code in onCreate method of your activity. Check for saveInstanceState for null, if it is then show your alertDialog
I am working on camera related app in android. What I want is when user takes photo he should be immediately take to previous activity where he was before. Right now what my code does is when user takes a photo then two button appear at the bottom of the screen i.e. Save and Discard. So I do not want that. When the picture is taken user should be directly navigate to previous activity. How can acheive this?
Here is my code
public class CameraActivity extends Activity implements View.OnClickListener {
ImageView iv;
Button bCapture, bSetWall;
Intent i;
int CameraResult = 0;
Bitmap bmp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialize();
InputStream is = getResources().openRawResource(R.drawable.ic_launcher);
bmp = BitmapFactory.decodeStream(is);
}
private void initialize() {
iv = (ImageView)findViewById(R.id.ivCamera);
bCapture = (Button)findViewById(R.id.bCapture);
bSetWall = (Button)findViewById(R.id.bSetWall);
bCapture.setOnClickListener(this);
bSetWall.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()) {
case R.id.bCapture:
i = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(i, CameraResult);
break;
case R.id.bSetWall:
try {
getApplicationContext().setWallpaper(bmp);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
bmp = (Bitmap) extras.get("data");
iv.setImageBitmap(bmp);
}
}
}
The code you have right now will capture photos using an existing camera application. That is, it is making use of an already existing Activity that belongs to some camera application that is installed on your device.
That said, there is no way to manipulate Activitys that belong to other applications. You'll have to implement your own Camera Activity instead.
I have this preferences class (below) that saves two ListPreferences, but if the ListPreferences are changed and the back button is pressed, the changes don't take affect unless the application is restarted. Did I miss something? Have been looking everywhere, but just can't seem to find an answer the fits or works. Please help.
public class Preferences extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
}
Application Code
public class Quotes extends Activity implements OnClickListener {
ProgressDialog dialog;
private WebView webview;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences SP = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String q = SP.getString("appViewType","http://www.google.com");
String c = SP.getString("appRefreshRate","20");
webview = (WebView) findViewById(R.id.scroll);
webview.getSettings().setJavaScriptEnabled(true);
webview.setWebViewClient(new QuotesWebView(this));
webview.loadUrl(q);
ScheduledExecutorService timer = Executors.newSingleThreadScheduledExecutor();
timer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
webview.reload();
}
}, 10, Long.parseLong(c),TimeUnit.SECONDS);
findViewById(R.id.refresh).setOnClickListener(this);
}
#Override
public void onPause(){
super.onPause();
}
#Override
public void onResume(){
super.onResume();
}
public void onClick(View v){
switch(v.getId()){
case R.id.refresh:
webview.reload();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
MenuItem about = menu.getItem(0);
about.setIntent(new Intent(this, About.class));
MenuItem preferences = menu.getItem(1);
preferences.setIntent(new Intent(this, Preferences.class));
return true;
}
}
You need to somehow reload your preferences when the preferences activity finishes. I thought Dirol's suggestion of loading them in onResume() instead of onCreate() was excellent; have you tried it? Or am I misunderstanding the problem as well.
In my own case, I launched the preferences activity with startActivityForResult() and then on the activity result callback, I reloaded the preferences.
Code snippets:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_PREFERENCES:
Intent intent = new Intent().setClass(this, CalcPreferences.class);
startActivityForResult(intent, MENU_PREFERENCES);
break;
default: return super.onOptionsItemSelected(item);
}
return true;
}
#Override
protected void onActivityResult(int req, int result, Intent data) {
switch( req ) {
case MENU_PREFERENCES:
SharedPreferences sp =
PreferenceManager.getDefaultSharedPreferences(this);
updatePreferences(sp);
break;
default:
super.onActivityResult(req, result, data);
break;
}
}
#Override
protected void updatePreferences(SharedPreferences sp) {
super.updatePreferences(sp);
keyclick = sp.getBoolean("keyclick", keyclick);
}
Anyway, this is what works for me. I may try moving my updatePreferences() call to onResume() myself to see if that works too.
Try overriding the onBackPressed() method.
If your "Up" button (top left <-) provides the correct result, then you can set the Back button to behave like the Up button.
#Override
public void onBackPressed() {
super.onBackPressed();
NavUtils.navigateUpFromSameTask(this);
}
You load preferences only on onCreate() method. That method called only when a fresh activity starts up. The addPreferencesFromResource inflates the xml file into the preferences, so you only get the info, which is already has been stored in the xml at the moment addPreferencesFromResource was called, not after.
Try to move that method to onResume. But watch for the memory leak. I don't know exactly what the addPreferencesFromResource do, but from the documentation - I would be very suspicious about that method activity.
I had the same problem and solved it as follows:
The main activity class implements OnSharedPreferenceChangeListener:
public class Activity_name extends Activity implements OnSharedPreferenceChangeListener {
...
}
Inside the main activity class the onSharedPreferenceChanged is run whenever a preference entry changes. I simply update all my variables from the preferences as i did in onCreate:
#Override
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
<read all preferences as you did in onCreate()>
}
This does the trick and I hope it saves you some time in searching for a solution.
I've had the same problem...
Try to create preference instance and load its data in every class and every activity where you need it.
It worked for me...Hope it helps.
You will need to reload your view or whatever object which uses those preferences, preferably when preference activity closes.
Preference activities do not change nothing but an internal file with your preferences(key=value list). When it is changed, preferenceActivity calls onPreferenceChaged() and nothing more. It doesn't refresh your stuff by itself. You need to reload prefs and to reuse them in onResume() method or equivalent.