Passing Object with multiple parts from one activity to another - android

Hi I have a Requirement like Person Details for that i have multiple details like personal,educational,job like In first activity am enter personal details and then educational and then job like that one after another for that how can i maintain all details in single object and pass through app please help me.

Be aware that you need to bundle an object in an Intent, that object must implement the Parcelable interface. Here's a common implementation taken from the Parcelable documentation...
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}
Once you've done that, simply pass the object around in an Intent...
Intent i = new Intent(getApplicationContext(), ACTIVITY_TO_START.class);
i.putExtra("extra_key", new MyParcelable());
startActivity(i);
to retrieve the object for the starting activity...
Bundle extras = getIntent().getExtras();
if(extras != null && extras.containsKey("extra_key"))
{
MyParcelable p = (MyParecelable)extras.getParcelable("extra_key");
}

Simple solution: Use intents for this
Personal.class
public class Personal extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personal);
Intent i = new Intent(getApplicationContext(), Educational.class);
i.putExtra("personal_details",<-get data from object->);
startActivity(i);
}
}
Educational.class
public class Personal extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personal);
String personal_details;
Bundle extras = getIntent().getExtras();
if (extras != null) {
personal_details= extras.getString("personal_details");
}
Intent i = new Intent(getApplicationContext(), educational.class);
i.putExtra("personal_details",personal_details);
i.putExtra("educational_details",<-get data from object->);
startActivity(i);
}
}
Job.class
public class Personal extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personal);
String personal_details,educational_details;
Bundle extras = getIntent().getExtras();
if (extras != null) {
personal_details= extras.getString("personal_details");
educational_details= extras.getString("educational_details");
}
Intent i = new Intent(getApplicationContext(), FinalResult.class);
i.putExtra("personal_details",personal_details);
i.putExtra("educational_details",educational_details);
i.putExtra("job_details",<-get data from object->);
startActivity(i);
}
}
FinalResult.class
public class Personal extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.personal);
String personal_details,educational_details,job_details;
Bundle extras = getIntent().getExtras();
if (extras != null) {
personal_details= extras.getString("personal_details");
educational_details= extras.getString("educational_details");
job_details= extras.getString("job_details");
}
}
}
{EDIT-1}
have a look at one of my answers in different storage options in
android - Click Here
You can achieve it using application variable or shared
preferences but i would not recommend it. !
Try storing it in POJO(Plain old Java class)
{EDIT-2}
Hmm if i understand correctly your question:: You are connected to internet(Wifi,Wired,... etc) basically you are trying to show a dialog when there is no network connectivity ! .... You can take the help of Broadcast receivers ...
Try this:: Set the broadcast receiver to fire the intent when there is no net connectivity ....
Write the code to catch that intent and pop the dialog .... In this dialog give the user option to reconnect the connectivity !

Related

Put And Get Extras From Another Class

