im sorry for the long question, but i could really use the help
so I've been trying to make a camera app for this school project that i have. i'm really new to coding in general, and i don't really know much about Java. i decided to use the CameraKit library by Furgle to help me with this. they say all i have to do is include
protected void onResume() {
super.onResume();
CameraView.start();
and
#Override
protected void onPause () {
super.onPause();
CameraView.stop();
}
i should be able to start and stop the camera preview im trying to create.
however, when i added this code to my main activity, i got the following:
non static method 'stop()' / 'start()' cannot be referenced from a static context
I've tried a few things like trying to create an object of the class and calling the method from that (i'm not completely sure if i said that right or not)
#Override
protected void onResume() {
super.onResume();
CameraView main = new CameraView()
main.start();
when i try to run that, i get:
cannot resolve constructor CameraView()
I also tried to create instances of the class called "CameraView" which is where the method "start();" and "stop();" are. sadly i have not been able to get anywhere with that.
the point is i tried everything that i could understand but any help would be greatly appreciated.
after looking into the code for the library, i saw that neither the start method or the stop method within the CameraView class are declared "static". so i really don't see where the problem is coming from and how to overcome it
Assuming the tutorial you're following is this one https://github.com/gogopop/CameraKit-Android#usage ...
When they say that "all you have to do" is add this code:
#Override
protected void onResume() {
super.onResume();
cameraView.start();
}
#Override
protected void onPause() {
cameraView.stop();
super.onPause();
}
They're speaking to more-experienced developers. The part they're leaving out is where does cameraView come from?
Well, the first step is to include a <CameraView> in your layout. But even after that, you need to find it and assign it to a cameraView variable. So really, you need all this:
public class MainActivity extends AppCompatActivity {
private CameraView cameraView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); // `activity_main.xml` must have a `<CameraView>` tag with id `camera`
cameraView = (CameraView) findViewById(R.id.camera);
}
#Override
protected void onResume() {
super.onResume();
cameraView.start();
}
#Override
protected void onPause() {
cameraView.stop();
super.onPause();
}
}
I'd like to implement an update checker in an application, and I obviously only need this to show up once when you start the application. If I do the call in the onCreate() or onStart() method, it'll be shown every time the activity is created and this is not a viable solution.
So my question is: Is there a way to do something, like check for updates, just once per application start / launch?
I'm sorry if it's a bit hard to understand, I'm having difficulties explaning myself on this one.
SharedPreferences seems like ugly solution to me. It's much more neat when you use application constructor for such purposes.
All you need is to use your own Application class, not default one.
public class MyApp extends Application {
public MyApp() {
// this method fires only once per application start.
// getApplicationContext returns null here
Log.i("main", "Constructor fired");
}
#Override
public void onCreate() {
super.onCreate();
// this method fires once as well as constructor
// but also application has context here
Log.i("main", "onCreate fired");
}
}
Then you should register this class as your application class inside AndroidManifest.xml
<application android:label="#string/app_name" android:name=".MyApp"> <------- here
<activity android:name="MyActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
You even can press Back button, so application go to background, and will not waste your processor resources, only memory resource, and then you can launch it again and constructor still not fire since application was not finished yet.
You can clear memory in Task Manager, so all applications will be closed and then relaunch your application to make sure that your initialization code fire again.
looks like you might have to do something like this
PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
int currentVersion = info.versionCode;
this.versionName = info.versionName;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int lastVersion = prefs.getInt("version_code", 0);
if (currentVersion > lastVersion) {
prefs.edit().putInt("version_code", currentVersion).commit();
// do the activity that u would like to do once here.
}
You can do this every time, to check if the app has been upgraded, so it runs only once for app upgrade
The shared preferences approach is messy, and the application class has no access to an activity.
Another alternative I've used is to have a retained fragment instance, and within that instance, a lot more stuff can be done especially if you need access to the main activity UI.
For this example, I've used asynctask within the retained fragment. My AsyncTask has callbacks to the parent activity. It is guaranteed to run only once per application because the fragment is never destroyed-recreated when the same activity is destroyed-recreated. It is a retained fragment.
public class StartupTaskFragment extends Fragment {
public interface Callbacks {
void onPreExecute();
void onProgressUpdate(int percent);
void onCancelled();
void onPostExecute();
}
public static final String TAG = "startup_task_fragment";
private Callbacks mCallbacks;
private StartupTask mTask;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (Callbacks) activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true); // this keeps fragment in memory even if parent activity is destroyed
mTask = new StartupTask();
mTask.execute();
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
private class StartupTask extends AsyncTask<Void, Integer, Void> {
#Override
protected void onPreExecute() {
if (mCallbacks != null) {
mCallbacks.onPreExecute();
}
}
#Override
protected Void doInBackground(Void... ignore) {
// do stuff here
return null;
}
#Override
protected void onProgressUpdate(Integer... percent) {
if (mCallbacks != null) {
mCallbacks.onProgressUpdate(percent[0]);
}
}
#Override
protected void onCancelled() {
if (mCallbacks != null) {
mCallbacks.onCancelled();
}
}
#Override
protected void onPostExecute(Void ignore) {
if (mCallbacks != null) {
mCallbacks.onPostExecute();
}
}
}
}
Then, in main (or parent) activity where you want this startup task fragment to run once.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getFragmentManager();
StartupTaskFragment st = (StartupTaskFragment) fm.findFragmentByTag(StartupTaskFragment.TAG);
if(st == null) {
fm.beginTransaction().add(mStartupTaskFragment = new StartupTaskFragment(), StartupTaskFragment.TAG).commit();
}
...
}
Ideas for retained fragment came from here: http://www.androiddesignpatterns.com/2013/04/retaining-objects-across-config-changes.html. I just figured out its other uses aside from config changes.
Yes you can do it Using SharedPrefernce concept of android. Just create a boolean flag and save it in SharedPrefernce and check its value in your onCreate() method .
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if (!prefs.getBoolean("onlyonce", false)) {
// <---- run your one time code here
// mark once runned.
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("onlyonce", true);
editor.commit();
}
}
This continues on #Vitalii's answer.
After having setup the Application class, if access to the Activity is required, we can use the aptly named android library "Once" https://github.com/jonfinerty/Once.
In the Application class's onCreate method
Once.initialise(this)
In the Activity / Fragment class's onCreate / onViewCreated method.
val helloTag = "hello"
if (!Once.beenDone(Once.THIS_APP_SESSION, helloTag)) {
//Do something that needs to be done only once
Once.markDone(helloTag) //Mark it done
}
I do this the same way as described in the other answer. I just have a global variable in the first activity which matches the release number from the manifest. I increment it for every upgrade and when the check sees a higher number, it executes the one-time code.
If successful, it writes the new number to shared preferences so it wont do it again until the next upgrade.
Make sure you assign the default to -1 when you retrieve the version from shared preferences so that you error on the side of running the code again as opposed to not running it and not having your app update correctly.
Use SharedPreference for this-
If you are not restarting your launcher activity again once your app is active then in that case you case use it.
Use this in a Splash screen if you are implementing it in the app.
If you are not using any splash screen then you need to create a activity with no view set and on it's oncreate call you can do start updation and start your main activity.
you can use counter value or boolean for this.
Here is SharedPreference doc:
http://developer.android.com/reference/android/content/SharedPreferences.html
try {
boolean firstboot = getSharedPreferences("BOOT_PREF",MODE_PRIVATE)
.getBoolean("firstboot", true);
if(firstboot){
//place your code that will run single time
getSharedPreferences("BOOT_PREF",MODE_PRIVATE).edit().
putBoolean("firstboot", false)
.commit();
}
I just solved doing this myself, I reopen my main activity multiple times throughout the application's execution. While the constructor is a valid approach for some things it doesn't let you access the current Application context to write toasts among other things.
My solution was to create a simple 'firstRun' boolean set to true in the class of my MainActivity, from there I run the contents of the if statement then set it to true. Example:
public class MainActivity extends AppCompatActivity
{
private static boolean firstRun = true;
#Override
protected void onCreate(Bundle savedInstanceState)
{
if(firstRun)
{
Toast.makeText(getApplicationContext(), "FIRST RUN", Toast.LENGTH_SHORT).show();
//YOUR FIRST RUN CODE HERE
}
firstRun = false;
super.onCreate(savedInstanceState);
//THE REST OF YOUR CODE
}
I have an app that user submit the log in form , when it sent the data to server and create a connection for its account.
In this connection i have an integer field named as state.
the state value is : 1 for connecting, 2 for connected and 0 for failed.
I want to show a dialog to user show is Connecting ... and then check the state of connection if its return 0 or 2 dismiss the dialog and show the related message else if it doesn't change after 15 sec dismiss dialog and change the state to 0 !
How can i do this logic ?
I am assuming to make the network all you are using an Asynctask. In this case you can use the methods onPreExecute and onPostExecute.
For more information about network calls and Asynctasks, please read http://developer.android.com/training/basics/network-ops/connecting.html. I've given a brief explanation below though.
If you create a dialog or initialise it in your onCreate method (or something similar), you can call the below methods to show and hide the dialog when the call starts and finishes
onPreExecute() {
dialog.show();
}
onPostExecute(Object result) {
dialog.dismiss();
}
You can also modify the UI from doInBackground through the use of onProgressUpdate(). This will allow you to call to the dialog whilst performing the logic in doInBackground by calling the method publishProgress(). The exact place you should call the method I'm not sure of because I don't fully understand your bigger picture but I hope this helps you along the way
This is one way.You could also use AsyncTask.onCancelled()
public class TestActivity extends Activity{
private Dialog dialog;
#override
protected void onCreate(Bundle bundle){
//relevant activity code.
TestAsync ta=new TestAsync().execute();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
ta.cancel();
if(dialog!=null)
dialog.dismiss();
}
}15*1000);
}
public class TestAsync extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
//create your dialog here
}
#Override
protected void onPostExecute(Void result) {
if(dialog!=null){
dialog.dismiss();
}
}
#Override
protected Void doInBackground(Void... params) {
//relevant AsyncTask code
}
}
}
Struggled with an appropriate title on this one. I've encountered and odd/baffling situation which only came to light as I sometimes initialize fields.
In this case, I had a boolean which I initialized to false (I know, redundant... but...)
the app runs fine and prior to exit my boolean is set to true. I watch the log cat to see that onDestroy() has been called.
I then restart the app.
My boolean, whose value I now log in onCreate(), is true.
WTF?
I noted that the activity started with a new PID. And yet, it is bypassing field initializations. Mind you, I have some which are not redundant. So what is going on here?
I then force stopped the app from the settings menu on the device. Restarting the app now shows all as expected, boolean = false.
So is onDestroy() not a reliable/real termination? I don't recall ever reading anything like that.
This is not my app but is an example of the situation:
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
private static boolean b = false;
private static int i = 1;
private static final String TAG = "junk app";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.i(TAG, "==================================================================");
if(b) Log.i(TAG,"boolean is true");
if(!b) Log.i(TAG,"boolean is false");
Log.i(TAG,"The value of i is"+i);
i++;
b=!b;
foo();
}
public void foo() {
finish();
}
#Override
public void onResume() {
Log.i(TAG,"onResume");
super.onResume();
}
#Override
public void onStop() {
Log.i(TAG,"onStop");
super.onStop();
}
#Override
public void onDestroy() {
Log.i(TAG,"onDestroy");
super.onDestroy();
}
}
Run this app on a device and watch your logcat. onDestroy() is called. Now start the app again from its icon. i is incremented and b becomes !b.
IDK but my (naive) expectation is that if an app is destroyed, if it is restarted it starts fresh and all initializations, etc are done again.
Statics are statics -- they are global to the process. So their value
will last for the lifetime of the process, which is usually much
longer than an individual activity instance.
Source: https://groups.google.com/forum/#!topic/android-developers/PZXbCXliRbo
How to overload onResume() to work the correct way? I want to come back from activity to MainActivity where I want to have the same state as after app start. I wanted to use recreate() but it looped or some sort of that.
My code:
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
recreate();
}
implement onSaveInstanceState(Bundle save) and onRestoreInstanceState(Bundle restore) to save and restore the state. See the documentation on this.
I guess, when you press back button, you want to refresh the previous activity.
It is pretty simple, you can just put your method in onResume(), and it should do the trick.
Ok Try this out, it is working for me.
public class main extends Activity{
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.your_layout);
//add any buttons or anything you have here.
doMainWork(); \\lets just say you have this method, which contains the main code of the layout.
}
protected void onResume(){
super.onResume();
doMainWork();
}
public void doMainWork(){
\\Put all your working code here. And this should work it out man.
}