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);
}
}
Related
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
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
I am trying to make the following Class parcelable. Usually, I do this by using the parcelabler website. But the website seems to have problems with the ArrayList> part. Does anybody know how to do it properly?
Thanks in advance!
package com.example.stoos.data;
import java.util.ArrayList;
import android.os.Parcel;
import android.os.Parcelable;
public class DataModelDiagrammDaten implements Parcelable {
ArrayList<String> Antworten = new ArrayList<String>();
ArrayList<ArrayList<Integer>> AntwortIDs = new ArrayList<ArrayList<Integer>>();
public ArrayList<String> getAntworten() {
return Antworten;
}
public ArrayList<ArrayList<Integer>> getAntwortIDs() {
return AntwortIDs;
}
public void setAntworten(ArrayList<String> antworten) {
Antworten = antworten;
}
public void setAntwortIDs(ArrayList<ArrayList<Integer>> antwortIDs) {
AntwortIDs = antwortIDs;
}
public DataModelDiagrammDaten(ArrayList<String> antworten,
ArrayList<ArrayList<Integer>> antwortIDs) {
super();
Antworten = antworten;
AntwortIDs = antwortIDs;
}
protected DataModelDiagrammDaten(Parcel in) {
if (in.readByte() == 0x01) {
Antworten = new ArrayList<String>();
in.readList(Antworten, String.class.getClassLoader());
} else {
Antworten = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (Antworten == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(Antworten);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<DataModelDiagrammDaten> CREATOR = new Parcelable.Creator<DataModelDiagrammDaten>() {
#Override
public DataModelDiagrammDaten createFromParcel(Parcel in) {
return new DataModelDiagrammDaten(in);
}
#Override
public DataModelDiagrammDaten[] newArray(int size) {
return new DataModelDiagrammDaten[size];
}
};
}
I think it is a little late, but hope it's still useful for others.
I tried to write a two dimensional Array to Parcel like this:
public class Avatar implements Parcelable {
ArrayList<Integer> arrayList;
ArrayList<ArrayList<Integer>> arrayLists;
public Avatar() {
arrayLists = new ArrayList<>();
for (int i = 0; i < 10; i++) {
ArrayList<Integer> temp = new ArrayList<>();
for (int j = 0; j < 10; j++) {
temp.add(j);
}
arrayLists.add(temp);
}
arrayList = new ArrayList<>();
for (int i = 100; i < 104; i++) {
arrayList.add(i);
}
}
protected Avatar(Parcel in) {
arrayList = new ArrayList<>();
in.readList(arrayList, Integer.class.getClassLoader());
arrayLists = new ArrayList<>();
in.readList(arrayLists, ArrayList.class.getClassLoader());
}
public static final Creator<Avatar> CREATOR = new Creator<Avatar>() {
#Override
public Avatar createFromParcel(Parcel in) {
return new Avatar(in);
}
#Override
public Avatar[] newArray(int size) {
return new Avatar[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(arrayList);
dest.writeList(arrayLists);
}
#Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < arrayList.size(); i++) {
stringBuilder.append(arrayList.get(i) + " ");
}
for (int i = 0; i < arrayLists.size(); i++) {
for (int j = 0; j < arrayLists.get(i).size(); j++) {
stringBuilder.append(arrayLists.get(i).get(j) + " ");
}
}
return stringBuilder.toString();
}
}
And send the class to another Activity:
avatar = new Avatar();
Intent intent = new Intent();
intent.setClass(ParcelActivity.this, Parcel2Activity.class);
intent.putExtra("avatar", avatar);
startActivity(intent);
Receive in another Activity:
textView.setText(getIntent().getParcelableExtra("avatar") + "");
It works correctly:
test
What should be careful is that writing and reading for the field objects in Parcel must be in the same sequence.
EDIT:
Try to put the second ArrayList in another class like this:
public class IdsObject implements Parcelable {
ArrayList<Integer> ids;
public IdsObject(ArrayList<Integer> ids) {
this.ids = ids;
}
protected IdsObject(Parcel in) {
if (in.readByte() == 0x01) {
ids = new ArrayList<Integer>();
in.readList(ids, Integer.class.getClassLoader());
} else {
ids = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (ids == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(ids);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<IdsObject> CREATOR = new Parcelable.Creator<IdsObject>() {
#Override
public IdsObject createFromParcel(Parcel in) {
return new IdsObject(in);
}
#Override
public IdsObject[] newArray(int size) {
return new IdsObject[size];
}
};
}
Then, use this class on your class like this:
public class DataModelDiagrammDaten implements Parcelable, Parcelable {
ArrayList<String> Antworten = new ArrayList<String>();
ArrayList<IdsObject> AntwortIDs = new ArrayList<IdsObject>();
protected DataModelDiagrammDaten(Parcel in) {
if (in.readByte() == 0x01) {
Antworten = new ArrayList<String>();
in.readList(Antworten, String.class.getClassLoader());
} else {
Antworten = null;
}
if (in.readByte() == 0x01) {
AntwortIDs = new ArrayList<IdsObject>();
in.readList(AntwortIDs, IdsObject.class.getClassLoader());
} else {
AntwortIDs = null;
}
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
if (Antworten == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(Antworten);
}
if (AntwortIDs == null) {
dest.writeByte((byte) (0x00));
} else {
dest.writeByte((byte) (0x01));
dest.writeList(AntwortIDs);
}
}
#SuppressWarnings("unused")
public static final Parcelable.Creator<DataModelDiagrammDaten> CREATOR = new Parcelable.Creator<DataModelDiagrammDaten>() {
#Override
public DataModelDiagrammDaten createFromParcel(Parcel in) {
return new DataModelDiagrammDaten(in);
}
#Override
public DataModelDiagrammDaten[] newArray(int size) {
return new DataModelDiagrammDaten[size];
}
};
}
Ok, I solved it. Here is the solution in case anybody else faces the same problem:
You can first make your class with an normal ArrayList (instead of ArrayList> ) parcelable with the website. Then take the following snippet an write it into the Constructor with the Parcel argument at the place, were the ArrayList was. Now change your ArrayList back to your ArrayList> and it should work.
if (in.readByte() == 0x01) {
IDs = new ArrayList<ArrayList<Integer>>();
Type collectionType = new TypeToken<ArrayList<Integer>>(){}.getType();
in.readList(IDs, collectionType.getClass().getClassLoader());
} else {
IDs = null;
}
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 have the class that implements Parcelable interface. That contain HashMap, this HashMap contains bitmap images. I need this HashMap for all my activities. So I used Parcelable. Look on my Parcelable code.
private HashMap<String, Bitmap> map;
public ParcelFullData() {
map = new HashMap();
}
public ParcelFullData(Parcel in) {
map = new HashMap();
readFromParcel(in);
}
public static final Parcelable.Creator CREATOR = new Parcelable.Creator() {
public ParcelFullData createFromParcel(Parcel in) {
return new ParcelFullData(in);
}
public ParcelFullData[] newArray(int size) {
return new ParcelFullData[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(map.size());
for (String s: map.keySet()) {
dest.writeString(s);
dest.writeValue(map.get(s));
}
}
public void readFromParcel(Parcel in) {
int count = in.readInt();
for (int i = 0; i < count; i++) {
map.put(in.readString(), (Bitmap)in.readValue(Bitmap.class.getClassLoader()));
}
}
public Bitmap get(String key) {
return map.get(key);
}
public String[] getKeys() {
Set<String> mapset = map.keySet();
String[] photoName = new String[mapset.size()];
Iterator<String> itr = mapset.iterator();
int index = 0;
while (itr.hasNext()) {
String name = itr.next();
photoName[index] = name;
index++;
}
return photoName;
}
public void put(String key, Bitmap value) {
map.put(key, value);
}
public HashMap<String, Bitmap> getHashMap() {
return map;
}
This will working fine when i pass the one Activity to another Activity.( For example Activity A to Activity B.) But If I pass this to another Activity( For example Activity B to Activity C.) means that HashMap contains no elements. That size is 0.
In Activity_A,
Intent setIntent = new Intent(activity_a, Activity_B.class);
ParcelFullData parcelData = new ParcelFullData();
Bundle b = new Bundle();
b.putParcelable("parcelData", parcelData);
startActivity(setIntent);
In Activity_B
ParcelFullData parcelData = (ParcelFullData)bundle.getParcelable("parcelData");
Parcel parcel = Parcel.obtain();
parcel.writeParcelable(parcelData , 0);
parcelData.writeToParcel(parcel, 0);
Intent setIntent = new Intent(activity_a, Activity_B.class);
Bundle b = new Bundle();
b.putParcelable("parcelData", parcelData);
startActivity(setIntent);
I'm doing the same in Activity C.
How to use resolve this?
Why do you use bundle? You don't add this bundle to intent. Use Intent.putExtra(String, Parcelable) and everything will be OK. I pass one Parcelable object through all activities in my app and it works fine.
In first activity:
Intent i = new Intent(activity_a, Activity_B.class);
i.putExtra("parcelData", parcelData);
In second activity:
parcelData = getIntent().getParcelableExtra("parcelData");
// ... do anything with parcelData here
Intent i = new Intent(activity_b, Activity_C.class);
i.putExtra("parcelData", parcelData);