I have Act_01 (where I put value) and Act_02 (where I get value) but have declared these methods in a Extras class, getting value from Act_02 returns null value:
Act_01: (Where I want to pass the value Name to Act_02)
public class Act_01 extends Activity {
Extras cc_Extras;
Button btn1;
Intent intent;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_01);
cc_Extras = new Extras();
str_Name = "Buck";
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
cc_Extras.putExtras();
startActivity(intent);
}
});
}
}
Act_02: (Where I want ot receive value Name from Act_01 but the app crashes with null value)
public class Act_02 extends Activity {
Extras cc_Extras;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_02);
cc_Extras = new Extras();
if(getIntent() != null && getIntent().getExtras() != null)
{
cc_Extras.getExtras();
}
Toast.makeText(getApplicationContext(), "Name: "+str_Name, Toast.LENGTH_SHORT).show();
}
}
Extras: (Where I define the methods to put and get Extras)
public class Extras extends Activity {
String str_Name;
Intent intent;
public void putExtras() {
// TODO Auto-generated method stub
intent.putExtra("KEY_Name", str_Name);
}
public void getExtras() {
// TODO Auto-generated method stub
str_Name = getIntent().getExtras().getString("KEY_Name");
}
}
EDIT: I do not want to pass and get data directly between activities, I want to use the 3rd class (Extras.java) because I have too many activities having too many values between each other and want to sort of define them globally in Extras so that all my other activities can just call one method instead of getting and putting too many values in my activities.
Your app crashes not with a null value, but a null pointer reference because you created a new Activity manually
cc_Extras = new Extras();
Then called a lifecycle method on it
cc_Extras.getExtras()
Which calls getIntent(), but the Intent was never setup by the Android framework, and cc_Extras.getExtras() wouldn't have any of the data you wanted anyway in the second Activity because it was just created there, not from the first Activity.
Briefly, you should never make a new Activity, and your Extras class does not need to be an Activity in the first place (nor does it provide much benefit).
Just use the Intent object provided by the first Activity to start the second Activity, and get extras like normal. Don't overcomplicate your code. Regarding the title of the question, Intent and Bundle are already "another class" designed by Android for you to transfer data.
On both activities you are creating a new instances of Extras class means they dont hold the same value you can do this to transfer data from A to B
public class Act_01 extends Activity {
Button btn1;
Intent intent;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_01);
str_Name = "Buck";
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
intent = new Intent(Act_01.this, Act_02.class);
intent.putExtra("data", str_Name)
startActivity(intent);
}
});
}
}
And receieve data like this
public class Act_02 extends Activity {
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_02);
// cc_Extras = new Extras();
if(getIntent() != null)
{
if (getIntent().getStringExtra("data") != null) {
Toast.makeText(Act_02.this, "Name: "+getIntent.getStringExtra("data"), Toast.LENGTH_SHORT).show();
}
}
}
}
Also you should consider using Activity Context instead of the application context
Ok! so here are the few things I might wanna suggest you to correct.
Changes needs to be done in the code.
You are not assigning anything to "intent" object , and you have passed a intent without assigning anything to it.
Your instance cc_Extra isn't doing anything in the activity1. You might wanna pass the "intent" object in your constructor of class like cc_Extras= new Extras(intent); and in the Extras class do the following- Intent intent;
Extras(Intent i)
{
this.intent=i;
}
In the activity2 you are creating the new Instance of Extras(). So according to your code it is going to be NULL by default. If you have done the changes from the previous step, you can create new instance by doing cc_Extras(getIntent());
Corrections in the code
1) In Extras class getExtras() method instead of str=getIntent() use str=intent.getExtras.getString().
2) In the activity2 you are not assigning anything to your String str_Name, so you need to return the string you got in getExtras() method. You can do it by changing the return type to String. Below is the sample code.
public String getExtras()
{
str_Name=intent.getExtras().getString("KEY_Name");
//OR
//str_Name=intent.getStringExtra("KEY_Name");
return str_Name;
}
3) By the doing this you need to catch this string in the activity2 by doing `
if(getIntent() != null && getIntent().getExtras() != null)
{
str_Name=cc_Extras.getExtras();
}`
4) Another thing is you must create intent like this-
Intent intent=new Intent(currentActivityName.this,anotherActivity2.class);
//then use the intent object
EDIT- Your code must look like this in the end...
Act1
public class Act_01 extends Activity {
Extras cc_Extras=null;
Button btn1;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_01);
str_Name = "Buck";
btn1 = (Button) findViewById(R.id.btn1);
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//changes to do
Intent intent= new Intent(Act01.this,Act02.class);
cc_Extras= new Extras(intent);
cc_Extras.putExtras(str_Name);
//end
startActivity(intent);
}
});
}
}
Act02
public class Act_02 extends Activity {
Extras cc_Extras;
String str_Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_02);
cc_Extras = new Extras(getIntent());
if(getIntent() != null && getIntent().getExtras() != null)
{
str_Name=cc_Extras.getExtras();
}
Toast.makeText(getApplicationContext(), "Name: "+str_Name, Toast.LENGTH_SHORT).show();
}
}
Extras class
public class Extras { //remove "extends Activity" because it is a class not a activity
String str_Name;
Intent intent;
Extras(Intent i)
{
this.intent=i;
}
public void putExtras(String str) {
// TODO Auto-generated method stub
str_Name=str;
intent.putExtra("KEY_Name", str_Name);
}
public String getExtras() {
// TODO Auto-generated method stub
str_Name = intent.getExtras().getString("KEY_Name");
return str_Name;
}
}
Above code will work just on String. You can extend the functionality if you want.
I hope this must work to get your code working!

Send parcelable object from second_activiy to main_activity, is it possible?

