I use 2 intent in same activity.One of them for take input Firstname,Lastname and Id.Other intent for send data to another activity.
But when I use intents like that code didn't work.
Can I use intents like that
intent.putExtra("lastName", intent2.getString("lastName"));
Search Activity
Intent intent = new Intent(getApplicationContext(),SearchActivity.class);
Bundle b=new Bundle();
b.putString("firstName", firstName);
b.putString("lastName", lastName);
b.putString("id", id);
b.putParcelable("LoginPartClass",lp2);
intent.putExtras(b);
startActivity(intent);
Search Activity code
final Bundle intent2 = getIntent().getExtras();
Intent intent = new Intent(getApplicationContext(),AnotherActivity.class);
intent.putExtra("keywords", keywords);
if(intent2!=null) {
final String Firstname=intent2.getString("firstName");
intent.putExtra("firstName", Firstname); }
intent.putExtra("lastName", intent2.getString("lastName"));
intent.putExtra("id", intent2.getString("id"));
}
startActivity(intent);
Parceable Class
public class LoginPart implements Parcelable{
private Token requestoken;
private OAuthService s;
private String authURL;
public LoginPart(Token Token, OAuthService S, String AuthURL) {
requestoken = Token;
s = S;
authURL = AuthURL;
}
public LoginPart( ) {
}
public Token getRequestoken() {
return requestoken;
}
public void setRequestoken(Token requestoken) {
this.requestoken = requestoken;
}
public OAuthService getS() {
return s;
}
public Parcelable getSParcelable() {
return (Parcelable) s;
}
public void setS(OAuthService s) {
this.s = s;
}
public String getAuthURL() {
return authURL;
}
public void setAuthURL(String authURL) {
this.authURL = authURL;
}
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeValue(requestoken);
dest.writeValue(s);
dest.writeValue(authURL);
}
}
Problem is related to Parcable class.When I use parceable class make crash.How can I solve that?
in your first activity:
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle b = new Bundle();
b.putInt("id", 1);
b.putString("firstName", "this is my first name");
b.putString("lastName", "this is my last name");
intent.putExtras(b);
startActivity(intent);
in second activity:
Bundle b =getIntent().getExtras();
String name =b.getString("firstName");
String lastname =b.getString("lastName");
chane your LoginPart class like this...
public class LoginPart implements Parcelable {
private Token requestoken;
private OAuthService s;
private String authURL;
public LoginPart(Token Token, OAuthService S, String AuthURL) {
requestoken = Token;
s = S;
authURL = AuthURL;
}
public LoginPart( ) {
}
public LoginPart(Parcel parcel) {
requestoken = parcel.readValue(getClassLoader());
s = parcel.readValue(getClassLoader());
authURL = parcel.readValue(getClassLoader());
}
public Token getRequestoken() {
return requestoken;
}
public void setRequestoken(Token requestoken) {
this.requestoken = requestoken;
}
public OAuthService getS() {
return s;
}
public Parcelable getSParcelable() {
return (Parcelable) s;
}
public void setS(OAuthService s) {
this.s = s;
}
public String getAuthURL() {
return authURL;
}
public void setAuthURL(String authURL) {
this.authURL = authURL;
}
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeValue(requestoken);
dest.writeValue(s);
dest.writeValue(authURL);
}
public static final Parcelable.Creator<LoginPart> CREATOR = new Creator<SecondActivity.LoginPart>() {
#Override
public LoginPart[] newArray(int size) {
return new LoginPart[size];
}
#Override
public LoginPart createFromParcel(Parcel source) {
return new LoginPart(source);
}
};
}
for this to work, your Token class and OAuthService class should implement Parcelable
Related
I have a problem I want to compare my json but isn't work I don't understand why.
i try to use the fonction compareTo() but isn't work too. I want that
if (Myjson<5 or Myjson>5)
{ ( do something ) }
I show my code
Acceuil.java
public class Accueil extends AppCompatActivity {
String json_string;
JSONObject jObj = null;
private TextView Mpx,Al,Ar,Rds,Pilots,Frequence,Rf;
private String value= String.valueOf(5);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accueil);
json_string = getIntent().getExtras().getString("json_data");
Mpx = (TextView) findViewById(R.id.mpx);
Ar=(TextView)findViewById(R.id.ar);
Al=(TextView)findViewById(R.id.al);
Rds=(TextView)findViewById(R.id.rds);
Pilots=(TextView)findViewById(R.id.pilots);
Frequence=(TextView)findViewById(R.id.fréquence);
Rf=(TextView)findViewById(R.id.rf);
try {
// Json Object {}
/******************************************************************************/
String mpx, rds, al, ar, frequence, pilots, id, id_SIGFOX, timestamps, rf;
jObj = new JSONObject(json_string);
mpx = jObj.getString("MPX");
rds = jObj.getString("RDS");
rf = jObj.getString("RF");
frequence = jObj.getString("Frequence");
timestamps = jObj.getString("timestamp");
id = jObj.getString("id");
id_SIGFOX = jObj.getString("id_SIGFOX");
pilots = jObj.getString("PILOT");
al = jObj.getString("a_l");
ar = jObj.getString("a_r");
Valeur valeurs = new Valeur(mpx, rds, al, ar, frequence, pilots, id, timestamps, id_SIGFOX, rf);
/******************************************************************************/
if(mpx.compareTo(String.valueOf(5))) {
Mpx.setText(valeurs.getMpx())
Mpx.setText(valeurs.getMpx());
Mpx.setTextColor(Color.parseColor("#00000"))
}else{
Mpx.setText(valeurs.getMpx())
Mpx.setTextColor(Color.parseColor("#DF0101"))};//red
} catch (JSONException e) {
e.printStackTrace();
}
}
public void popUp(View view){
Intent intent=new Intent(this,popUp.class);
startActivity(intent);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.warning:
Intent intent = new Intent(this, popUp.class);
startActivity(intent);
return true;
case R.id.localiser:
return true;
case R.id.station:
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
//ajoute les entrées de menu_test à l'ActionBar
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
Valeur.java
public class Valeur {
private String mpx,rds,al,ar,pilots,frequence,id,timestamps,id_SIGFOX,rf;
public Valeur(String mpx, String rds, String al, String ar, String pilots, String frequence, String id, String timestamps, String id_SIGFOX, String rf)
{
this.setMpx(mpx);
this.setRds(rds);
this.setAl(al);
this.setAr(ar);
this.setPilots(pilots);
this.setFrequence(frequence);
this.setId(id);
this.setTimestamps(timestamps);
this.setId_SIGFOX(id_SIGFOX);
this.setRf(rf);
}
public String getMpx() {
return mpx;
}
public void setMpx(String mpx) {
this.mpx = mpx;
}
public String getRds() {
return rds;
}
public void setRds(String rds) {
this.rds = rds;
}
public String getAl() {
return al;
}
public void setAl(String al) {
this.al = al;
}
public String getAr() {
return ar;
}
public void setAr(String ar) {
this.ar = ar;
}
public String getPilots() {
return pilots;
}
public void setPilots(String pilots) {
this.pilots = pilots;
}
public String getFrequence() {
return frequence;
}
public void setFrequence(String frequence) {
this.frequence = frequence;
}
public String getTimestamps() {
return timestamps;
}
public void setTimestamps(String timestamps) {
this.timestamps = timestamps;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getId_SIGFOX() {
return id_SIGFOX;
}
public void setId_SIGFOX(String id_SIGFOX) {
this.id_SIGFOX = id_SIGFOX;
}
public String getRf() {
return rf;
}
public void setRf(String rf) {
this.rf = rf;
}
}
my flux json
{"id":"1","timestamp":"2017-01-31 10:59:11","id_SIGFOX":"ABER","MPX":"1","RDS":"2","RF":"79","PILOT":"8","a_l":"-5","a_r":"-39","Frequence":"1034"}
Do as follow:
int mpxInt = Integer.parseInt(mpx);
if(mpxInt > 5) {
// mpx is > 5
} else {
// mpx is < 5
}
This should works fine
I think the problem is you try to compare the String in mpx with the integer 5.
mpx = jObj.getString("MPX");
...
if(mpx.compareTo(String.valueOf(5))) {
To do this correctly, you need to convert mpx to int. Either use something else than jObj.getString, or use Integer.parseInt to convert the string to an int.
It's one day work with no solution,
I would to passed data beetween activity, I implement Parcelable but from called activity I receive the ListFileMedia with a size=0.
When I mistake?
Class ListFileMedia (Extended of ArrayList)
public class ListFileMedia extends ArrayList<FileMedia> implements Parcelable{
public ListFileMedia(){.....}
// for test i have cancel all methods and var, sure i tested also with...
//Interface Parcelable
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
//dest.writeInt(countIntestazioni);
// Add inner class
dest.writeParcelable(this.add(FileMedia),flags);
}
public ListFileMedia(Parcel in) {
}
public final static Parcelable.Creator <ListFileMedia>CREATOR = new Creator<ListFileMedia>() {
#Override
public ListFileMedia createFromParcel(Parcel source) {
return new ListFileMedia(source);
}
#Override
public ListFileMedia[] newArray(int size) {
return new ListFileMedia[size];
}
};
}
Custom objects in FileListMedia
public class FileMedia implements Comparable,Parcelable{
public String getPath() {return path;}
public String getBucket() {
return bucket;
}
public String getMimeType() { return mimeType; }
private String path;
private String bucket;
private String mimeType;
private int giorno;
private int mese;
private int anno;
public FileMedia(int giorno,int mese,int anno, String path,String bucket,String mimeType){
....
}
public int compareTo(Object o) {
.....
}
//Interface Parcelable
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.path);
dest.writeString(this.bucket);
dest.writeString(this.mimeType);
dest.writeInt(this.giorno);
dest.writeInt(this.mese);
dest.writeInt(this.anno);
}
public FileMedia(Parcel in) {
this.path = in.readString();
this.bucket=in.readString();
this.mimeType=in.readString();
this.giorno=in.readInt();
this.mese=in.readInt();
this.anno=in.readInt();
}
public final static Parcelable.Creator <FileMedia>CREATOR = new Creator<FileMedia>() {
#Override
public FileMedia createFromParcel(Parcel source) {
return new FileMedia(source);
}
#Override
public FileMedia[] newArray(int size) {
return new FileMedia[size];
}
};}
Call activity
ListFileMedia test=new ListFileMedia();
ArrayList arrayList=new ArrayList();
test.add(new FileMedia(10,12,2016,"t","t","t"));
b.putParcelable("list",test);
intent.putExtras(b);
startActivity(intent);
Called activity
Intent intent = this.getIntent();
Bundle b=intent.getExtras();
ListFileMedia listFileMedia (ListFileMedia)b.getParcelable("list"); //size==0 !!!
But if i passed only b.putParcelable("list",new FileMedia(10,12,2016,"t","t","t") work correctely!!
Sorry for my English..
This question already has answers here:
How to pass ArrayList<CustomeObject> from one activity to another? [duplicate]
(3 answers)
Closed 7 years ago.
I try pass an object to new activity but I have a problem. My ArrayList use another class in this way:
ArrayList<ListData> myList = new ArrayList<>();
All is great, I'm adding to mList a few objects and my listview work fine.
I try pass an object after click in this way:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
ListData listdata = myList.get(position);
ListData dataToSend = new ListData();
dataToSend.setStrefa(listdata.getStrefa());
dataToSend.setDzielnica(listdata.getDzielnica());
dataToSend.setAdres(listdata.getAdres());
dataToSend.setKryteria(listdata.getKryteria());
dataToSend.setTelefon(listdata.getTelefon());
dataToSend.setData(listdata.getData());
Intent intent = new Intent(Zlecenia.this, Zlecenie.class);
intent.putExtra("myData", dataToSend);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.no_animation);
}
});
Here is a problem because "bundle.putParcelableArrayList("listdata", listdata);" is marked on red. This forces on me using extends Parcelable in ListData Class but when I added this extends then my ArrayList is empty. What schould I do?
My ListData:
public class ListData implements Parcelable{
String Strefa;
String Adres;
String Kryteria;
String Telefon;
String Data;
String Dzielnica;
String Ilosc;
/* Zlecenia */
public String getStrefa() {
return Strefa;
}
public void setStrefa(String strefa) {
this.Strefa = strefa;
}
public String getAdres() {
return Adres;
}
public void setAdres(String adres) {
this.Adres = adres;
}
public String getKryteria() {
return Kryteria;
}
public void setKryteria(String kryteria) {
this.Kryteria = kryteria;
}
public String getTelefon() {
return Telefon;
}
public void setTelefon(String telefon) {
this.Telefon = telefon;
}
public String getData() {
return Data;
}
public void setData(String data) {
this.Data = data;
}
/* Statystyki */
public String getDzielnica() {
return Dzielnica;
}
public void setDzielnica(String dzielnica) {
this.Dzielnica = dzielnica;
}
public String getIlosc() {
return Ilosc;
}
public void setIlosc(String ilosc) {
this.Ilosc = ilosc;
}
public ListData() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Strefa);
dest.writeString(Dzielnica);
dest.writeString(Adres);
dest.writeString(Kryteria);
dest.writeString(Telefon);
dest.writeString(Data);
}
private ListData(Parcel in) {
Strefa = in.readString();
Dzielnica = in.readString();
Adres = in.readString();
Kryteria = in.readString();
Telefon = in.readString();
Data = in.readString();
}
public static final Parcelable.Creator<ListData> CREATOR
= new Parcelable.Creator<ListData>() {
#Override
public ListData createFromParcel(Parcel in) {
return new ListData(in);
}
#Override
public ListData[] newArray(int size) {
return new ListData[size];
}
};
}
Try this in your class
public class ListData implements Serializable
I'm fairly new to java/android. I am attempting to pass a custom object (Raffle), which is implementing Parcelable, to another activity.
In the receiving activity I am able to access string properties of this object, but lists appear to be emptied at some point. Toasting the the list.size() in the first activity gives 3, but the same toast in the receiving activity gives 0.
Relevant code is below. Please let me know if I have left out anything.
onCLickListener in Sending Activity (HomeActivity)
raffleListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Intent intent = new Intent(HomeActivity.this,RafflePurchaseActivity.class);
Raffle selectedRaffle = (Raffle) allRaffles.get(position);
Toast.makeText(getApplicationContext(), "1: " + selectedRaffle.Description + ": " + Integer.toString(selectedRaffle.getTicketTiers().size()), Toast.LENGTH_SHORT).show();
//Toast.makeText(getApplicationContext(), "TEST: " + Integer.toString(selectedRaffle.ticketTiers.size()), Toast.LENGTH_SHORT).show();
intent.putExtra("raffle", selectedRaffle);
startActivity(intent);
}
});
Receiving Activity (RafflePurchaseActivity)
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_raffle_purchase);
Bundle bundle = this.getIntent().getExtras();
Raffle theRaffle = bundle.getParcelable("raffle");
List<RaffleTicketTier> xticketTiers = theRaffle.getTicketTiers();
Toast.makeText(getApplicationContext(), "2:" + theRaffle.Description + ": " + Integer.toString(xticketTiers.size()), Toast.LENGTH_SHORT).show();
}
the Raffle class
public class Raffle implements Parcelable {
public String Title;
public String Description;
public int TicketLimit;
public int numPrizes;
public String prize1;
public String prize2;
public String prize3;
public String prize4;
private List<RaffleTicketTier> ticketTiers = new ArrayList<RaffleTicketTier>();
public Raffle() {
Title = "Art Union";
Description = "THIS IS A RAFFLE DESCRIPTION";
ticketTiers.add(new RaffleTicketTier(1,10.00));
ticketTiers.add(new RaffleTicketTier(3,20.00));
ticketTiers.add(new RaffleTicketTier(8,50.00));
ticketTiers.add(new RaffleTicketTier(15,100.00));
testList.add("Test1");
testList.add("Test2");
testList.add("Test3");
}
//================================================================================
// Getters/Setters
//================================================================================
public List<RaffleTicketTier> getTicketTiers() {
return ticketTiers;
}
//================================================================================
// Parcelable methods
//================================================================================
//Constructor to use when re-constructing object from a parcel
public Raffle(Parcel in) {
readFromParcel(in);
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Title);
dest.writeString(Description);
dest.writeInt(TicketLimit);
dest.writeInt(numPrizes);
dest.writeString(prize1);
dest.writeString(prize2);
dest.writeString(prize3);
dest.writeString(prize4);
}
private void readFromParcel(Parcel in) {
Title= in.readString();
Description= in.readString();
TicketLimit= in.readInt();
numPrizes= in.readInt();
prize1= in.readString();
prize2= in.readString();
prize3= in.readString();
prize4= in.readString();
}
public static final Parcelable.Creator<Raffle> CREATOR = new Parcelable.Creator<Raffle>() {
public Raffle createFromParcel(Parcel in) {
return new Raffle(in);
}
public Raffle[] newArray(int size) {
return new Raffle[size];
}
};
}
You don't seem to be writing tickerTiers to the parcel. Something like this answer https://stackoverflow.com/a/10781119/156708 for parceling arrays of custom types.
Relevant code from other answer
public void writeToParcel(Parcel out, int arg1) {
out.writeInt(mObjList.length);
out.writeTypedArray(mObjList, arg1);
}
private void readFromParcel(Parcel in) {
int size = in.readInt();
mObjList = in.readTypedArray(new MyClass[size], MyClass.CREATOR);
}
Look at my code, wheather wrong in it.
Activity one:
Intent intent = new Intent(SendActivity.this, PickContactsActivity.class);
startActivityForResult(intent, 20);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
ArrayList<PickBean> cons = data.getParcelableArrayListExtra("data");
for (int i = 0; i < cons.size(); i++) {
JLog.e(LOG_TAG, "displayName:" + cons.get(i).displayName + "displayNumber" + cons.get(i).displayNumber);
}
}
}
Activity two:
Intent data = new Intent();
ArrayList<PickBean> cons = new ArrayList<PickBean>();
for (int i = 0; i < conData.size(); i++) {
cons.add(new PickBean(conData.get(i).displayName, conData.get(i).displayNumber));
}
}
data.putParcelableArrayListExtra("data", cons);
setResult(RESULT_OK, data);
finish();
The PickBean code:
public class PickBean implements Parcelable {
public String displayName;
public String displayNumber;
public boolean selected = false;
public PickBean() {
super();
}
public PickBean(String displayName, String displayNumber) {
super();
this.displayName = displayName;
this.displayNumber = displayNumber;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(displayName);
dest.writeString(displayNumber);
}
public final Parcelable.Creator<PickBean> CREATOR = new Parcelable.Creator<PickBean>() {
#Override
public PickBean createFromParcel(Parcel source) {
return new PickBean(source.readString(), source.readString());
}
#Override
public PickBean[] newArray(int size) {
return new PickBean[size];
}
};
}
It will always throws
java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=20,
result=-1, data=Intent { (has extras) }} to activity
{com.chishacai.smscenter/com.chishacai.smscenter.SendActivity}: java.lang.NullPointerException: expected receiver of type
com.chishacai.smscenter.bean.PickBean, but got null
Caused by: java.lang.NullPointerException: expected receiver of type
com.chishacai.smscenter.bean.PickBean, but got null
Please help me how to deal with this problem, thanks.
Pass the data :
Intent intent = new Intent(SendActivity.this, PickContactsActivity.class);
Bundle bundle;
bundle.putParcelableArrayList("data", cons); // Be sure con is not null here
intent.putExtras(bundle);
Get the data :
ArrayList<PickBean> arrayParents = intent.getParcelableArrayListExtra("data");
Replace you method newArray with :
public final Parcelable.Creator<PickBean> CREATOR = new Parcelable.Creator<PickBean>() {
#Override
public PickBean createFromParcel(Parcel source) {
return new PickBean(source);
}
#Override
public PickBean[] newArray(int size) {
return new PickBean[size];
}
};
public PickBean(Parcel data) {
this.displayName = data.readString();
this.displayNumber = data.readString();
}
//DataModel Class
package com.DEECOUP.DataModel;
import android.os.Parcel;
import android.os.Parcelable;
public class OrderedData implements Parcelable {
private String _title, _subtitle, _person_type, _processed_name;
private Integer _price, _quantity;
public OrderedData(String title, String subtitle , String person_type, String processed_name,
Integer price, Integer quantity)
{
_title = title;
_subtitle =subtitle ;
_person_type = person_type;
_processed_name = processed_name;
_price = price;
_quantity = quantity;
}
public OrderedData(Parcel in) {
// TODO Auto-generated constructor stub
String[] data = new String[6];
in.readStringArray(data);
_title = data[0];
_subtitle = data[1];
_person_type= data[2];
_processed_name = data[3];
_price = Integer.parseInt(data[4]);
_quantity = Integer.parseInt(data[5]);
}
public String getTitle()
{
return _title;
}
public String getSubTitle()
{
return _subtitle;
}
public String getPersonType()
{
return _person_type;
}
public String getProcessedName()
{
return _processed_name;
}
public Integer getPrice()
{
return _price;
}
public Integer getQuantity()
{
return _quantity;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeStringArray(new String[] {
this._title,
this._subtitle,
this._person_type,
this._processed_name,
String.valueOf(this._price),
String.valueOf(this._quantity)
});
}
public static final Parcelable.Creator<OrderedData> CREATOR = new Parcelable.Creator<OrderedData>() {
public OrderedData createFromParcel(Parcel in) {
return new OrderedData(in);
}
public OrderedData[] newArray(int size) {
return new OrderedData[size];
}
};
}
//button click to send data on second activity
case R.id.btnOrderDetails:
Intent intent = new Intent(SenderActiviry.this,
RecieverActivity.class);
intent.putParcelableArrayListExtra("data", orderedDataList);
startActivity(intent);
break;
// Add data to datamodel from first addtivity
global list
ArrayList<OrderedData> orderedDataList = new ArrayList<OrderedData>();
and in on create
orderedDataList.add(new OrderedData(_title, _subTitle,_person_Type, _processName,_pRice,getFinalQuantity));