Passing Parcelable Object between Intents - java

I am having an issue passing an object I have created in between events. I used the website http://www.parcelabler.com/ to create the parcelable element of the code. The object class is show below: (The Item class is another simple object containing Strings and doubles and has also been made parcelable)
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
public class Diner implements Parcelable {
private String name;
private ArrayList<Item> itemList = new ArrayList<Item>();
public Diner(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void addItem(Item foodItem) {
itemList.add(foodItem);
foodItem.incrementBuyerCount();
}
public double getPrice() {
double total = 0;
for(Item item : itemList) {
total += item.getPrice() / item.getBuyerCount();
}
return total;
}
protected Diner(Parcel in) {
name = in.readString();
if (in.readByte() == 0x01) {
itemList = new ArrayList<Item>();
in.readList(itemList, Item.class.getClassLoader());
} else {
itemList = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
if (itemList == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(itemList);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<Diner> CREATOR = new Parcelable.Creator<Diner>() {
#Override
public Diner createFromParcel(Parcel in) {
return new Diner(in);
}
#Override
public Diner[] newArray(int size) {
return new Diner[size];
}
};
}
In my main activity, I have a button which opens an 'Add Diner' activity, when a button is pressed and waits for a result.
private final int SET_REQUEST = 1;
addDinerButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), AddDinerActivity.class);
startActivityForResult(intent, SET_REQUEST);
}
});
The Add Diner activity is opened, the user enters a String in a Diner Name EditText which is used the create a new Diner object and returns to the main activity when an OK button is pressed.
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
Diner newDiner = new Diner(dinerNameEditText.getText().toString());
intent.putExtra("newDiner", newDiner);
setResult(RESULT_OK, intent);
finish();
}
});
Finally the Diner object is received and added to an array in the main activity:
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK) {
if(requestCode == SET_REQUEST) {
Diner newDiner = getIntent().getParcelableExtra("newDiner");
dinerList.add(newDiner);
}
}
}
Unfortunately my code is crashing when I try to save the Diner object and pass it to the main activity, can anyone see why this is?

Use data third parameter of onActivityResult method instead of getIntent() for getting data from Intent which is sent from Activity which is started using startActivityForResult :
Diner newDiner = data.getParcelableExtra("newDiner");

Related

Can't Edit or Update Room database entries