I´m trying to send a parcelabe object from second activity to main activity, but the main activity is still in the Activities´ Stack, so I have two main activity running, I know this because I have a button to close the app and I have to press the button twice, one per each main activity.
Is it possible to send a parcelable object to main activity without open again the main activity? Is it impossible or I must use sql Lite instead of?
Is other command to use instead of startActivity() to call an activity that is now in the activities stack?
My goal saves in a list the new document that the user has saved in the second activity and shown it in the main activity all the documents save.
I can recover the data send for the second activity to the main activity, but I have two main activity running...
Any advice?
Thanks in advance.
My code:
public class Albaran implements Parcelable {
private String numalbaran;
private boolean tienefoto;
private boolean incidencia;
private Uri imageToUploadUri;
public Albaran(){
}
public Albaran(String numalbaran, boolean tienefoto, boolean incidencia, Uri imageToUploadUri) {
this.numalbaran = numalbaran;
this.tienefoto = tienefoto;
this.incidencia = incidencia;
this.imageToUploadUri = imageToUploadUri;
}
protected Albaran(Parcel in) {
numalbaran = in.readString();
tienefoto = in.readByte() != 0;
incidencia = in.readByte() != 0;
imageToUploadUri = in.readParcelable(Uri.class.getClassLoader());
}
public static final Creator<Albaran> CREATOR = new Creator<Albaran>() {
#Override
public Albaran createFromParcel(Parcel in) {
return new Albaran(in);
}
#Override
public Albaran[] newArray(int size) {
return new Albaran[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(numalbaran);
dest.writeByte((byte) (tienefoto ? 1 : 0));
dest.writeByte((byte) (incidencia ? 1 : 0));
dest.writeParcelable(imageToUploadUri, flags);
}
}
I call to the second activity in my main activity
public void recogerDatos(View view){ //Onclick
intent = new Intent(this,RecogerActivity.class);
startActivity(intent);
}
I call to the first activity from my second activity
public void guardarAlbaran(View view){ //Save data when button is pressed
Albaran NuevoAlbaran = new Albaran(numAlbaran.toString(),incidenciaCheckbox.isChecked(), incidenciaCheckbox.isChecked(), imageToUploadUri);
Intent intent = new Intent(this, MainActivity.class);
intent.putExtra("Albaran", NuevoAlbaran);
startActivity(intent);
finish(); //Finalizar Actividad
}
I read the data from the parcelable objects in my main activity
Albaran nuevoAlbaran;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nuevoAlbaran = getIntent().getParcelableExtra("Albaran");
}

Parcelable from activity to fragment

I am new to parcelable and I am trying to pass data from an Activity (MainActivity) to a fragment (MainFragment) but I`m struggle to get this right.
I made a class (InfoBean) with all the (parcelable) data. When I send the data from the MainActivity, the data from bean.newTheme (2131296447) is there but as soon as I try to retrieve in the Fragment, the value is 0!
Could someone pls have a look, what I`m doing wrong? Thank you for your help.
Send data (MainActivity):
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener {
InfoBean bean = new InfoBean();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SecureSharedPreferences theme = SecureSharedPreferences.getInstance(this, "MyPrefsFile");
int newTheme = theme.getInt("themeCustom", 0);
bean.newTheme = newTheme;
Bundle bundle = new Bundle();
bundle.putInt("theme", bean.newTheme); // debug shows value 2131296447
MainFragment mf = new MainFragment();
mf.setArguments(bundle);
//
}
}
Retrieve data (MainFragment):
public class MainFragment extends Fragment {
InfoBean bean = new InfoBean();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//
Bundle bundle = this.getArguments(); // Debugging shows 0!
if (bundle != null) {
bean.newTheme = bundle.getInt("theme");
}
if (bean.newTheme == 2131296447) { // White Theme
mCardView1.setBackgroundColor(Color.parseColor("#E8EBED"));
} else { // Dark Theme
mCardView1.setBackgroundColor(Color.parseColor("#282929"));
relLay.setBackgroundColor(Color.parseColor("#1B1C1C"));
}
return rootView;
}
}
InfoBean.class:
public class InfoBean implements Parcelable {
public int newTheme;
public int THEME_DARK = R.style.DarkTheme;
public int THEME_LIGHT = R.style.LightTheme;
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.newTheme);
dest.writeInt(this.THEME_DARK);
dest.writeInt(this.THEME_LIGHT);
}
public InfoBean() {
}
protected InfoBean(Parcel in) {
this.newTheme = in.readInt();
this.THEME_DARK = in.readInt();
this.THEME_LIGHT = in.readInt();
}
public static final Parcelable.Creator<InfoBean> CREATOR = new Parcelable.Creator<InfoBean>() {
#Override
public InfoBean createFromParcel(Parcel source) {
return new InfoBean(source);
}
#Override
public InfoBean[] newArray(int size) {
return new InfoBean[size];
}
};
}
If you have embedded fragment in your XML you can't use the setArguments() like that in your program. It is better to use dynamic fragment creation.
There is a brief example in android developer website which can guide you: http://developer.android.com/reference/android/app/Fragment.html there is also another implementation when you have embedded fragments and how to process arguments with that.
There is also another resource here which may help you:
Set arguments of fragment from activity
In your activity, you are using .putInt("theme" .....) but in the fragment you call .getParcelable("theme"). You're getting 0 because you're attempting to get two different data types.
Update
Since you have your fragment embedded in xml, you can't pass values to fragment class. To that you need to make it excute through java code and remove that xml. Make fragment Transaction then it will work
Update
You should try retrieving values in onCreate method of fragment.
#overide
protect void onCreate(bundle onSavedInstance){
if (savedInstance != null) {
bean.newTheme = bundle.getInt("theme");
}
}
Try this
if (bundle != null) {
bean.newTheme = bundle.getInt("theme");
}
instead of
if (bundle != null) {
bean.newTheme = bundle.getParcelable("theme");
}

