Android - onCreate() - java

Is there a way to access to variables on onCreate(), to reuse them in another class?
String testSubCa="";
String prixe="";
String testWiifi="";
Double testPrice=0.0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_srdata);
testSubCa = getIntent().getStringExtra(SearchRestau.txxtSub);
prixe = getIntent().getStringExtra(SearchRestau.txtprix);
testWiifi = getIntent().getStringExtra(SearchRestau.txxtWifi);
testPrice=Double.parseDouble(prixe);
refresh = (ImageButton) findViewById(R.id.imgRefresh);
refresh.setOnClickListener(this);
}
I need to use these data :/

Since you didn't really specify what exactly your plan is, it's a bit of a challenge getting a proper solution.
I'm just going to assume what you want to do is to start an activity, let the user do something inside this activity and then go back to where it was started from with the ability to use the values created inside the activity.
The easiest way to that is by not starting the activity via startActivity(Intent) but rather by using startActivityForResult(Intent, RequestCode);
In the same activity you then need to handle the event of actually getting a result. To do this you need to implement the method
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
//Your code to retrieve the data here!
}
}
The variables should be stored inside the Intent data and can be grabbed by using
data.getStringExtra();
To place the values inside the result you need to place this code in the activity you actually create them:
Intent intent = new Intent();
intent.putExtra("value_id", value);
setResult(RESULT_OK, intent);
finish();
I hope that helps with your problem!
GL

Related

After calling zxing scanner, I go back to my activity but in a new instance