I am building an app where the user can store his/her usernames and passwords. The app has a simple UI. The Main thread has a list of entries, a FAB and a delete all icon on the action bar. My issue is that I am not able to edit and update existing entries.
I have the following code in the onCreate() of my MainActivity.java. When the user holds an entry, it launches the AddEditEntry.java activity. What happens here is that the launched activity does not have the existing entry data in its EditText fields:
adapter.setOnItemLongClickListener(new RecyclerViewAdapter.OnItemLongClickListener() {
#Override
public void onItemLongClick(Entries entries) {
Intent intent = new Intent(MainActivity.this, AddEditEntry.class);
intent.putExtra(AddEditEntry.EXTRA_USERNAME, entry.getUsername());
intent.putExtra(AddEditEntry.EXTRA_HINT, entry.getHint());
intent.putExtra(AddEditEntry.EXTRA_PASSWORD, entry.getPassword());
intent.putExtra(AddEditEntry.EXTRA_ID, entry.getId());
startActivityForResult(intent, EDIT_ENTRY_REQUEST);
}
});
In my AddEditEntry.java activity, I have the following code in the onClick of the save button. I am adding the new data as extras to the intent:
saveEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra(EXTRA_USERNAME, usernameEditText.getText().toString());
data.putExtra(EXTRA_HINT, hintEditText.getText().toString());
data.putExtra(EXTRA_PASSWORD, passwordEditText.getText().toString());
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if(id != -1){data.putExtra(EXTRA_ID, id);}
setResult(RESULT_OK, data);
finish();
}
});
and back in my MainActivity.jav, this is my onActivityResult():
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == ADD_ENTRY_REQUEST && resultCode == RESULT_OK){
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
Entries entry = new Entries(username, hint, password);
viewModel.insert(entry);
Toast.makeText(this, "Entry added!", Toast.LENGTH_SHORT).show();
}else if(requestCode == EDIT_ENTRY_REQUEST && resultCode == RESULT_OK){
int id = Objects.requireNonNull(data).getIntExtra(AddEditEntry.EXTRA_ID, -1);
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
if (id == -1){Toast.makeText(addEditEntry, "Something went wrong", Toast.LENGTH_SHORT).show();}
Entries entry = new Entries(username, hint, password);
entry.setId(id);
viewModel.update(entry);
Toast.makeText(this, "Entry updated", Toast.LENGTH_SHORT).show();
}
else{Toast.makeText(this, "Entry not added!", Toast.LENGTH_SHORT).show();}
}
When I run the app and try to edit an entry, the Toast message reads "Entry updated!" so it does run that code but the changes do not exist. I tried stopping the app and restarting it to refresh it but it still doesn't exist.
ViewModel.java:
public class EntryViewModel extends AndroidViewModel {
private EntryRepository repository;
private LiveData<List<Entries>> allEntries;
public EntryViewModel(#NonNull Application application) {
super(application);
repository = new EntryRepository(application);
allEntries = repository.getAllEntries();
}
public void insert(Entries entries){repository.insert(entries);}
public void update(Entries entries){repository.update(entries);}
public void delete(Entries entries){repository.delete(entries);}
public void deleteAll(){repository.deleteAllEntries();}
public LiveData<List<Entries>> getAllEntries() {return allEntries;}
}
EntryRepository.java:
public class EntryRepository {
private EntryDAO entryDAO;
private LiveData<List<Entries>> allEntries;
public EntryRepository(Application application){
EntryDatabase database = EntryDatabase.getInstance(application);
entryDAO = database.generateDao();
allEntries = entryDAO.getAllEntries();
}
public void insert(Entries entries){new InsertEntryAsyncTask(entryDAO).execute(entries);}
public void update(Entries entries){new UpdateEntryAsyncTask(entryDAO).execute(entries);}
public void delete(Entries entries){new DeleteEntryAsyncTask(entryDAO).execute(entries);}
public void deleteAllEntries(){new DeleteAllEntriesAsyncTask(entryDAO).execute();}
public LiveData<List<Entries>> getAllEntries(){return allEntries;}
public static class InsertEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private InsertEntryAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.insert(entries[0]);
return null;
}
}
public static class UpdateEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private UpdateEntryAsyncTask(EntryDAO entryDAO){
this.entryDAO = entryDAO;
}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.update(entries[0]);
return null;
}
}
public static class DeleteEntryAsyncTask extends AsyncTask<Entries, Void, Void>{
private EntryDAO entryDAO;
private DeleteEntryAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Entries... entries) {
entryDAO.delete(entries[0]);
return null;
}
}
public static class DeleteAllEntriesAsyncTask extends AsyncTask<Void, Void, Void>{
private EntryDAO entryDAO;
private DeleteAllEntriesAsyncTask(EntryDAO entryDAO){this.entryDAO = entryDAO;}
#Override
protected Void doInBackground(Void... voids) {
entryDAO.deleteAllEntries();
return null;
}
}
}
EntryDAO.java:
#Dao
public interface EntryDAO {
#Insert
void insert(Entries entries);
#Update
void update(Entries entries);
#Delete
void delete(Entries entries);
#Query("DELETE FROM entries_table")
void deleteAllEntries();
#Query("SELECT * FROM entries_table")
LiveData<List<Entries>> getAllEntries();
}
Entries.java:
#Entity(tableName = "entries_table")
public class Entries {
#PrimaryKey(autoGenerate = true)
private int id;
private String username, hint, password;
public Entries(String username, String hint, String password){
this.username = username;
this.hint = hint;
this.password = password;
}
public Entries(){}
public int getId() {return id;}
public void setId(int id) {this.id = id;}
public String getUsername() {return username;}
public void setUsername(String username) {this.username = username;}
public String getHint() {return hint;}
public void setHint(String hint) {this.hint = hint;}
public String getPassword() {return password;}
public void setPassword(String password) {this.password = password;}
}
This is the onCreate() of my AddEditEntry.java class. I've added the following Toast messages to see if it was receiving the data at all and turns out it doesn't. The Toast messages were empty:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addedit_entry);
usernameEditText = findViewById(R.id.username_field);
passwordEditText = findViewById(R.id.password_field);
hintEditText = findViewById(R.id.hint_field);
passwordABCD = findViewById(R.id.upp_checkbox);
passwordabcd = findViewById(R.id.low_checkbox);
password0123 = findViewById(R.id.num_checkbox);
passwordSymbols = findViewById(R.id.sym_checkbox);
radio4 = findViewById(R.id.four);
radio8 = findViewById(R.id.eight);
radio12 = findViewById(R.id.twelve);
radio16 = findViewById(R.id.sixteen);
Button generatePassword = findViewById(R.id.btn_password_generate);
Button saveEntry = findViewById(R.id.btn_save);
Intent intent = getIntent();
if(intent.hasExtra(EXTRA_ID)){
setTitle("Edit Entry");
usernameEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_USERNAME));
passwordEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_PASSWORD));
hintEditText.setText(Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_HINT));
Toast.makeText(this, "Info Received!!!", Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_USERNAME), Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_PASSWORD), Toast.LENGTH_SHORT).show();
Toast.makeText(this, Objects.requireNonNull(getIntent().getExtras()).getString(EXTRA_HINT), Toast.LENGTH_SHORT).show();
}
else{setTitle("Add Entry");}
generatePassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {passwordEditText.setText(generatedPassword());}});
saveEntry.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent data = new Intent();
data.putExtra(EXTRA_USERNAME, usernameEditText.getText().toString());
data.putExtra(EXTRA_HINT, hintEditText.getText().toString());
data.putExtra(EXTRA_PASSWORD, passwordEditText.getText().toString());
int id = getIntent().getIntExtra(EXTRA_ID, -1);
if(id != -1){data.putExtra(EXTRA_ID, id);}
setResult(RESULT_OK, data);
finish();
}
});
}
Do it like this
In your MainActivity.java
....
....
adapter.setOnItemLongClickListener(new RecyclerViewAdapter.OnItemLongClickListener() {
#Override
public void onItemLongClick(Entries entries) {
entry = entries; // this is very important, entry holds the current edited item
Intent intent = new Intent(MainActivity.this, AddEditEntry.class);
intent.putExtra(AddEditEntry.EXTRA_USERNAME, entry.getUsername());
intent.putExtra(AddEditEntry.EXTRA_HINT, entry.getHint());
intent.putExtra(AddEditEntry.EXTRA_PASSWORD, entry.getPassword());
// no need to pass the id, it's a autogenerated field
// intent.putExtra(AddEditEntry.EXTRA_ID, entry.getId());
startActivityForResult(intent, EDIT_ENTRY_REQUEST);
}
});
....
...
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
if(requestCode == ADD_ENTRY_REQUEST && resultCode == RESULT_OK){
...
...
} else if(requestCode == EDIT_ENTRY_REQUEST && resultCode == RESULT_OK) {
// in an Edit operation, id should not be modified, so, no need to pass this parameter
// int id =
// Objects.requireNonNull(data).getIntExtra(AddEditEntry.EXTRA_ID, -1);
String username = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_USERNAME);
String password = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_PASSWORD);
String hint = Objects.requireNonNull(data).getStringExtra(AddEditEntry.EXTRA_HINT);
// entry already exists, so, no need to create a new one
//Entries entry = new Entries(username, hint, password);
//entry.setId(id);
entry.setUsername(username);
entry.setPassword(password);
entry.setHint(hint);
viewModel.update(entry);
Toast.makeText(this, "Entry updated", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Entry not added!", Toast.LENGTH_SHORT).show();
}
super.onActivityResult(requestCode, resultCode, data);
}
Other remarks...
In your RecyclerViewAdapter.java
// This is not needed. Your list is already created in your Room query
//private List<Entries> entries = new ArrayList<>();
private List<Entries> entries;
In your MainActivity.java
// This is not needed
// AddEditEntry addEditEntry;
....
....
// addEditEntry = new AddEditEntry();