How to check state of app optimally?

I develop android app. It needs save Internet data and login/password pair. I need to check that in every activity. How to do that optimally? My solution:
I create the BaseActivity class:
public class BaseActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkRequirements();
}
private void checkRequirements() {
if (needToCheckInternetConnection())
checkInternetConnection();
//check other requirements
}
private void checkInternetConnection() {
if (!Updater.getInstance(context).checkInternetConnection()) {
Bundle data = new Bundle();
data.putSerializable(SplashScreenActivity.FIELD_ACTION, SplashScreenActivity.Action.SHOW_TEXT);
data.putString(SplashScreenActivity.FIELD_TEXT, getString(R.string.splashScreenInternetNotAvailable));
changeActivity(SplashScreenActivity.class, data);
}
}
protected void changeActivity(Class<?> goTo, Bundle data) {
Intent intent = new Intent(context, goTo);
if (data != null)
intent.putExtras(data);
startActivity(intent);
finish();
}
}
And I extends all activity classes from this.
But finish() not working. So, how to change that architecture or force to work the finish() method?

keeping a variable value across all android activities

I have a database with one row of data that will be used across a number of activities. I need to be able to keep the row id available in all activites so I can read and write data across different activites with my DB adapter. I have successfully used putExtra (Overthelimit.java) via an intent to pass a row id to the next activity. mRowId variable is then given the row id using getExtra (Profile.java). The problem I now have is making mRowId available to other activities i.e. MyUsual and DrinksList so I can update data as I go.
You can see I have tried putExtras, putSerializable but can't get it to work. I think I am missing some understanding.
So for my profile menu option in the activity below I can send the value of the cursor row id to Profile class:
public class Overthelimit extends ListActivity {
private OverLimitDbAdapter dbHelper;
private Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.getListView();
dbHelper = new OverLimitDbAdapter(this);
dbHelper.open();
fillData();
registerForContextMenu(getListView());
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
private void fillData() {
cursor = dbHelper.fetchAllUserDrinks();
startManagingCursor(cursor);
//cursor.getCount();
String[] from = new String[] { OverLimitDbAdapter.KEY_USERNAME };
int[] to = new int[] { R.id.label };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
R.layout.user_row, cursor, from, to);
setListAdapter(notes);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (dbHelper != null) {
dbHelper.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.profile:
Intent myIntent1 = new Intent(this, Profile.class);
if(cursor.getCount() != 0) {
//Toast.makeText(getApplicationContext(), "no profile",Toast.LENGTH_SHORT).show();
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
}
startActivityForResult(myIntent1, 0);
return true;
case R.id.myusual:
Intent myIntent2 = new Intent(this, MyUsual.class);
startActivityForResult(myIntent2, 0);
return true;
case R.id.trackme:
Intent myIntent3 = new Intent(this, TrackMe.class);
startActivityForResult(myIntent3, 0);
return true;
case R.id.moreinfo:
Intent myIntent4 = new Intent(this, MoreInfo.class);
startActivityForResult(myIntent4, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Then make it available as mRowId in my Profile activity below:
mRowId = (bundle == null) ? null :
(Long) bundle.getSerializable(OverLimitDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? Long.parseLong(extras.getString(OverLimitDbAdapter.KEY_ROWID))
: null;
}
I then need to make this mRowId available to another activity called DrinkList from MyUsual. so I have MyUsual below with a drink1 button onClickListener to try and send the row id to DrinksList:
public class MyUsual extends Activity {
private Long mRowId;
private OverLimitDbAdapter mDbHelper;
private Cursor cursor;
private TextView mDrink1Label;
private TextView mDrink1Units;
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
mDbHelper = new OverLimitDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.my_usual);
mDrink1Label = (TextView) findViewById(R.id.drink1Label);
mDrink1Units = (TextView) findViewById(R.id.drink1Units);
Button drink1 = (Button) findViewById(R.id.drink1Button);
// get intent data i.e. which drink button pressed and mRowId
mRowId = (bundle == null) ? null :
(Long) bundle.getSerializable(OverLimitDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? Long.parseLong(extras.getString(OverLimitDbAdapter.KEY_ROWID))
: null;
}
//populateFields();
drink1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setResult(RESULT_OK);
//finish();
Intent myIntent1 = new Intent(view.getContext(), DrinksList.class);
myIntent1.putExtra("drinkButton", "drink1");
if(cursor.getCount() != 0) {
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
}
startActivityForResult(myIntent1, 0);
}
});
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//saveState();
outState.putSerializable(OverLimitDbAdapter.KEY_ROWID, mRowId);
}
}
From DrinksList I select a drink and I need to use the mRowId write the data to the database via the onListItemclick:
public class DrinksList extends ListActivity {
private ProgressDialog m_ProgressDialog = null;
private ArrayList<CreateDrinkOption> m_drinks = null;
private DrinkAdapter m_adapter;
private Runnable viewDrinks;
private String drinkButton;
private Long mRowId;
private OverLimitDbAdapter mDbHelper;
private String databaseRow;
private Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.drinks_list);
mDbHelper = new OverLimitDbAdapter(this);
mDbHelper.open();
m_drinks = new ArrayList<CreateDrinkOption>();
this.m_adapter = new DrinkAdapter(this, R.layout.drink_row, m_drinks);
setListAdapter(this.m_adapter);
viewDrinks = new Runnable(){
#Override
public void run() {
getDrinks();
}
};
Thread thread = new Thread(null, viewDrinks, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(DrinksList.this,
"Please wait...", "Retrieving data ...", true);
// get intent data i.e. which drink button pressed and mRowId
mRowId = (bundle == null) ? null :
(Long) bundle.getSerializable(OverLimitDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
drinkButton = extras.getString(drinkButton);
mRowId = extras != null ? Long.parseLong(extras.getString(OverLimitDbAdapter.KEY_ROWID))
: null;
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//saveState();
outState.putSerializable(OverLimitDbAdapter.KEY_ROWID, mRowId);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_drinks != null && m_drinks.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_drinks.size();i++)
m_adapter.add(m_drinks.get(i));
}
m_ProgressDialog.dismiss();
m_adapter.notifyDataSetChanged();
}
};
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
try
{
super.onListItemClick(l, v, position, id);
CreateDrinkOption bkg = (CreateDrinkOption)l.getItemAtPosition(position);
String drink1type = bkg.getDrinkType().toString();
float drink1units = (bkg.getPercentageByVolume() * bkg.getVolume());
//Toast.makeText(this, mRowId.toString(), Toast.LENGTH_LONG).show();
mDbHelper.updateDrink(mRowId, drink1type, drink1units);
finish();
}
catch(Exception ex)
{
Toast.makeText(this, "error", Toast.LENGTH_LONG).show();
}
}
private void getDrinks(){
try{
m_drinks = new ArrayList<CreateDrinkOption>();
CreateDrinkOption o1 = new CreateDrinkOption();
o1.setDrinkType("Beer - 1 pint");
o1.setPercentageByVolume((float) 4.5);
o1.setVolume((float) 0.5);
m_drinks.add(o1);
CreateDrinkOption o2 = new CreateDrinkOption();
o2.setDrinkType("Wine - small glass");
o2.setPercentageByVolume((float) 12);
o2.setVolume((float) 0.125);
m_drinks.add(o2);
CreateDrinkOption o3 = new CreateDrinkOption();
o3.setDrinkType("Spirit - single");
o3.setPercentageByVolume((float) 40);
o3.setVolume((float) 0.25);
m_drinks.add(o3);
CreateDrinkOption o4 = new CreateDrinkOption();
o4.setDrinkType("Alcopop - bottle");
o4.setPercentageByVolume((float) 5);
o4.setVolume((float) 0.275);
m_drinks.add(o4);
Thread.sleep(1000);
Log.i("ARRAY", ""+ m_drinks.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private class DrinkAdapter extends ArrayAdapter<CreateDrinkOption> {
private ArrayList<CreateDrinkOption> items;
public DrinkAdapter(Context context, int textViewResourceId, ArrayList<CreateDrinkOption> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.drink_row, null);
}
CreateDrinkOption o = items.get(position);
if (o != null) {
TextView tt = (TextView) v.findViewById(R.id.drinkdetail);
TextView bt = (TextView) v.findViewById(R.id.drinkunits);
if (tt != null) {
tt.setText("Type: "+o.getDrinkType());
}
if(bt != null){
bt.setText("Units: "+ String.valueOf(o.getPercentageByVolume() * o.getVolume()));
}
}
return v;
}
}
}
Sorry for the long post, but all I need to do is make this value for mRowId available to all activites so I can read/write data at any point. The data also needs to be there if the app is paused or interupted by say an incoming call, so I use onSaveInstanceState.
ok, thanks. So reply to great answers and I have done this, but it crashes trying to get the data. I have this as my Application class:
public class OverthelimitApplication extends Application {
private Long rowId;
public Long getRowId() {
return rowId;
}
public void setRowId(Long value) {
rowId = value;
}
}
then set value with this:
OverthelimitApplication app1 = (OverthelimitApplication)getApplicationContext();
app1.setRowId((long) cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID));
then try to get value with this and it crashes:
mRowId = ((OverthelimitApplication) getApplicationContext()).getRowId();
I have fixed it! using this the set and get:
app1.setRowId(Long.parseLong(cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID))));
mRowId = (long)((OverthelimitApplication)getApplicationContext()).getRowId();
I still had to specify long when setting and getting. Thanks for all your input.
Another way is to create a application class which is available for all activities.
To do that, you have to extend you Manifest with
<application
..
android:name=".MyApplication" >
and create a new Class
public class MyApplication extends Application {
public int rowId = 0;
}
inside the activities, you can access the rowId by
int mRowId = ((MyApplication) getApplicationContext()).rowId;
There are two options that I think are fit for your purpose:
SharedPreferences: the added benefit is that your variables will kept and available next time you start the application. You can store primitive types easily in shared preferences, like your rowId.
Application: you can subclass the application class, something like MyApplication extends Application, declare in your manifest that you're using this class instead of the default application, and access it using getApplication from all your activities. The added benefit is you can store anything, even a complex data structure in the application, you define the member and access methods in your MyApplication class. For example you could store the whole row of data in your application, not just the rowId)
Personally, I use SharedPreferences to remember settings that I want to be saved for the user, and not having to set them again each time the application is started is nice. And I use application for all the temporary data that I want to live across all activities as long as the application is open.
I'll describe 2 ways.
1) Use a static variable in any one of the Activities. This is the quick, dirty and lazy way. You've been warned.
2) Create your Application class.
Create a Simple class MyApplication that extends Application
In the Android Manifest, there should be a field for Application, make sure you choose your Class.
Typical example.
public class MyApp extends Application
{
private Object myGloballyAccessibleObject; //make getter and setter
private static MyApp singleInstance = null;
public static MyApp getInstance()
{
return singleInstance;
}
#Override
public void onCreate() {
super.onCreate();
singleInstance = this;
}
}
In your activities,
Call this
MyApp myApp = MyApp.getInstance();
myApp.getMyAwesomeObject(); //Booyaah!
You can use the ApplicationContext too. In your Manifest, you should have something like this :
<application
...
android:name="xx.xx.MyApp"
...>
Now, you can access to the Application from any Activity thanks to :
MyApp application = (MyApp)this.getApplicationContext();
You can put your attributes in this class, it'll be accessible anywhere in your app. MyApp must extends Application. See Manifest and
Application
Here you want to get mRowId values from all activity and it is primitive types, So
Either use Shared Preferences for store data or make your member field as a static globally, Then you can use this data in your whole application life cycle..
EDIT: Also you can use Application class as a singleton for your application and create field mRowId in this class and also make getter setter method for this field..

Categories

Resources