I use the library zxing-android-embedded in my Android App. Before calling initiateScan() method to start the scanner from my activity, I set a class variable scanedItemId to know on which item I clicked to scan.
My issue is that when the scanner activity finished, it goes back to my activity, but in a new instance and not the initial one (I checked with a break point in the onCreate method). So, my class variable is null. What can I do to keep my initial activity instance live and be sure the scanner goes back to it?
public class MyActivity
[...]
scanedItemId = currentItem.id // The current item where we clicked on.
IntentIntegrator qrCodeScanner = new IntentIntegrator(this);
qrCodeScanner.setOrientationLocked(false);
qrCodeScanner.initiateScan();
[...]
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case IntentIntegrator.REQUEST_CODE:
// Here the scanedItemId is always null.
[...]
```
You asked:
What can I do to keep my initial activity instance live and be sure
the scanner goes back to it?
You can't. When your app goes to the background and the scanner app needs resources, Android will kill your app to make the resources available to the scanner app. This is normal and your app needs to be made robust enough to deal with this. If you need to keep track of your app's state so that you can continue when your app returns to the foreground, then you need to save that information somewhere persistent. You have choices:
SharedPreferences
SQLite database
Use a file
Implement onSaveInstanceState()
Following what #David said, I implemented the "onSaveInstanceState()" solution which works fine: I just added this in my activity:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
savedInstanceState.putInt("scanedItemIdKey", scanedItemId);
}
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
scanedItemId = savedInstanceState.getInt("scanedItemIdKey");
}
Thanks

How to remember score after app has been restarted?

I am making a two player game where I am able to have a rematch. I am also keeping track of the scores of each player. This is what my code for a rematch looks like:
public void rematch(View view) {
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(i);
}
The above code is called when the user clicks a rematch button. I basically just restart the application because it's easier than resetting all the variables I have. Anyways, to keep track of the scores, I am overriding the onStop() method like this:
#Override
protected void onStop() {
super.onStop();
// We need an Editor object to make preference changes.
// All objects are from android.context.Context
SharedPreferences settings = getSharedPreferences(SCORES_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("scoreOne", p1Score);
editor.putInt("scoreTwo", p2Score);
editor.commit();
}
I am using shared preferences. Then, in my onCreate method, I get these shared preferences like this:
// Remember scores from previous games
SharedPreferences settings = getSharedPreferences(SCORES_NAME, 0);
p1Score = settings.getInt("scoreOne", 0);
p2Score = settings.getInt("scoreTwo", 0);
updateScores();
SCORES_NAME is
public static final String SCORES_NAME = "MyScores";
This all isn't working. My scores after the game restarts are always back to 0. I was thinking of putting extras onto the intent in rematch() but I'm not sure how to access this intent in my onCreate() method. Any help is greatly appreciated!
You need to override onSaveInstanceState(Bundle savedInstanceState) and write the application state values you want to change to the Bundle parameter like this:
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
super.onSaveInstanceState(savedInstanceState);
// Save UI state changes to the savedInstanceState.
// This bundle will be passed to onCreate if the process is
// killed and restarted.
savedInstanceState.putInt("scoreOne", p1Score);
savedInstanceState.putInt("scoreTwo", p2Score);
// etc.
}
The Bundle is essentially a way of storing a NVP ("Name-Value Pair") map, and it will get passed in to onCreate() and also onRestoreInstanceState() where you'd extract the values like this:
#Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// Restore UI state from the savedInstanceState.
// This bundle has also been passed to onCreate.
int p1Score = settings.getInt("scoreOne", 0);
int p2Score = settings.getInt("scoreTwo", 0);
}
You would usually use this technique to store instance values for your application (selections, unsaved text, etc.).
Problem here is that you made the assumption that the new activity's onCreate() will be called after your first activity's onStop() has completed execution.
That's probably not an assumption you want to make, because they are two not completely related things.
Send the values you need to the newly created activity in the intent
public void rematch(View view) {
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// Those next values will be there for sure in the new activity.
i.putExtra("scoreOne", p1Score);
i.putExtra("scoreTwo", p2Score);
finish();
startActivity(i);
}
And in the onCreate of your Activity can extract those values as follows
public void onCreate(Bundle savedInstance) {
super.onCreate();
..
int p1Score = getIntent().getIntExtra("scoreOne", 0);
int p2Score = getIntent().getIntExtra("scoreTwo", 0);
}
You need to take the code from onStop and execute it before your call to finish() from the rematch method. Like this:
private void saveScores() {
SharedPreferences settings = getSharedPreferences(SCORES_NAME, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putInt("scoreOne", p1Score);
editor.putInt("scoreTwo", p2Score);
editor.commit();
}
And then call this function from rematch:
(...)
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
saveScores();
finish();
startActivity(i);
However, #elmorabea's solution is better is you are now only using SharedPreferences to pass values between activities.

Check checkbox from antoher activity

I was wondering if anyone could tell me how I could check a checkBox in an activity from another activity.
I'm making a homework app and I want to put a check next to the questions that have been completed.
So the first activity has a list of questions and next to them are unchecked boxes. When you click a question, the app takes you to the second activity. In the second activity, I want to check the box of the question that was completed.
You should use SharedPreferences for that. call this in the first activity:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
prefs.putBoolean("KEY", <your value>).apply();
and something similar in another activity:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
boolean isTicked = prefs.getBoolean("KEY", <default boolean value>);
where KEY can be anything, for example, your question's number
You should use intent and bundle logic for passing data between activities.(in most cases)
In the first activity, whenever you are creating the second activity, you pass your data.
Intent intent = new Intent(FirstActivity.this,SecondActivity.class);
intent.putExtra("checked",checkBox.isChecked());
startActivity(intent);
In the second activity you receive your data by using :
Intent receivedIntent = getIntent();
boolean finalChecked = receivedIntent.getExtras().getBoolean("checked");
//now you can apply your logic with finalChecked variable
You can save checked check question to a bundle and pass it as extra to your second activity through intent and read it from that intent inside your second activity
In your first activity do something like this
public class FirstActivity extends Activity {
public static final String EXTRA_CHECKED_QUESTION = "Checked Question";
// other codes here
private void startSecondActivity() {
String checkedQuestion = getCheckedQuestion(); // a method to get checked question
Intent intent = new Intent(this, SecondActivity.class);
intent.putExtra(FirstActivity.EXTRA_CHECKED_QUESTION, checkedQuestion);
startActivity(intent);
}
}
then in your second activity
public class SecondActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstance) {
// other codes
String checkedQuestion = getIntent().getStringExtra(FirstActivity.EXTRA_CHECKED_QUESTION);
// do whatever you want with checkQuestion
}
}
Please note that the string which you pass as first parameter to putExtra() method in FirstActivity, should be same as the string you are using with getStringExtra() to retrieve your extra in SecondActivity, otherwise you can not retrieve your passed extra in SecondActivity.
Also, I did not write these codes inside idea, so there might be syntax error
Read more about intent here

Placement of OnActivityResult with OnClicklistener

I have implemented a 3rd party camera scanning app within a project of mine
I have an adaptor that extends a viewholder so i can have a custom layout
Within a view i have a button
When i create the view i add an OnclickListener to the image which i want to make clickable
i want this OnclickListener to call the camera but i need to call an startActivityForResult
i am confused about the placement of the onActivityResult when calling in this way.
my current attempts have been to create a seperate class(scan_activity) which extends activity but i couldnt get the onclicklistener to start the class
i have then attempted to declare it within the setOnClickListener, which as you can guess also failed.
Im guessing the call to the class is the way forward.im sure its an easy fix, but im not seeing it
please help
thanks in advance
imgCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ScanActivity.class);
intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, 1);
((Activity) context).startActivityForResult(intent,99);
}
}
);
and the class
imgCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ScanActivity
}
}
);
The first option should work. You create an Intent object and you specify activity component as a parameter. Android will create an Activity object for you, so, never do that manually. Android should manage the lifecycle of activity.
By starting activity for result you tell Android that it should call onActivityResult callback with request code 99 on your first activity when ScanActivity will be closed.
Handling onActivityResult in your Activity:
#Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
if (requestCode == 99) {
// handle your result here
}
}

Set first visible item in gridview

I need to have gridview scrolling to the first item onResume of my activity. It has only the vertical scrolling.
I have tried the following, but it didn't work...
gridView.setSelection(0);
gridView.scrollY(0);
Can someone help please...
I would try gridView.scrollTo(0,0) or gridVIew.smoothScrollTo(0,0), depending on your preference.
Edit: Updated with fixed code.
I have solved my problem!. I have implemented onActivityResult and called the activity for adding a new item, with a known request code. Then upon return, and the result was OK; I use gridView.smoothScrollTo(0), which worked like charm! See code below...
Intent intent = new Intent(this, AddNewActivity.class);
startActivityForResult(intent, REQUEST_ADD_NEW);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode == RESULT_OK)
{
if (requestCode == REQUEST_ADD_NEW_CLOTHING_ITEM)
{
gridView.smoothScrollToPosition(0);
}
}
}

Categories