ID sent as int by intent to another activity is always zero

I am trying to send an ID as an int and get it from an intent in another activity but it returns zero.
This is the intent in the first activity:
public class Main_page extends AppCompatActivity {
ListView PatientList;
Button BTaddPatient;
DBpatients db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page);
PatientList = findViewById(R.id.PateintList);
BTaddPatient = findViewById(R.id.ADDpateint);
db = new DBpatients(this);
BTaddPatient.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Main_page.this, Add_patient_Activity.class);
startActivity(intent);
}
});
PatientList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Patient selected_patient = (Patient) parent.getItemAtPosition(position);
Intent intent = new Intent(getApplicationContext(), Update_patient.class);
intent.putExtra("ID", selected_patient.getId());
intent.putExtra("name", selected_patient.getName());
intent.putExtra("diagnose", selected_patient.getDiagnose());
startActivity(intent);
}
});
}
#Override
protected void onResume() {
super.onResume();
ArrayList<Patient> patients = db.getAllPatients();
PatientAdapter patientAdapter = new PatientAdapter(this, R.layout.item_pateint, patients);
PatientList.setAdapter(patientAdapter);
}
}
And trying to get the ID in the other activity:
public class Update_patient extends AppCompatActivity {
DBpatients db;
EditText editName, editDiagnose;
Button UpdateBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update_patient);
final int id = getIntent().getExtras().getInt("ID");
db = new DBpatients(this);
editName = findViewById(R.id.EDname);
editDiagnose = findViewById(R.id.EDdiagnose);
UpdateBTN = findViewById(R.id.BTupdate);
Patient patient = db.getPatientByID2(id);
editDiagnose.setText(patient.getDiagnose());
editName.setText(patient.getName());
UpdateBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String name = editName.getText().toString();
String diagnose = editDiagnose.getText().toString();
Patient newPatient = new Patient( id, name, diagnose);
db.UpdatePatient(newPatient);
Toast.makeText(Update_patient.this, "successfuly UPDATED", Toast.LENGTH_SHORT).show();
}
});
}
This is Patient class :
public class Patient {
private String name;
private int id;
private String diagnose;
public Patient(String name, String diagnose) {
this.name = name;
this.diagnose = diagnose;
}
public Patient(int id, String name, String diagnose) {
this.name = name;
this.diagnose = diagnose;
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDiagnose() {
return diagnose;
}
public void setDiagnose(String diagnose) {
this.diagnose = diagnose;
}
}
The app crashes, and, by using the debugger, it shows that ID = 0 when receiving it.
Please help.
You just have to send extras while calling your intent.
Like this:
Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
intent.putExtra("Variable name", "Value you want to pass");
startActivity(intent);
Now on the OnCreate method of your SecondActivity you can fetch the extras like this.
If the value you sent was in int:
int value = getIntent().getIntExtra("Variable name which you sent as an extra", defaultValue(you can give it anything));
Example:
int value = getIntent().getIntExtra("ID", 0);

Passing an object from the 2nd activity back to main activity using serializable in android

The first block of code below is my main activity in which I created the intent to the second activity. On this activity I am displaying the expense in a list view which for now I have left out as it is not fully implemented. What I simple want to do is launch the second activity and let the user enter in details and press a button to add the activity to the list view.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.addExpense) {
Intent intent = new Intent(this, ExpenseActivity.class);
startActivityForResult(intent, 1);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check that it is the SecondActivity with an OK result
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Expense expense = (Expense) data.getSerializableExtra("sampleObject");
Expenses.add(expense);
}
}
}
final Button btnAddExpense = (Button) findViewById(R.id.btnAddExpense);
btnAddExpense.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String amountV = txtAmountVat.getText().toString();
int amountVTwo = Integer.parseInt(amountV);
String amountI = txtAmount.getText().toString();
int amountITwo = Integer.parseInt(amountI);
Expense expense = new Expense(amountITwo, amountVTwo, txtDateOfExpense.getText().toString(), txtDateAdded.getText().toString(), datePaid, paid, txtDes.getText().toString(), imageUri );
Intent intent = new Intent();
intent.putExtra("Expense", expense);
setResult(MainActivity.RESULT_OK, intent);
finish();
}
});
And this is my second activity in which the user enters in data. When i try pass back the expense object the emulator states the app has stopped working. Please could I have some help as I don't know what is causing this problem. This is what my class looks like.
public class Expense implements Serializable {
private int _amount, _amountVat;
private String _dateOfExpense, _dateAdded, _datePaid, _expenseDescription;
private Boolean _paid;
private Uri _imageUri;
public Expense(int amount, int amountVat, String dateOfExpense, String dateAdded, String datePaid, Boolean paid, String expenseDescription, Uri imageUri){
_amount = amount;
_amountVat = amountVat;
_dateOfExpense = dateOfExpense;
_dateAdded = dateAdded;
_datePaid = datePaid;
_paid = paid;
_expenseDescription = expenseDescription;
_imageUri = imageUri;
}
public int get_amount() {
return _amount;
}
public void set_amount(int _amount) {
this._amount = _amount;
}
public int get_amountVat() {
return _amountVat;
}
public void set_amountVat(int _amountVat) {
this._amountVat = _amountVat;
}
public String get_dateOfExpense() {
return _dateOfExpense;
}
public void set_dateOfExpense(String _dateOfExpense) {
this._dateOfExpense = _dateOfExpense;
}
public String get_dateAdded() {
return _dateAdded;
}
public void set_dateAdded(String _dateAdded) {
this._dateAdded = _dateAdded;
}
public String get_datePaid() {
return _datePaid;
}
public void set_datePaid(String _datePaid) {
this._datePaid = _datePaid;
}
public Boolean get_paid() {
return _paid;
}
public void set_paid(Boolean _paid) {
this._paid = _paid;
}
public Uri get_imageUri() {
return _imageUri;
}
public void set_imageUri(Uri _imageUri) {
this._imageUri = _imageUri;
}
public String get_expenseDescription() {return _expenseDescription;}
public void set_expenseDescription(String _expenseDescription) {this._expenseDescription = _expenseDescription;}
}
Much can't be said about your problem without proper log details.
But you can go through these points.
The problem with Serializable approach is that reflection is used and it is a slow process. This method create a lot of temporary objects and cause quite a bit of garbage collection. So, it might be due to this. Try running on a real device & see if it persists.
Alternatively, you can implement Parcelable to your class which is faster than Serializable.

