I'm trying to read an object ChatMassage from the stream and to print a message (which this object contains) with its method getMassage(). It prints a message the first time but next time it always prints the first message. What is wrong?
Here is an example of the code:
while(keepGoing){
System.out.println("Client: " + ((ChatMassage) in.readObject()).getMassage() + "\n" );
}
ChatMassage class:
public class ChatMassage implements Serializable {
String msg, recipientName = null;
String senderName = "None";
public void setMassage(String msg) {
this.msg = msg;
}
public void setRecipientName(String recName) {
recipientName = recName;
}
public String getMassage() {
return msg;
}
public String getRecipientName() {
return recipientName;
}
public void setSenderName(String name) {
senderName = name;
}
public String getSenderName() {
return senderName;
}
}
I think the problem lies in this method:
public void setMassage(String msg) {
this.msg = msg;
}
I don't know if that can be a problem, but try changing the parameter to something like "new_msg". I think it confuses the "this.msg" with "msg".
Related
i have a problem and the documentations and github examples doesn't provide a clear example about how to do it....
i have this class
public class KeySerializable implements IdentifiedDataSerializable{
private String claveReq;
private int id_interno_pe;
private String cod_nrbe_en;
private int num_sec_ac;
public KeySerializable(String claveReq, int id_interno_pe, String cod_nrbe_en, int num_sec_ac) {
this.claveReq = claveReq;
this.id_interno_pe = id_interno_pe;
this.cod_nrbe_en = cod_nrbe_en;
this.num_sec_ac = num_sec_ac;
}
public KeySerializable() {
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeString(claveReq);
out.writeInt(id_interno_pe);
out.writeString(cod_nrbe_en);
out.writeInt(num_sec_ac);
}
public void readData(ObjectDataInput in) throws IOException {
this.claveReq = in.readString();
this.id_interno_pe = in.readInt();
this.cod_nrbe_en = in.readString();
this.num_sec_ac = in.readInt();
}
public int getFactoryId() {
return KeySerializableFactory.FACTORY_ID;
}
public int getClassId() {
return KeySerializableFactory.KEY_SERIALIZABLE_TYPE;
}
#Override
public String toString() {
return "KeySerializable [claveReq=" + claveReq + ", id_interno_pe=" + id_interno_pe + ", cod_nrbe_en="
+ cod_nrbe_en + ", num_sec_ac=" + num_sec_ac + "]";
}
}
and this class
public class ResponseSerializablePlus implements IdentifiedDataSerializable{
private int id_interno_pe;
private String cod_nrbe_en;
private int num_sec_ac;
private int statusCode;
private HashMap<String,List<String>> headers;
private byte[] content;
public ResponseSerializablePlus(int id_interno_pe, String cod_nrbe_en, int num_sec_ac, int statusCode,
HashMap<String, List<String>> headers, byte[] content) {
this.id_interno_pe = id_interno_pe;
this.cod_nrbe_en = cod_nrbe_en;
this.num_sec_ac = num_sec_ac;
this.statusCode = statusCode;
this.headers = headers;
this.content = content;
}
public ResponseSerializablePlus() {
}
public void writeData(ObjectDataOutput out) throws IOException {
out.writeInt(id_interno_pe);
out.writeString(cod_nrbe_en);
out.writeInt(num_sec_ac);
out.write(statusCode);
out.writeObject(headers);
out.writeByteArray(content);
}
public void readData(ObjectDataInput in) throws IOException {
this.id_interno_pe = in.readInt();
this.cod_nrbe_en = in.readString();
this.num_sec_ac = in.readInt();
this.statusCode = in.readInt();
this.headers = in.readObject();
this.content = in.readByteArray();
}
public int getFactoryId() {
return ResponseSerializablePlusFactory.FACTORY_ID;
}
public int getClassId() {
return ResponseSerializablePlusFactory.RESPONSE_SERIALIZABLE_PLUS_CLASS;
}
#Override
public String toString() {
return "ResponseSerializablePlus [id_interno_pe=" + id_interno_pe + ", cod_nrbe_en=" + cod_nrbe_en
+ ", num_sec_ac=" + num_sec_ac + ", statusCode=" + statusCode + ", headers=" + headers + ", content="
+ Arrays.toString(content) + "]";
}
and this other class
public class ResponseSerializable implements IdentifiedDataSerializable{
private int statusCode;
private HashMap<String,List<String>> headers;
private byte[] content;
public ResponseSerializable(int statusCode, HashMap<String, List<String>> headers, byte[] content) {
this.statusCode = statusCode;
this.headers = headers;
this.content = content;
}
public ResponseSerializable() {
}
public void writeData(ObjectDataOutput out) throws IOException {
out.write(statusCode);
out.writeObject(headers);
out.writeByteArray(content);
}
public void readData(ObjectDataInput in) throws IOException {
this.statusCode = in.readInt();
this.headers = in.readObject();
this.content = in.readByteArray();
}
public int getFactoryId() {
return ResponseSerializableFactory.FACTORY_ID;
}
public int getClassId() {
return ResponseSerializableFactory.RESPONSE_TYPE;
}
#Override
public String toString() {
return "ResponseSerializable [statusCode=" + statusCode + ", headers=" + headers + ", content="
+ Arrays.toString(content) + "]";
}
}
and the factory it's always the same but with different classes
public class KeySerializableFactory implements DataSerializableFactory{
public static final int FACTORY_ID = 1;
public static final int KEY_SERIALIZABLE_TYPE = 1;
public IdentifiedDataSerializable create(int typeId) {
if ( typeId == KEY_SERIALIZABLE_TYPE ) {
return new KeySerializable();
} else {
return null;
}
}
}
and im always having this bunch errors
the documentation and the github examples from hazelcast doesn't provide a good example about how to use the getters and setters and i don't understand what to do here to write or read an object
any hint? can you help me?
You shouldn't be calling readData or writeData yourself. These methods are called by Hazelcast internally when the data is about to be serialized/deserialized.
On your side, you should only register the data serializable factories you have created to the Hazelcast.
Then, upon receiving an instance of a class that implements IdentifiedDataSerializable and has a factory registered for it, Hazelcast will call the methods I mentioned above in appropriate places and return you the object read.
From the code sample you shared, you need to drop the line starting with newResponse.writeData(..., and everything should be working, assuming you did the factory registration.
Also, please fix your ResponseSerializablePlus and ResponseSerializable classes: You need to use writeInt method to write the statusCode field. The readData and writeData methods should be consistent with each other.
This Is Main Fragment
Fragment:
private void getStock() {
dialog.show();
Retrofit retrofit = RetrofitClient.getRetrofitInstance();
apiInterface api = retrofit.create(apiInterface.class);
Call<List<Blocks>>call = api.getVaccineBlocks();
call.enqueue(new Callback<List<Blocks>>() {
#Override
public void onResponse(Call<List<Blocks>>call, Response<List<Blocks>> response) {
if (response.code() == 200) {
block = response.body();
spinnerada();
dialog.cancel();
}else{
dialog.cancel();
}
}
#Override
public void onFailure(Call<List<Blocks>> call, Throwable t) {
dialog.cancel();
}
});
}
private void spinnerada() {
String[] s = new String[block.size()];
for (int i = 0; i < block.size(); i++) {
s[i] = block.get(i).getBlockName();
final ArrayAdapter a = new ArrayAdapter(getContext(), android.R.layout.simple_spinner_item, s);
a.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//Setting the ArrayAdapter data on the Spinner
spinner.setAdapter(a);
}
}
This Is Blocks Model
model:
package com.smmtn.book.models;
import java.io.Serializable;
public class Blocks implements Serializable {
public String id;
public String blockName;
public String blockSlug;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getBlockName() {
return blockName;
}
public void setBlockName(String blockName) {
this.blockName = blockName;
}
public String getBlockSlug() {
return blockSlug;
}
public void setBlockSlug(String blockSlug) {
this.blockSlug = blockSlug;
}
}
here i need onitemclick with blockslug please any one can help, am new to android so i need some example.when on click i want take blockslug and load another method with that blockslug,like will get data from u "http://example.com/block/"+blockslug
i want to get blockslug from selected block
i hope guys i will get help
and sorry for my bad English,
First of all, you need to implement setOnItemSelectedListener. Refer to this https://stackoverflow.com/a/20151596/9346054
Once you selected the item, you can call them by making a new method. Example like below
public void onItemSelected(AdapterView<?> parent, View view, int pos,long id) {
Toast.makeText(parent.getContext(),
"OnItemSelectedListener : " + parent.getItemAtPosition(pos).toString(),
Toast.LENGTH_SHORT).show();
final String itemSelected = parent.getItemAtPosition(pos).toString();
showBlockSlug(itemSelected);
}
And then, at the method showBlockSlug() , you can call Retrofit.
private void showBlockSlug(final String blockslug){
final String url = "http://example.com/block/"+ blockslug;
//Do your stuff...
}
This is my CartAdapter I called GetCart function in this adapter my function is calling successfully but my orgmst id and userid going null to database.
quantity.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
new GetUpdateQuantity().execute();
TwoFragment fragment = new TwoFragment();
fragment.Getcart();
if (quantity.length() == 0) {
} else {
quan = Double.parseDouble(quantity.getText().toString());
rate = Double.parseDouble(rate1.getText().toString());
total1 = Double.parseDouble(String.valueOf(rate * quan));
// convert double to string to get value
String show = Double.toString(total1);
//show in Textview
total.setText(show);
Log.d("<<<hcvyd", "" + show);
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
----------
In myfragment i create method to send data to webservice this method i call in GetCart function then this function call inside adapter
MyFragment
'''GetCart Function'''
public void Getcart(){
String gh = orgmstid;
String hj = userid;
new GetCartItems().execute();
}
private class GetCartItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
String jsonStr = sh.makeServiceCall("VIEW_CART", "F", "" + 'N' + "~" + orgmstid + "~" + userid);
Code for background CAll
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
import android.util.Log;
public class DownloadFileFromURL extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... f_url) {
try {
URL url = new URL(f_url[0]);
URLConnection conection = url.openConnection();
conection.connect();
InputStream input = new BufferedInputStream(url.openStream(), 8192);
byte data[] = new byte[1024];
String file_string = "";
while ((count = input.read(data)) != -1) {
for (int i = 0; i < count; i++) {
file_string += (char) data[i];
}
}
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
protected void onProgressUpdate(String... progress) {
// pDialog.setProgress(Integer.parseInt(progress[0]));
}
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
}
}
Code for calling
new DownloadFileFromURL().execute("URL");
long story short, I have one settlementItemeBase class as my father and two children. I want to make the father class parcelable so as extension happens, my two child classes be parcelable as well. I don't exactly know what I'm doing right or wrong. I searched little bit but nothing helped me.
here are my classes:
SettlementItemBase:
public class SettlementItemBase implements Parcelable{
public SettlementItemBase(){}
protected SettlementItemBase(Parcel in) {
}
public static final Creator<SettlementItemBase> CREATOR = new Creator<SettlementItemBase>() {
#Override
public SettlementItemBase createFromParcel(Parcel in) {
return new SettlementItemBase(in);
}
#Override
public SettlementItemBase[] newArray(int size) {
return new SettlementItemBase[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
}
}
first child class:
public class FirstClass extends SettlementItemBase {
private int id;
private int cardId;
private String cardNumber;
private String expDate;
private String currency;
private String url;
public FirstClass(){
id = 0;
cardId = 0;
cardNumber = "";
expDate = "";
currency = "";
url = "";
}
protected FirstClass(Parcel in) {
super(in);
id = in.readInt();
cardId = in.readInt();
cardNumber = in.readString();
expDate = in.readString();
currency = in.readString();
url = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeInt(cardId);
dest.writeString(cardNumber);
dest.writeString(expDate);
dest.writeString(currency);
dest.writeString(url);
}
public int getId() {
return id;
}
public int getCardId() {
return cardId;
}
public String getCardNumber() {
return cardNumber;
}
public String getExpDate() {
return expDate;
}
public String getCurrency() {
return currency;
}
public String getUrl() {
return url;
}
}
second child class:
public class SecondClass extends SettlementItemBase{
private int id;
private String currency;
private String accountNumber;
private String ibanNumber;
public SecondClass(int id, String currency,
String accountNumber, String ibanNumber){
this.id = id;
this.currency = currency;
this.accountNumber = accountNumber;
this.ibanNumber = ibanNumber;
}
protected SecondClass(Parcel in){
super(in);
id = in.readInt();
currency = in.readString();
accountNumber = in.readString();
ibanNumber = in.readString();
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(id);
dest.writeString(currency);
dest.writeString(accountNumber);
dest.writeString(ibanNumber);
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCurrency() {
return currency;
}
public String getAccountNumber() {
return accountNumber;
}
public String getIbanNumber() {
return ibanNumber;
}
}
I'm passing and getting an ArrayList of both child class' items with intent putParcelableArrayListExtra and getParcelableArrayListExtra methods and get the following error:
Parcel android.os.Parcel#2d0fde33: Unmarshalling unknown type code 3276849 at offset 172
any help would be appreciated 3>
well I'm posting this for those who may run into the same problem as me.
the problem was solved after adding the Creator statement to the child classes.
for one of the child classes it would be like:
public static final Creator<FirstClass> CREATOR = new Creator<FirstClass>() {
#Override
public FirstClass createFromParcel(Parcel in) {
return new FirstClass(in);
}
#Override
public FirstClass[] newArray(int size) {
return new FirstClass[size];
}
};
hope this helps. 3>
my json data is this
{
"data":[
{
"id":"4",
"totalOpns":"40000",
"killedDrugPer":"320",
"arrestedDrugPer":"17683",
"houseVisited":"4000",
"userSurrenderers":"45000",
"pusherSurrenderers":"15000",
"totalSurrenderers":"60000",
"killedPNPPerOpns":"40",
"woundedPNPPerOpns":"70",
"killedAFPPerOpns":"100",
"woundedAFPPerOpns":"10",
"date":"2017-07-12 13:57:34.000"
}
]
}
and my data model is this
package com.androidtutorialpoint.retrofitandroid;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import java.io.Serializable;
public class Student implements Serializable {
//Variables that are in our json
#SerializedName("id")
#Expose
private String id;
#SerializedName("totalOpns")
#Expose
private String totalOpns;
#SerializedName("killedDrugPer")
#Expose
private String killedDrugPer;
#SerializedName("arrestedDrugPer")
#Expose
private String arrestedDrugPer;
#SerializedName("houseVisited")
#Expose
private String houseVisited;
#SerializedName("userSurrenderers")
#Expose
private String userSurrenderers;
#SerializedName("pusherSurrenderers")
#Expose
private String pusherSurrenderers;
#SerializedName("totalSurrenderers")
#Expose
private String totalSurrenderers;
#SerializedName("killedPNPPerOpns")
#Expose
private String killedPNPPerOpns;
#SerializedName("woundedPNPPerOpns")
#Expose
private String woundedPNPPerOpns;
#SerializedName("killedAFPPerOpns")
#Expose
private String killedAFPPerOpns;
#SerializedName("woundedAFPPerOpns")
#Expose
private String woundedAFPPerOpns;
#SerializedName("date")
#Expose
private String date;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTotalOpns() {
return totalOpns;
}
public void setTotalOpns(String totalOpns) {
this.totalOpns = totalOpns;
}
public String getKilledDrugPer() {
return killedDrugPer;
}
public void setKilledDrugPer(String killedDrugPer) {
this.killedDrugPer = killedDrugPer;
}
public String getArrestedDrugPer() {
return arrestedDrugPer;
}
public void setArrestedDrugPer(String arrestedDrugPer) {
this.arrestedDrugPer = arrestedDrugPer;
}
public String getHouseVisited() {
return houseVisited;
}
public void setHouseVisited(String houseVisited) {
this.houseVisited = houseVisited;
}
public String getUserSurrenderers() {
return userSurrenderers;
}
public void setUserSurrenderers(String userSurrenderers) {
this.userSurrenderers = userSurrenderers;
}
public String getPusherSurrenderers() {
return pusherSurrenderers;
}
public void setPusherSurrenderers(String pusherSurrenderers) {
this.pusherSurrenderers = pusherSurrenderers;
}
public String getTotalSurrenderers() {
return totalSurrenderers;
}
public void setTotalSurrenderers(String totalSurrenderers) {
this.totalSurrenderers = totalSurrenderers;
}
public String getKilledPNPPerOpns() {
return killedPNPPerOpns;
}
public void setKilledPNPPerOpns(String killedPNPPerOpns) {
this.killedPNPPerOpns = killedPNPPerOpns;
}
public String getWoundedPNPPerOpns() {
return woundedPNPPerOpns;
}
public void setWoundedPNPPerOpns(String woundedPNPPerOpns) {
this.woundedPNPPerOpns = woundedPNPPerOpns;
}
public String getKilledAFPPerOpns() {
return killedAFPPerOpns;
}
public void setKilledAFPPerOpns(String killedAFPPerOpns) {
this.killedAFPPerOpns = killedAFPPerOpns;
}
public String getWoundedAFPPerOpns() {
return woundedAFPPerOpns;
}
public void setWoundedAFPPerOpns(String woundedAFPPerOpns) {
this.woundedAFPPerOpns = woundedAFPPerOpns;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
and the interface is this
package com.androidtutorialpoint.retrofitandroid;
import retrofit2.Call;
import retrofit2.http.GET;
public interface RetrofitObjectAPI {
/*
* Retrofit get annotation with our URL
* And our method that will return us details of student.
*/
// #GET("JSONTESTING/index.php")
#GET("getJson")
Call<Student> getStudentDetails();
}
and in my main is this
private void getRetrofitObject() {
HttpLoggingInterceptor.Level logLevel = HttpLoggingInterceptor.Level.BODY;
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
// set your desired log level
logging.setLevel(logLevel);
OkHttpClient.Builder httpClient = new OkHttpClient.Builder();
// add your other interceptors …
// add logging as last interceptor
httpClient.addInterceptor(logging); // <-- this is the important line!
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient.build())
.build();
RetrofitObjectAPI service = retrofit.create(RetrofitObjectAPI.class);
Call<Student> call = service.getStudentDetails();
call.enqueue(new Callback<Student>() {
#Override
public void onResponse(Call<Student> call, Response<Student> response) {
try {
if (response.isSuccessful()) {
text_id_1.setText("StudentId : " + response.body().getId());
text_name_1.setText("StudentName : " + response.body().getTotalOpns());
text_marks_1.setText("StudentMarks : " + response.body().getArrestedDrugPer());
} else {
//unsuccessful response
}
} catch (Exception e) {
Log.d("onResponse", "There is an error");
e.printStackTrace();
}
}
#Override
public void onFailure(Call<Student> call, Throwable t) {
Log.d("onFailure", t.toString());
}
});
}
and in my logcat is this, i can see the json data but on my response.body returns null.
logcat
What should I do?
You are getting a response but there is issue in deserialization.
Reason being the Call<Student> is not the type it will be serialized to becuase you are getting a List of Students(JSONArray).
add this class
MyResponse
public class MyResponse {
#SerializedName("data")
#Expose
private List<Student> data = null;
public List<Student> getData() {
return data;
}
public void setData(List<Student> data) {
this.data = data;
}
}
and change your call to:
#GET("getJson")
Call<MyResponse> getStudentDetails();
Now you will get response body
and how to retrive?
List<Student> students = response.body().getData();
This will do..:)