I want to pass an array of objects without using the preference
I use Intent!!!
The Object class Bts
public class Bts implements Serializable {
int idbts;
String nombts;
String ipaddress;
String logb;
String pawb;
int xbts;
int ybts;
public Bts(int idbts, String nombts, String ipaddress, String logb,
String pawb, int xbts, int ybts) {
super();
this.idbts = idbts;
this.nombts = nombts;
this.ipaddress = ipaddress;
this.logb = logb;
this.pawb = pawb;
this.xbts = xbts;
this.ybts = ybts;
}
//wthis setter and getter
}
The source activity
Ps:JSONParseBts filled listeBts.
public class ApresConnextionActivity extends Activity {
public Bts[] listeBts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.apresconnect);
final Button btsButton = (Button) findViewById(R.id.btbts);
//boutonbts
btsButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.w("myApp",""+listeBts.length);
Intent i = new Intent(ApresConnextionActivity.this, BtsBoutonActivity.class);
i.putExtra("tabbts",listeBts);
startActivity(i);
}
});
new JSONParseBts().execute();
}
public class JSONParseBts extends AsyncTask<String, String, JSONObject> { ... }
}
And distination Activity:
public class BtsBoutonActivity extends Activity {
cellule[] listecellule;
Bts[] listeBts;
int i,xx=0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.btsbouton);
Bundle b = getIntent().getExtras();
if (b != null)
{
Bts[] listeBts = (Bts[])b.getSerializable("tabbts") ;
Log.w("myApp",""+listeBts.length);
}else{
Log.w("myApp","you have problem");
}
/* Intent intent = getIntent();
listeBts = (Bts[])intent.getSerializableExtra("tabbts");*/
final Button[] b = new Button[listeBts.length];
LinearLayout ll3 = (LinearLayout)findViewById(R.id.linearLayout2); // Btn
for(i = 0; i < listeBts.length; i++){
//Log.w("myApp",listeBts[i].toString());
b[i] = new Button(BtsBoutonActivity.this);
b[i].setText(listeBts[i].getNombts());
xx =listeBts[i].getIdbts();
Log.w("myApp",""+xx);
b[i].setId(xx);
ll3.addView(b[i]);
final Button btbts = (Button) findViewById(xx);
btbts.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast saved_message=Toast.makeText(BtsBoutonActivity.this,btbts.getText()+" "+btbts.getId(),1);
saved_message.show();
}});
}
}
}
The error is:
05-10 16:29:25.096: E/AndroidRuntime(819): java.lang.RuntimeException: Unable to start activity ComponentInfo{pfe.essat.com/pfe.essat.com.BtsBoutonActivity}: java.lang.ClassCastException: java.lang.Object[] cannot be cast to pfe.essat.objet.com.Bts[]
You can use a wrapper class that contains the Serializable array, I just tested this and it works.
First, create your simple wrapper class:
import java.io.Serializable;
public class BtsWrapper implements Serializable{
Bts[] array;
public BtsWrapper(Bts[] a){
array = a;
}
}
Then pass the Serializable wrapper class in the Intent:
btsButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.w("myApp",""+listeBts.length);
Intent i = new Intent(ApresConnextionActivity.this, BtsBoutonActivity.class);
BtsWrapper bWrapper = new BtsWrapper(listeBts); //added
i.putExtra("tabbts",bWrapper); //modified
startActivity(i);
}
});
Then, get the Serializable wrapper from the extras, and just extract the array:
Bundle b = getIntent().getExtras();
if (b != null)
{
//Bts[] listeBts = (Bts[])b.getSerializable("tabbts") ;
BtsWrapper bWrapper = (BtsWrapper) b.getSerializable("tabbts"); //added
Bts[] listeBts = bWrapper.array; //added
Log.w("myApp",""+listeBts.length);
}else{
Log.w("myApp","you have problem");
}
I believe there is no such putExtra API existent that accepts Array of some Serializable objects. See http://developer.android.com/reference/android/content/Intent.html#putCharSequenceArrayListExtra(java.lang.String, java.util.ArrayList) onwards. There is also no getter available for extracting Array of some Serializable objects from Intent.
You could perhaps make your Bts class Parcelable and use public Intent putExtra (String name, Parcelable[] value) instead.
Create Constants.java
public class Constants {
public static String BTS_EXTRA_KEY = "bts_extra";
}
Fix your Bts class to be like this
import android.os.Parcel;
import android.os.Parcelable;
public class Bts implements Parcelable {
private String nombts;
private String ipaddress;
private String logb;
private String pawb;
private int idbts;
private int xbts;
private int ybts;
public Bts(Parcel in) {
// Construct from parcel
String[] data = new String[4];
int[] dataInt = new int[3];
in.readStringArray(data);
in.readIntArray(dataInt);
nombts = data[0];
ipaddress = data[1];
logb = data[2];
pawb = data[3];
idbts = dataInt[0];
xbts = dataInt[0];
ybts = dataInt[0];
}
public Bts(int idbts, String nombts, String ipaddress, String logb, String pawb, int xbts, int ybts) {
super();
this.idbts = idbts;
this.nombts = nombts;
this.ipaddress = ipaddress;
this.logb = logb;
this.pawb = pawb;
this.xbts = xbts;
this.ybts = ybts;
}
public String getNombts() {
return nombts;
}
public void setNombts(String nombts) {
this.nombts = nombts;
}
public String getIpaddress() {
return ipaddress;
}
public void setIpaddress(String ipaddress) {
this.ipaddress = ipaddress;
}
public String getLogb() {
return logb;
}
public void setLogb(String logb) {
this.logb = logb;
}
public String getPawb() {
return pawb;
}
public void setPawb(String pawb) {
this.pawb = pawb;
}
public int getIdbts() {
return idbts;
}
public void setIdbts(int idbts) {
this.idbts = idbts;
}
public int getXbts() {
return xbts;
}
public void setXbts(int xbts) {
this.xbts = xbts;
}
public int getYbts() {
return ybts;
}
public void setYbts(int ybts) {
this.ybts = ybts;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeStringArray(new String[]{nombts, ipaddress, logb, pawb});
parcel.writeIntArray(new int[]{idbts, xbts, ybts});
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public Bts createFromParcel(Parcel in) {
return new Bts(in);
}
public Bts[] newArray(int size) {
return new Bts[size];
}
};
}
Now to pass this data to another activity, you must have the data in an ArrayList
public void onBtnClick(View v){
Intent i = new Intent(MainActivity.this, SecondActivity.class);
ArrayList<Bts> listOfBts = new ArrayList<Bts>();
listOfBts.add(new Bts(123, "323", "23423", "3423", "frlaldf", 45, 324));
listOfBts.add(new Bts(124, "323", "23423", "3423", "frlaldf", 45, 324));
listOfBts.add(new Bts(125, "323", "23423", "3423", "frlaldf", 45, 324));
listOfBts.add(new Bts(126, "323", "23423", "3423", "frlaldf", 45, 324));
listOfBts.add(new Bts(127, "323", "23423", "3423", "frlaldf", 45, 324));
listOfBts.add(new Bts(128, "323", "23423", "3423", "frlaldf", 45, 324));
i.putParcelableArrayListExtra(Constants.BTS_EXTRA_KEY, listOfBts);
startActivity(i);
}
And in the other activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
printBts();
}
private void printBts(){
Bundle extras = getIntent().getExtras();
ArrayList<Bts> btsList = extras.getParcelableArrayList(Constants.BTS_EXTRA_KEY);
for(Bts b : btsList){
Log.d("SecondActivity", "" + b.getIdbts());
}
}
Result:
05-10 21:14:51.414 19703-19703/si.kseneman.btstest D/SecondActivity﹕ 123
05-10 21:14:51.414 19703-19703/si.kseneman.btstest D/SecondActivity﹕ 124
05-10 21:14:51.414 19703-19703/si.kseneman.btstest D/SecondActivity﹕ 125
05-10 21:14:51.414 19703-19703/si.kseneman.btstest D/SecondActivity﹕ 126
05-10 21:14:51.414 19703-19703/si.kseneman.btstest D/SecondActivity﹕ 127
05-10 21:14:51.414 19703-19703/si.kseneman.btstest D/SecondActivity﹕ 128
Related
I have three activities, I capture all data but one from DetailActivity upon button click and save in database using Room; My intention is to insert all these data into the database and start ReviewActivity so as to get the arraylist of reviews and also insert it in the database. Everything seems to work fine until when I want to view review offline because I believe it has been saved, reviews does not get loaded.
This is my DetailActivity,
TextView overview_tv; ImageView image_tv; TextView name_tv; TextView ratings; Context context; TextView release_date; ImageView backdrop_poster; private ExpandableHeightListView trailers; public static ArrayList<Youtube> youtube; public static ArrayList<Review> reviews; TrailerViewAdapter adapter; public static DataObject data; DataObject dataObject; ArrayList<Review> savedReview; private static final String IMAGE_URL = "http://image.tmdb.org/t/p/w185/"; private static final String THE_MOVIEDB_URL2 = "https://api.themoviedb.org/3/movie/"; private static final String MOVIE_QUERY2 = "api_key"; private static final String API_KEY2 = "6cc4f47bd4a64e0117e157b79072ae37"; private static String SEARCH_QUERY2 = "videos"; public static int movieId; Button viewReviews; Button favourite; String movieRating; private static final int YOUTUBE_SEARCH_LOADER = 23; private static final int REVIEW_SEARCH_LOADER = 24; File file; String name; String overview; String releaseDate; int switcher; public static ArrayList<Review> favouriteReviews; TextView trev; AppDatabase mDb; //Navigation arrow on the action bar #Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == android.R.id.home) { NavUtils.navigateUpFromSameTask(this); } return super.onOptionsItemSelected(item); } #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_detail); mDb = AppDatabase.getInstance(getApplicationContext()); youtube = new ArrayList<Youtube>(); reviews = new ArrayList<Review>(); adapter = new TrailerViewAdapter(this, youtube); //Credit to Paolorotolo #github trailers = findViewById(R.id.expandable_list); trailers.setAdapter(adapter); trailers.setExpanded(true); //Navigation arrow on the acton bar; check also override onOptionsItemSelected ActionBar actionBar = this.getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } context = getApplicationContext(); Intent intent = getIntent(); if (intent == null) { closeOnError(); } switcher = getIntent().getIntExtra("switch", 3); overview_tv = findViewById(R.id.overview); image_tv = findViewById(R.id.image); name_tv = findViewById(R.id.name); ratings = findViewById(R.id.ratings); release_date = findViewById(R.id.release_date); backdrop_poster = findViewById(R.id.backdrop_poster); trev = findViewById(R.id.review_show); viewReviews = findViewById(R.id.review_button); favourite = findViewById(R.id.favourite_button); addListenerOnRatingBar(ratings); if (switcher != 2) { favourite.setVisibility(View.INVISIBLE); dataObject = (DataObject) getIntent().getParcelableExtra("array"); final String favouriteName = dataObject.getName(); final String favouriteOverview = dataObject.getOverview(); final String favouriteReleaseDate = dataObject.getReleaseDate(); ArrayList<Youtube> savedTrailer = dataObject.getTrailers(); savedReview = dataObject.getMovieReviews(); movieRating = dataObject.getRating(); name_tv.setText(favouriteName); overview_tv.setText(favouriteOverview); ratings.setText("Rating: " + movieRating); release_date.setText("Release Date: " + favouriteReleaseDate);// Toast.makeText(this, "Testing Reviews " + savedReview.get(0).getAuthor(), Toast.LENGTH_SHORT).show(); String imagePath = name_tv.getText().toString() + "0i"; String backdropPath = name_tv.getText().toString() + "1b"; try { DataObjectAdapter.downloadImage(imagePath, image_tv, this); } catch (Exception e) { e.printStackTrace(); } try { DataObjectAdapter.downloadImage(backdropPath, backdrop_poster, context); } catch (Exception e) { e.printStackTrace(); } if (savedTrailer != null) { TrailerViewAdapter lv = new TrailerViewAdapter(DetailActivity.this, savedTrailer); trailers.setAdapter(lv); switcher = 3; } } else { name = getIntent().getStringExtra("Name"); overview = getIntent().getStringExtra("Overview"); final String image = getIntent().getStringExtra("Image"); movieId = getIntent().getIntExtra("movieId", 1); final String backdrop = getIntent().getStringExtra("backdrop"); releaseDate = getIntent().getStringExtra("releaseDate"); movieRating = getIntent().getStringExtra("rating"); Log.i("this", "switch " + switcher); name_tv.setText(name); overview_tv.setText(overview); ratings.setText("Rating: " + movieRating); release_date.setText("Release Date: " + releaseDate); //load backdrop poster Picasso.with(context) .load(IMAGE_URL + backdrop) .fit() .placeholder(R.drawable.placeholder_image) .error(R.drawable.placeholder_image) .into(backdrop_poster); Picasso.with(context) .load(IMAGE_URL + image) .fit() .placeholder(R.drawable.placeholder_image) .error(R.drawable.placeholder_image) .into(image_tv); getSupportLoaderManager().initLoader(YOUTUBE_SEARCH_LOADER, null, this); //getSupportLoaderManager().initLoader(REVIEW_SEARCH_LOADER, null, this); //loadTrailers(); //loadReviews(); //populateKeys(); } /** * Here manages the views(list) for reviews */ viewReviews.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { if (switcher == 3) { startActivity(new Intent(DetailActivity.this, ReviewActivity.class) .putExtra("switch", 3)); } else { Log.i("this", "I am from initial" + switcher); startActivity(new Intent(DetailActivity.this, ReviewActivity.class).putExtra("id", movieId)); } } } ); favourite.setOnClickListener(new View.OnClickListener() { #Override public void onClick(View v) { data = new DataObject(); data.setName(name); data.setOverview(overview); data.setRating(movieRating); data.setReleaseDate(releaseDate); data.setTrailers(youtube);// data.setMovieReviews(reviews); try { saveImage(name_tv.getText().toString() + "0i", image_tv); saveImage(name_tv.getText().toString() + "1b", backdrop_poster); } catch (IOException e) { e.printStackTrace(); } Toast.makeText(context, "The movie is saved as a favourite", Toast.LENGTH_LONG).show(); AppExecutors.getInstance().diskIO().execute(new Runnable() { #Override public void run() { mDb.dataDao().insertData(data); } }); startActivity(new Intent(DetailActivity.this, ReviewActivity.class).putExtra("id", movieId) .putExtra(ReviewActivity.EXTRA_DATA_ID, 20)); } } ); }
And my ReviewActivity
public class ReviewActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<ArrayList<Review>>{ public static ArrayList<Review> reviews; public static List<DataObject> favouriteReviews; public static RecyclerView reviewList; ArrayList<Review> r; private static final int REVIEW_SEARCH_LOADER = 24; private static final String MOVIE_QUERY3 = "api_key"; private static final String API_KEY3 = "6cc4f47bd4a64e0117e157b79072ae37"; private static String SEARCH_QUERY3 = "reviews"; private static final String THE_MOVIEDB_URL3 = "https://api.themoviedb.org/3/movie/"; private static int movId; public static final String EXTRA_DATA_ID = "extraDataId"; private static final int DEFAULT_TASK_ID = -1; private int mTaskId = DEFAULT_TASK_ID; DataObject data1; AppDatabase mDb; ReviewAdapter revAdapter; int loaderSwitch; #Override protected void onResume() { super.onResume(); } #Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_review); mDb = AppDatabase.getInstance(getApplicationContext()); reviews = new ArrayList<Review>(); favouriteReviews = new ArrayList<DataObject>(); reviewList = findViewById(R.id.review_list); LinearLayoutManager layoutManager = new LinearLayoutManager(getApplicationContext()); reviewList.setLayoutManager(layoutManager); reviewList.setHasFixedSize(true); int switcher = getIntent().getIntExtra("switch", 1); Intent intent = getIntent(); if (intent == null) { finish(); } Log.i("this", "swithcer " + switcher); Log.i("this loader", "Loader " + loaderSwitch); if (switcher == 3){ DataObject dataObject = (DataObject) getIntent().getParcelableExtra("ArrayOfReviews"); if (dataObject != null){ ArrayList<Review> movieReviews = dataObject.getMovieReviews(); Toast.makeText(this, "There are reviews saved", Toast.LENGTH_LONG).show(); revAdapter = new ReviewAdapter(this, movieReviews ); reviewList.setAdapter(revAdapter); } } else { movId = getIntent().getIntExtra("id", 20); revAdapter = new ReviewAdapter(this, reviews); reviewList.setAdapter(revAdapter); loadReviews(); //populateReview(); } DividerItemDecoration decoration = new DividerItemDecoration(this, VERTICAL); reviewList.addItemDecoration(decoration); } #Override protected void onStart() { super.onStart(); //loadReviews(); } public static URL buildUrl3(String stringUrl) { Uri uri = Uri.parse(THE_MOVIEDB_URL3).buildUpon() .appendPath(stringUrl) .appendPath(SEARCH_QUERY3) .appendQueryParameter(MOVIE_QUERY3, API_KEY3) .build(); URL url = null; try { url = new URL(uri.toString()); } catch (MalformedURLException exception) { Log.e(TAG, "Error creating URL", exception); } return url; } public void loadReviews(){ // COMPLETED (19) Create a bundle called queryBundle Bundle queryBundle = new Bundle(); // COMPLETED (20) Use putString with SEARCH_QUERY_URL_EXTRA as the key and the String value of the URL as the value// queryBundle.putString(SEARCH_QUERY_URL_EXTRA, url.toString()); // COMPLETED (21) Call getSupportLoaderManager and store it in a LoaderManager variable LoaderManager loaderManager = getSupportLoaderManager(); // COMPLETED (22) Get our Loader by calling getLoader and passing the ID we specified Loader<ArrayList<Review>> movieReviews = loaderManager.getLoader(REVIEW_SEARCH_LOADER); // COMPLETED (23) If the Loader was null, initialize it. Else, restart it. if (movieReviews == null) { loaderManager.initLoader(REVIEW_SEARCH_LOADER, queryBundle, this); } else { loaderManager.restartLoader(REVIEW_SEARCH_LOADER, queryBundle, this); } } #Override public Loader<ArrayList<Review>> onCreateLoader(int id, Bundle args) { return new AsyncTaskLoader<ArrayList<Review>>(this) { #Override protected void onStartLoading() { super.onStartLoading(); forceLoad(); } #Override public ArrayList<Review> loadInBackground() { String g = String.valueOf(movId); // Create URL object URL url = buildUrl3(g); // Perform HTTP request on the URL and receive a JSON response back String jsonResponse = ""; try { jsonResponse = getResponseFromHttpUrl(url); } catch (Exception e) { e.printStackTrace(); } reviews = MovieJsonUtils.parseReview(jsonResponse); return reviews; } }; } #Override public void onLoadFinished(Loader<ArrayList<Review>> loader, ArrayList<Review> dat) { if (reviews != null) { Intent intent = getIntent(); if (intent != null && intent.hasExtra(EXTRA_DATA_ID)) { //mButton.setText(R.string.update_button); if (mTaskId == DEFAULT_TASK_ID) { mTaskId = intent.getIntExtra(EXTRA_DATA_ID, DEFAULT_TASK_ID); AppExecutors.getInstance().diskIO().execute(new Runnable() { #Override public void run() { data.setMovieReviews(reviews); mDb.dataDao().updateData(data); //mDb.dataDao().insertData(data); final List<DataObject> task = mDb.dataDao().loadById(mTaskId); runOnUiThread(new Runnable() { #Override public void run() { populateUI(task); } }); } }); } } else { ReviewAdapter lv = new ReviewAdapter(ReviewActivity.this, reviews); reviewList.setAdapter(lv); } } } #Override public void onLoaderReset(Loader<ArrayList<Review>> loader) { }
Data gets loaded from MainActivity, the saved data is passed on to other activities as a parcellable bundle via intent, the passed data is displayed in DetailActivity but not in ReviewActivity.
Alternatively, if I can load reviews alongside YouTube keys from DetailActivity, I believe I can handle the database issue from there, but two Loaders wouldn't just work together, the app crashes; I am aware two AsyncTasks concurrently run together solved this problem, but I prefer to use Loaders because of performance on configuration change
Im building an app where I have an Array list with strings and a button.
When I press the button it deletes the string from the list (with string.remove) and display it in another activity..
The problem is that when I close the app and reopen it everything goes back to normal. How to save the changes made?
Here is the code:
public class TasksActivity extends AppCompatActivity {
private static ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_tasks);
final Button tasksbtn = (Button) findViewById(R.id.btnfortasks);
Button checkTask = (Button) findViewById(R.id.remove_case);
final TextView tasksView = (TextView) findViewById(R.id.tasks_textView);
final ArrayList<String> tasks = new ArrayList<String>();
tasks.add("one");
tasks.add("two");
tasks.add("three");
tasks.add("four");
tasks.add("five");
tasks.add("six");
Collections.shuffle(tasks);
tasksView.setText(tasks.get(0));
assert tasksbtn != null;
tasksbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Collections.shuffle(tasks);
tasksView.setText(tasks.get(0));
}
});
checkTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(TasksActivity.this, CompletedTasks.class);
intent.putExtra("completedTasks", tasks.get(0));
tasks.remove(tasks.get(0));
startActivity(intent);
}
});
}
}
And the second Activity
public class CompletedTasks extends AppCompatActivity {
String completedTasks;
Global_Variable object = new Global_Variable();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_completed_tasks);
TextView completedTasksView = (TextView) findViewById(R.id.completed_tasks);
Intent intent = getIntent();
completedTasks = intent.getExtras().getString("completedTasks");
object.tasks.add(completedTasks + "\n");
String a = "";
for (int i = 0; i < object.tasks.size(); i++) {
a += object.tasks.get (i);
completedTasksView.setText(a);
Log.d("a", "a---------" + a);
}
}
}
You should probably give try to serialization. Please take look over below sample example.
public class SerializationDemo extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Person person = new Person();
person.setName("CoderzHeaven");
person.setAddress("CoderzHeaven India");
person.setNumber("1234567890");
//save the object
saveObject(person);
// Get the Object
Person person1 = (Person)loadSerializedObject(new File("/sdcard/save_object.bin")); //get the serialized object from the sdcard and caste it into the Person class.
System.out.println("Name : " + person1.getName());
}
public void saveObject(Person p){
try
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("/sdcard/save_object.bin"))); //Select where you wish to save the file...
oos.writeObject(p); // write the class as an 'object'
oos.flush(); // flush the stream to insure all of the information was written to 'save_object.bin'
oos.close();// close the stream
}
catch(Exception ex)
{
Log.v("Serialization Save Error : ",ex.getMessage());
ex.printStackTrace();
}
}
public Object loadSerializedObject(File f)
{
try
{
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
Object o = ois.readObject();
return o;
}
catch(Exception ex)
{
Log.v("Serialization Read Error : ",ex.getMessage());
ex.printStackTrace();
}
return null;
}
Person implements Serializable //Added implements Serializable
{
String name="";
private String number="";
private String address="";
private static final long serialVersionUID = 46543445;
public void setName(String name)
{
this.name = name;
}
public void setNumber(String number)
{
this.number = number;
}
public void setAddress(String address)
{
this.address = address;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public String getAddress()
{
return address;
}
}
}
You could try saving your changes to the SharedPreferences. Then when you resatrt your app, read the changes from your ShraredPreferences and apply it to your ListView or whatever you are using.
You can read more about SharedPreferences here: https://developer.android.com/training/basics/data-storage/shared-preferences.html
I want to pass ArrayList via Intent to another activity. However, the code doesn't give any errors but List is always empty. Any idea what i'm doing wrong ? ty
Activity1
private ArrayList<ResimBean> rbList = new ArrayList<ResimBean>();
Bitmap bmp = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] thumbArray = stream.toByteArray();
Uri selectedImageUri = data.getData();
String fotopath = getRealPathFromURI(selectedImageUri);
ResimBean rb = new ResimBean(Parcel.obtain());
// rb.setResim(bar);
rb.setThumbnail(thumbArray);
rb.setPath(fotopath);
rbList.add(rb);
Intent intent = new Intent(getApplicationContext(), ResimListActivity.class);
intent.putParcelableArrayListExtra("reslist",rbList);
startActivityForResult(intent, 100);
Activity2
Bundle extras = getIntent().getExtras();
if (extras != null) {
try {
Intent i = getIntent();
ArrayList<ResimBean> rbList = i.getParcelableArrayListExtra("reslist");
} catch (Exception ex) {
String msg = ex.getMessage();
}
}
Its not giving any error but list is always empty.
EDIT
Added the code how i fill in list.
EDIT 2
Something wrong with my Parcelable class or what ?
public class ResimBean implements Parcelable {
private int Id;
private int HataBildirimId;
private byte[] Resim;
private byte[] Thumbnail;
public byte[] getThumbnail() {
return Thumbnail;
}
public void setThumbnail(byte[] thumbnail) {
Thumbnail = thumbnail;
}
private String Path;
public String getPath() {
return Path;
}
public void setPath(String path) {
Path = path;
}
public int getHataBildirimId() {
return HataBildirimId;
}
public void setHataBildirimId(int hataBildirimId) {
HataBildirimId = hataBildirimId;
}
public int getId() {
return Id;
}
public void setId(int id) {
Id = id;
}
public byte[] getResim() {
return Resim;
}
public void setResim(byte[] resim) {
Resim = resim;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(HataBildirimId);
dest.writeByteArray(Resim);
dest.writeByteArray(Thumbnail);
}
public ResimBean(Parcel in) {
readFromParcel(in);
}
public void readFromParcel(Parcel in){
this.HataBildirimId = in.readInt();
this.Resim = new byte[in.readInt()];
this.Thumbnail = new byte[in.readInt()];
}
public static final Parcelable.Creator<ResimBean> CREATOR = new Parcelable.Creator<ResimBean>() {
#Override
public ResimBean createFromParcel(Parcel in) {
return new ResimBean(in);
}
#Override
public ResimBean[] newArray(int size) {
return new ResimBean[size];
}
};
The way you are showing, you create a new ArrayList<> and send it empty as extra via intent to the next activity.
Where exactly do you populate your ArrayList?
You should do something like this:
private ArrayList<ResimBean> rbList = new ArrayList<ResimBean>();
//populate rbList using adapter, then call intent
Intent intent = new Intent(getApplicationContext(), ResimListActivity.class);
intent.putParcelableArrayListExtra("reslist",rbList);
startActivityForResult(intent, 100);
Otherwise, the rbList you send as extra will always be empty. It sounds obvious but I don't know how you are doing it, so this is my best guess.
You can follow this tutorial:
http://aryo.lecture.ub.ac.id/android-passing-arraylist-of-object-within-an-intent/
I got it working like this
Bundle extras = this.getIntent().getExtras();
if (extras != null) {
try {
Intent i = getIntent();
ArrayList<ResimBean> rbList = (ArrayList<ResimBean>) i.getExtras().get("reslist");
Log.i("mytag", " "+i.getExtras().get("reslist").toString());
Log.i("mytag", " "+rbList.get(0).toString());
} catch (Exception ex) {
String msg = ex.getMessage();
}
}
With the rbList in Activity2 size=1,
With your code I was getting size=0
In this code I have a custom adapter, and after I add new data into ArrayList my adapter.notifyDataSetChanged(); doesn't work.
public class ReceiveListFragment extends ListFragment implements AbsListView.OnScrollListener {
public ArrayList<ReceivedItemStructure> items;
private int prevVisibleItem;
private boolean isFirstTime;
private DatabaseHandler db;
private String config_username;
private String config_password;
private ReceivedAdapter adapter;
private Cursor cursor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
db = new DatabaseHandler(G.context);
config_username = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.USERNAME);
config_password = Configuration.getInstance()
.getString(getActivity(),
Configuration.SharedPrefsTypes.PASSWORD);
items = new ArrayList<ReceivedItemStructure>();
getRequestFromServer(0, 10);
adapter = new ReceivedAdapter(G.context, items);
setListAdapter(adapter);
Timer smsThread = new Timer();
GetSMSThread getSMSThread = new GetSMSThread();
smsThread.scheduleAtFixedRate(getSMSThread, 1, 10000); //(timertask,delay,period)
return super.onCreateView(inflater, container, savedInstanceState);
}
private String getRequestFromServer(long lastID, int count) {
String received = "";
try {
received = new JsonService(config_username, config_password, lastID, count, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(received);
String mUserID = config_username;
for (int i = 0; i < data_array.length(); i++) {
JSONObject json_obj = data_array.getJSONObject(i);
String mLastID = json_obj.getString("id_recived_sms");
String mSmsBody = json_obj.getString("sms_body");
String mSmsNumber = json_obj.getString("sms_number");
String mSenderName = json_obj.getString("mobile_number");
String mContactName = json_obj.getString("contact_name");
String mDate = json_obj.getString("recived_date");
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
//Log.e(" ", "" + mLastID);
}
/** Creating array adapter to set data in listview */
} catch (Exception e) {
e.printStackTrace();
}
return received;
}
public long getLastID() {
return Long.parseLong(items.get(items.size() - 1).getmLastID());
}
private void addDataToList(String LastID, String SmsBody, String SmsNumber, String SenderName, String ContactName, String Date) {
String mLastID = LastID;
String mUserID = config_username;
String mSmsBody = SmsBody;
String mSmsNumber = SmsNumber;
String mSenderName = SenderName;
String mContactName = ContactName;
String mDate = Date;
ReceivedItemStructure item = new ReceivedItemStructure(
mLastID,
mUserID,
mSmsBody,
mSmsNumber,
mSenderName,
mContactName,
mDate
);
items.add(item);
adapter.update(items);
adapter.notifyDataSetChanged();
}
public class GetSMSThread extends TimerTask {
private Long lastID;
private SQLiteDatabase dbHelper;
private List<ReceiveListFragment> rows;
#Override
public void run() {
lastID = getLastID();
if (Configuration.getInstance().checkInternetConnection(G.context)) {
try {
Thread threadTask = new Thread() {
#Override
public void run() {
G.activity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
int countSMS = 0;
String smsReceivedSender = "";
String receive_lastID = "";
String r = new JsonService(config_username, config_password, 0, 1, G.F_RECEIVE_SMS).request();
JSONArray data_array = new JSONArray(r);
ArrayList<String> items_array = new ArrayList<String>();
JSONObject json_obj = data_array.getJSONObject(0);
receive_lastID = json_obj.getString("id_recived_sms");
smsReceivedSender = json_obj.getString("mobile_number");
for (ReceivedItemStructure rf : items) {
items_array.add(rf.getmLastID());
}
if (items_array.indexOf(receive_lastID) == -1) {
countSMS++;
addDataToList(
json_obj.getString("id_recived_sms"),
json_obj.getString("sms_body"),
json_obj.getString("sms_number"),
json_obj.getString("mobile_number"),
json_obj.getString("contact_name"),
json_obj.getString("recived_date")
);
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
};
threadTask.start();
} catch (Exception e) {
e.printStackTrace();
} // END TRY
}
}
}
}
My custom Adapter code is this:
public class ReceivedAdapter extends ArrayAdapter<ReceivedItemStructure> {
private ArrayList<ReceivedItemStructure> list;
public ReceivedAdapter(Context c, ArrayList<ReceivedItemStructure> items) {
super(c,0,items);
list = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ReceiveItemView itemView = (ReceiveItemView)convertView;
if (null == itemView)
itemView = ReceiveItemView.inflate(parent);
itemView.setItem(getItem(position));
return itemView;
}
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item);
}
}
}
}
setListAdapter(adapter); works correctly and I don't have any problem, but after I add new data into items notifyDataSetChanged it doesn't work.
My manifest content:
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="21"/>
it is the super class that is handling the dataset, since you are not overriding getCount and getItem,
public void update(ArrayList<ReceivedItemStructure> items) {
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
addAll(items);
} else {
for (ReceivedItemStructure item : items) {
add(item)
}
}
}
addAll was introduced with Honeycomb, so you probably want to check the current supported sdk where you are app is running
You are modifying your original items collection. But you should to modify adapter's data. Use ArrayAdapter.add method to add new items.
I'd like to ask what I'm doing wrong if I want to pass such data to other class:
String [] codes = {"code"};
Class<?> [] classes = { TestActivity.class };
Intent i = new Intent();
Pack p = new Pack();
p.eat(classes,codes);
i.putExtra("com.mbar", p);
i.setClass(this, CaptureActivity.class);
startActivity(i);
}
}
Later in other activity I try it to unpack like that:
Bundle b = getIntent().getExtras();
Pack p = (Pack)b.getParcelable("com.mbar");
if(p!=null){
classes = p.getClasses();
codes = p.getNames();
The Pack class which is Parcelable looks like:
package com.mbar;
import android.os.Parcel;
import android.os.Parcelable;
public class Pack implements Parcelable {
Class<?>[] classes;
String [] codes;
public void eat(Class<?>[] classes,String [] codes){
this.classes = classes;
this.codes = codes;
}
public Class<?>[] getClasses(){
return this.classes;
}
public String [] getNames(){
return this.codes;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
}
String [] codes = {"code"};
Class<?> [] classes = { TestActivity.class };
Intent i = new Intent();
Pack p = new Pack(classes,codes);
i.putExtra("com.mbar", p);
i.setClass(this, CaptureActivity.class);
startActivity(i)
Pack p = (Pack)getIntent().getParcelableExtra("com.mbar");
if(p!=null){
classes = p.getClasses();
codes = p.getNames();
public static class Pack implements Parcelable {
Class<?>[] classes;
String[] codes;
public Pack(Class<?>[] classes, String[] codes) {
this.classes = classes;
this.codes = codes;
}
public Pack(Parcel in) {
int len = in.readInt();
String[] classnames = new String[len];
in.readStringArray(classnames);
classes = new Class<?>[classnames.length];
for (int i = 0; i < classnames.length; i++) {
try {
classes[i] = Class.forName(classnames[i]);
} catch (ClassNotFoundException e) {
}
}
len = in.readInt();
codes = new String[len];
in.readStringArray(codes);
}
public Class<?>[] getClasses() {
return this.classes;
}
public String[] getNames() {
return this.codes;
}
#Override
public int describeContents() {
return 0;
}
public static final Parcelable.Creator<Pack> CREATOR = new Parcelable.Creator<Pack>() {
public Pack createFromParcel(Parcel in) {
return new Pack(in);
}
public Pack[] newArray(int size) {
return new Pack[size];
}
};
#Override
public void writeToParcel(Parcel dest, int flags) {
String[] classnames = new String[classes.length];
for (int i = 0; i < classes.length; i++) {
classnames[i] = classes[i].getName();
}
dest.writeInt(classnames.length);
dest.writeStringArray(classnames);
dest.writeInt(codes.length);
dest.writeStringArray(codes);
}
}