How to send Parcelable Object that contains doubly nested Parcelable arrays

I am trying to write an object in my startup activty to Parcel then send it to my Main activity using an intent. However I get a null pointer exception when retrieving the ParacelableArrayExtra in my Main activity. So i put in a check for null to handle the the null condition. However, the forecast Object does have data before being put into the intent so this condition should not be met.
I seems as though the Array of objects never gets put inside the intent. I this because I have my data being parceled incorrectly?
StartUpActivity.java
public class StartUpActivity extends AppCompatActivity {
public static final String FORECAST_KEY = "FORECAST_KEY";
private Forecast[] mForecasts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new BackgroundTask(this).execute();
}
#Override
public void startActivityForResult(Intent intent, int requestCode) {
super.startActivityForResult(intent, requestCode);
}
private class BackgroundTask extends AsyncTask {
private Intent mIntent;
private Context mContext;
private static final String TAG = "BACKGROUND_TASK";
public BackgroundTask(Context context) {
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mIntent = new Intent(StartUpActivity.this, MainActivity.class);
}
#Override
protected Object doInBackground(Object[] params) {
mForecasts = getForecasts();
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
// mForecasts is populated and does contain data
mIntent.putExtra(StartUpActivity.FORECAST_KEY, mForecasts);
// mForecasts in not located in mIntent
startActivity(mIntent);
finish();
}
// Other methods omitted
}
}
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
intent.getParcelableArrayExtra(StartUpActivity.FORECAST_KEY);
Parcelable[] allForecastParcelables = getIntent().getParcelableArrayExtra(StartUpActivity.FORECAST_KEY);
if (allForecastParcelables != null) {
mForecasts = new Forecast[allForecastParcelables.length];
for (int i = 0 ; i < allForecastParcelables.length; i++) {
mForecasts[i] = (Forecast) allForecastParcelables[i];
}
}
else {
mForecasts = null;
}
setupSlidingTabs();
}
Here are my Model objects that implement Parcelable
Forecast.java
public class Forecast implements Parcelable{
Day[] mDays;
public Day[] getDailyForecast() {
return mDays;
}
public void setDailyForecast(Day[] days) {
mDays = days;
}
#Override
public int describeContents() {
return 0;
}
public Forecast() {}
private Forecast(Parcel in) {
in.readTypedArray(mDays, Day.CREATOR);
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedArray(mDays, flags);
}
public static final Creator<Forecast> CREATOR = new Creator<Forecast>() {
#Override
public Forecast createFromParcel(Parcel source) {
return new Forecast(source);
}
#Override
public Forecast[] newArray(int size) {
return new Forecast[size];
}
};
}
Day.java
public class Day implements Parcelable {
private Hour[] mHours;
private Average mAverage;
public Hour[] getHourlyForecast() {
return mHours;
}
public void setHourlyForecast(Hour[] hours) {
mHours = hours;
}
public Average getAverageForecast() {
return mAverage;
}
public void setAverageForecast(Average average) {
mAverage = average;
}
#Override
public int describeContents() {
return 0;
}
public Day() {}
private Day(Parcel in) {
in.readTypedArray(mHours, Hour.CREATOR);
mAverage = in.readParcelable(getClass().getClassLoader());
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeTypedArray(mHours, flags);
dest.writeParcelable(mAverage, flags);
}
public static final Creator<Day> CREATOR = new Creator<Day>() {
#Override
public Day createFromParcel(Parcel source) {
return new Day(source);
}
#Override
public Day[] newArray(int size) {
return new Day[size];
}
};
}
Average.java
public class Average implements Parcelable {
private String mWindCompassDireciton;
public String getWindCompassDireciton() {
return mWindCompassDireciton;
}
public void setWindCompassDireciton(String windCompassDireciton) {
mWindCompassDireciton = windCompassDireciton;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mWindCompassDireciton);
}
public Average() {}
private Average(Parcel in) {
mWindCompassDireciton = in.readString();
}
public static final Creator<Average> CREATOR = new Creator<Average>() {
#Override
public Average createFromParcel(Parcel source) {
return new Average(source);
}
#Override
public Average[] newArray(int size) {
return new Average[size];
}
};
}
And Hour is similar to average.java
Is there anything I am overlooking?
Each ArrayList and object inside the parcelable object should be peaceable too, Check this example. but i recommend you to send GSON and convert it to String and send it between activities as a string and convert it again to your object, Check this example.

ConfirmationActivity wearable how to?

I have a problem with the implementation ConfirmationActivity. When I downloaded the full API reference documentation, and looked the part about ConfirmationActivity, I saw only one method onCreate and do not understand how to implement animation like in demos. When I search in sdk/templates/ I don't find any. Help me please.
There is my code:
public class MyActivity extends Activity {
public static final String EXTRA_TITLE = "title";
public static final String EXTRA_TEXT = "text";
#Override
public void onResume() {
super.onResume();
setContentView(R.layout.activity_my);
setTitle(getTextExtra(EXTRA_TITLE, "Title"));
((TextView)findViewById(R.id.text)).setText(getTextExtra(EXTRA_TEXT, "text"));
findViewById(R.id.ok).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
private String getTextExtra(String extra, String def) {
final String text = getIntent().getStringExtra(extra);
if (text == null) {
return def;
} else {
return text;
}
}
}
Like this one
public static void showSuccessActivity(Context context) {
Intent intent = new Intent(context, ConfirmationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION | Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(ConfirmationActivity.EXTRA_ANIMATION_TYPE, ConfirmationActivity.SUCCESS_ANIMATION);
context.startActivity(intent);
}

Categories

Resources