I am integrating Citrus wallet in my company's app and am stuck on the following error.
the stack trace:
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:304)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
Caused by: java.lang.NumberFormatException: Invalid double: "["5.0","5.0"]"
at java.lang.StringToReal.invalidReal(StringToReal.java:63)
at java.lang.StringToReal.initialParse(StringToReal.java:164)
at java.lang.StringToReal.parseDouble(StringToReal.java:282)
at java.lang.Double.parseDouble(Double.java:301)
at com.citrus.sdk.classes.Amount.getValueAsDouble(Amount.java:65)
at com.citrus.sdk.payment.PaymentBill.<init>(PaymentBill.java:90)
at com.citrus.sdk.payment.PaymentBill.fromJSON(PaymentBill.java:261)
at com.citrus.sdk.GetJSONBill.doInBackground(GetJSONBill.java:70)
at com.citrus.sdk.GetJSONBill.doInBackground(GetJSONBill.java:22)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:818)
This is the java code. The error occurs after Yes is clicked in the Dialog Box:
public class FragmentWallet extends DialogFragment implements View.OnClickListener {
private Context mContext;
private int balance = 1200;
Button proceed;
TextView textView;
TextView log;
TextView user_bal;
CitrusClient citrusClient;
Message text;
Amount amount = new Amount("5.0");
private String BILL_URL = "my_url"
private WalletFragmentListener mListener;
String msg;
public FragmentWallet() {
}
public FragmentWallet(Context mContext) {
this.mContext = mContext;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.wallet_screen, container, false);
textView = (TextView) rootView.findViewById(R.id.user_email);
log = (TextView) rootView.findViewById(R.id.logout);
user_bal=(TextView) rootView.findViewById(R.id.user_balance);
proceed = (Button) rootView.findViewById(R.id.proceed_citrus);
msg = PaymentDialogFragment.getCitrusClientInstance().getUserEmailId();
proceed.setOnClickListener(this);
log.setOnClickListener(this);
textView.setText(msg);
return rootView;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.proceed_citrus:
onCreateDialog();
break;
case R.id.logout:
onLogout();
break;
}
}
public void onCreateDialog() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(mContext);
builder1.setMessage("Are you sure you want to proceed?");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//dialog.cancel();
payUsingNewCash();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
private void payUsingNewCash() {
Log.d("inside", "payUsingNewCash");
checkBalance();
}
private void checkBalance() {
Log.d("inside", "payUsingNewCash");
PaymentDialogFragment.getCitrusClientInstance().getBalance(new Callback<Amount>() {
#Override
public void success(Amount amount) {
//get balance amount . for now balance is hardcoded to 1200
double bal=(Double)amount.getValueAsDouble();
user_bal.setText("Your current balance is Rs."+bal);
if (bal >50) {
Toast.makeText(mContext,"balance is "+bal, Toast.LENGTH_LONG).show();
//proceed with payment
proceedWithPayment();
Log.d("inside", "payUsingNewCash");
} else {
LoadMoney loadMoney=new LoadMoney(mContext);
FragmentManager fm=getFragmentManager();
loadMoney.show(fm,null);
}
}
#Override
public void error(CitrusError error) {
Toast.makeText(mContext,"balance is not available. Please try again",Toast.LENGTH_LONG).show();
}
});
}
public void proceedWithPayment() {
// Toast.makeText(mContext,"balance is not available. Please try again",Toast.LENGTH_LONG).show();
Log.d("TAG","inside Proceed");
try {
Log.d("TAG","inside try");
PaymentDialogFragment.getCitrusClientInstance().prepaidPay(new PaymentType.CitrusCash(amount,BILL_URL),new Callback<PaymentResponse>() {
#Override
public void success(PaymentResponse paymentResponse) {
Log.d("TAG","inside success");
Toast.makeText(mContext,"Successful",Toast.LENGTH_LONG).show();
}
#Override
public void error(CitrusError citrusError) {
Log.d("TAG", citrusError.getMessage());
Toast.makeText(mContext,"Not successful.",Toast.LENGTH_LONG).show();
}
});Log.d("TAG","++");
} catch (CitrusException e) {
Log.d("Tag",e.toString());
e.printStackTrace();
}
}
public void onLogout(){
getDialog().dismiss();
PaymentDialogFragment.getCitrusClientInstance().signOut(new Callback<CitrusResponse>()
{
#Override
public void success(CitrusResponse citrusResponse) {
UserManagementFragment userManagementFragment = new UserManagementFragment(mContext);
FragmentManager fm=getFragmentManager();
userManagementFragment.show(fm,null);
}
#Override
public void error(CitrusError error) {
}
});
}
}
The method Amount.getValueAsDouble():
public double getValueAsDouble() throws NumberFormatException {
double value = 0.0D;
if(!TextUtils.isEmpty(this.value)) {
value = Double.parseDouble(this.value);
}
return value;
}
The entire amount class:
public class Amount implements Parcelable {
private final String value;
private final String currency;
public static final Creator<Amount> CREATOR = new Creator() {
public Amount createFromParcel(Parcel source) {
return new Amount(source, null);
}
public Amount[] newArray(int size) {
return new Amount[size];
}
};
public Amount(String value) {
this.value = value;
this.currency = "INR";
}
public Amount(String value, String currency) {
this.value = value;
this.currency = currency;
}
public String getValue() {
return !TextUtils.isEmpty(this.value)?this.value.replaceFirst("^0+(?!$)", ""):this.value;
}
public String getCurrency() {
return this.currency;
}
public String getValueAsFormattedDouble(String format) throws NumberFormatException {
DecimalFormat df = new DecimalFormat(format);
return df.format(this.getValueAsDouble());
}
public double getValueAsDouble() throws NumberFormatException {
double value = 0.0D;
if(!TextUtils.isEmpty(this.value)) {
value = Double.parseDouble(this.value);
}
return value;
}
public static Amount fromJSON(String response) {
Amount amount = null;
JSONObject jsonObject = null;
if(!TextUtils.isEmpty(response)) {
try {
jsonObject = new JSONObject(response);
amount = fromJSONObject(jsonObject);
} catch (JSONException var4) {
var4.printStackTrace();
}
}
return amount;
}
public static Amount fromJSONObject(JSONObject amountObject) {
Amount amount = null;
if(amountObject != null) {
String value = amountObject.optString("value");
String currency = amountObject.optString("currency");
if(!TextUtils.isEmpty(value) && !TextUtils.isEmpty(currency)) {
amount = new Amount(value, currency);
}
}
return amount;
}
public static String toJSON(Amount amount) {
JSONObject billObject = toJSONObject(amount);
return billObject != null?billObject.toString():null;
}
public static JSONObject toJSONObject(Amount amount) {
JSONObject billObject = null;
if(amount != null) {
try {
billObject = new JSONObject();
billObject.put("value", amount.value);
billObject.put("currency", amount.currency);
} catch (JSONException var3) {
var3.printStackTrace();
}
}
return billObject;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(this.value);
dest.writeString(this.currency);
}
private Amount(Parcel in) {
this.value = in.readString();
this.currency = in.readString();
}
public String toString() {
return "Amount{value=\'" + this.value + '\'' + ", currency=\'" + this.currency + '\'' + '}';
}
public int hashCode() {
return super.hashCode();
}
public boolean equals(Object o) {
if(this == o) {
return true;
} else if(!(o instanceof Amount)) {
return false;
} else {
Amount amount = (Amount)o;
return this.getValueAsDouble() == amount.getValueAsDouble() && this.currency.equalsIgnoreCase(amount.getCurrency());
}
}
}
Any help will be highly appreciated
Seems you get in your json array of doubles? Am i right?
`"["5.0","5.0"]"`
please check if your json is correct and if array parse as array of doubles instead of as one double value.
Related
Can any one help me whats wrong in my code
unable to save ArrayList document value in shared Preference
getting null value in Debug of Array List Document
please help me
Thanks in advance
here is my JSON response
{
"errCode": 0,
"message": "Success",
"responseDestinationDocument": [
{
"name": "United Arab Emirates",
"document": [
{
"name": "Passport Front",
"id": "2",
"notes": [
{
"name": "Upload colored passport copies."
},
{
"name": "Passport should be valid 6 months from the date of entry in Sri Lanka."
},
{
"name": "DDDDDDD"
}
]
},
{
"name": "Passport Back",
"id": "3",
"notes": [
{
"name": "Upload colored passport copy."
}
]
},
{
"name": "Photograph",
"id": "4",
"notes": [
{
"name": "Upload photograph with white background"
}
]
}
]
}
]
}
I want to save ArrayList document value in shared Preference
Here is activity code
public class UploadDocumentsActivity extends AppCompatActivity {
private MyCustomAdapter myCustomAdapter;
protected ViewDialog viewDialog;
String destination_id, start_date, end_date, no_of_travellers, destination_name, package_id, radioSexButton, booking_id, count_index;
private List<ResponseBookingDocument> responseBookingDocumentArrayList;
private List<Document> document1ArrayList;
Document document1;
private RecyclerView recyclerView_Identity;
private static final int SELECT_PICTURE = 100;
private static final int STORAGE_PERMISSION_CODE = 123;
final Handler handler = new Handler();
final int delay = 1000; //milliseconds
private ImageView imageView1;
String selectedImagePath;
private Uri filePath_1;
private boolean isOnTag = false;
Bitmap bitmap;
preivate ArrayList<String> nameList = new ArrayList<>();
preivate ArrayList<String> idList = new ArrayList<>();
TextView continueTextView;
private Runnable mToast = new Runnable() {
#Override
public void run() {
// documentRequiredCall();
handler.postDelayed(this, 1000);
}
};
ResponseBookInfo responseBookInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_documents);
viewDialog = new ViewDialog(this);
viewDialog.setCancelable(false);
// Log.e("document1", document1.getId() + "");
try {
document1 = PrefUtils.getDocId(UploadDocumentsActivity.this);
Log.e("document1", document1.getId() + "");
} catch (Exception e) {
e.printStackTrace();
}
Intent i = getIntent();
destination_id = i.getStringExtra("destination_id");
package_id = i.getStringExtra("package_id");
radioSexButton = i.getStringExtra("radioSexButton");
booking_id = i.getStringExtra("booking_id");
count_index = i.getStringExtra("count_index");
Log.e("BookING", booking_id + "");
destination_name = i.getStringExtra("destination_name");
start_date = i.getStringExtra("start_date");
end_date = i.getStringExtra("end_date");
no_of_travellers = i.getStringExtra("no_of_travellers");
recyclerView_Identity = findViewById(R.id.recyclerView_Identity);
continueTextView = findViewById(R.id.continueTextView);
LinearLayoutManager layoutManager = new LinearLayoutManager(UploadDocumentsActivity.this);
layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView_Identity.setLayoutManager(layoutManager);
recyclerView_Identity.setHasFixedSize(true);
continueTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(UploadDocumentsActivity.this, ApplicationFormActivity.class);
i.putExtra("booking_id", booking_id);
i.putExtra("count_index", count_index);
i.putExtra("start_date", start_date);
i.putExtra("end_date", end_date);
startActivity(i);
}
});
documentRequiredCall();
//
Log.e("Values", destination_id + " " + package_id + " " + end_date + " " + no_of_travellers + " " + count_index + "");
}
public void documentRequiredCall() {
Call<DocumentFetchModel> call = RetrofitClient
.getInstance().getApi().documentFetchModel(booking_id, count_index);
showProgressDialog();
call.enqueue(new Callback<DocumentFetchModel>() {
#Override
public void onResponse(Call<DocumentFetchModel> call, retrofit2.Response<DocumentFetchModel> response) {
final DocumentFetchModel documentFetchModel = response.body();
hideProgressDialog();
PrefUtils.setDocId(documentFetchModel.getResponseBookingDocument().get(0).getDocument(), UploadDocumentsActivity.this);
int size = documentFetchModel.getResponseBookingDocument().get(0).getDocument().size();
for (int i = 0; i < size; i++) {
nameList.add(documentFetchModel.getResponseBookingDocument().get(0).getDocument().get(i).getName());
idList.add(documentFetchModel.getResponseBookingDocument().get(0).getDocument().get(i).getId());
}
//here is app preference class saving the values
AppPreference.setNameList(this, nameList);
AppPreference.setIdList(this, idLIst);
if (documentFetchModel.getErrCode().booleanValue() == true) {
responseBookingDocumentArrayList = new ArrayList<ResponseBookingDocument>();
try {
Log.e("Booking_Document", new Gson().toJson(response.body()));
document1ArrayList = documentFetchModel.getResponseBookingDocument().get(0).getDocument();
myCustomAdapter = new MyCustomAdapter(document1ArrayList);
recyclerView_Identity.setAdapter(myCustomAdapter);
myCustomAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(UploadDocumentsActivity.this, documentFetchModel.getMessage() + "", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<DocumentFetchModel> call, Throwable t) {
hideProgressDialog();
Toast.makeText(UploadDocumentsActivity.this, t.getMessage() + "", Toast.LENGTH_LONG).show();
Log.e("Error", t.getMessage() + "");
}
});
}
protected void hideProgressDialog() {
viewDialog.dismiss();
}
protected void showProgressDialog() {
viewDialog.show();
}
protected void showProgressDialog(String message) {
showProgressDialog();
}
public class MyCustomAdapter extends RecyclerView.Adapter<MyCustomAdapter.MyViewHolder> {
private List<Document> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView textTitle;
public ImageView imageUpload, imageFetch;
private List<Note> noteArrayList;
private MyCustomAdapter2 myCustomAdapter2;
private RecyclerView recyclerView_Identity_Bullets;
public MyViewHolder(View view) {
super(view);
textTitle = view.findViewById(R.id.textTitle);
imageUpload = view.findViewById(R.id.imageUpload);
imageFetch = view.findViewById(R.id.imageFetch);
recyclerView_Identity_Bullets = view.findViewById(R.id.recyclerView_Identity_Bullets);
LinearLayoutManager layoutManager2 = new LinearLayoutManager(UploadDocumentsActivity.this);
layoutManager2.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView_Identity_Bullets.setLayoutManager(layoutManager2);
recyclerView_Identity_Bullets.setHasFixedSize(true);
}
}
public MyCustomAdapter(List<Document> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_upload_document, parent, false);
return new MyCustomAdapter.MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public void onBindViewHolder(final MyViewHolder holder, final int position) {
final Document datum = moviesList.get(position);
holder.textTitle.setText(datum.getName() + "");
holder.noteArrayList = datum.getNotes();
holder.myCustomAdapter2 = new MyCustomAdapter2(holder.noteArrayList);
holder.recyclerView_Identity_Bullets.setAdapter(holder.myCustomAdapter2);
if (datum.getImageName().equals("")) {
holder.imageFetch.setVisibility(View.GONE);
holder.imageUpload.setVisibility(View.VISIBLE);
holder.imageUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(UploadDocumentsActivity.this, datum.getId(), Toast.LENGTH_SHORT).show();
}
});
} else {
holder.imageUpload.setVisibility(View.GONE);
holder.imageFetch.setVisibility(View.VISIBLE);
Picasso.with(UploadDocumentsActivity.this).load(datum.getImageName() + "").into(holder.imageFetch);
}
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
public class MyCustomAdapter2 extends RecyclerView.Adapter<MyCustomAdapter2.MyViewHolder> {
private List<Note> moviesList;
public class MyViewHolder extends RecyclerView.ViewHolder {
public TextView textBullet;
public MyViewHolder(View view) {
super(view);
textBullet = view.findViewById(R.id.textBullet);
}
}
public MyCustomAdapter2(List<Note> moviesList) {
this.moviesList = moviesList;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_upload_bullets_and_image, parent, false);
return new MyViewHolder(itemView);
}
public void clear() {
int size = this.moviesList.size();
if (size > 0) {
for (int i = 0; i < size; i++) {
this.moviesList.remove(0);
}
this.notifyItemRangeRemoved(0, size);
}
}
#Override
public void onBindViewHolder(MyViewHolder holder, final int position) {
final Note datum = moviesList.get(position);
holder.textBullet.setText(" \u25CF " + datum.getName() + "");
Log.e("textBullet", datum.getName() + "");
}
#Override
public int getItemCount() {
return moviesList.size();
}
}
#Override
public void onStart() {
super.onStart();
mToast.run();
}
#Override
public void onStop() {
super.onStop();
handler.removeCallbacks(mToast);
}
}
Here is Model Class
public class DocumentFetchModel {
#SerializedName("errCode")
#Expose
private Boolean errCode;
#SerializedName("message")
#Expose
private String message;
#SerializedName("responseBookingDocument")
#Expose
private List<ResponseBookingDocument> responseBookingDocument = null;
public Boolean getErrCode() {
return errCode;
}
public void setErrCode(Boolean errCode) {
this.errCode = errCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<ResponseBookingDocument> getResponseBookingDocument() {
return responseBookingDocument;
}
public void setResponseBookingDocument(List<ResponseBookingDocument> responseBookingDocument) {
this.responseBookingDocument = responseBookingDocument;
}
}
public class ResponseBookingDocument {
#SerializedName("name")
#Expose
private String name;
#SerializedName("document")
#Expose
private List<Document> document = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Document> getDocument() {
return document;
}
public void setDocument(List<Document> document) {
this.document = document;
}
}
public class DocumentFetchModel {
#SerializedName("errCode")
#Expose
private Boolean errCode;
#SerializedName("message")
#Expose
private String message;
#SerializedName("responseBookingDocument")
#Expose
private List<ResponseBookingDocument> responseBookingDocument = null;
public Boolean getErrCode() {
return errCode;
}
public void setErrCode(Boolean errCode) {
this.errCode = errCode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<ResponseBookingDocument> getResponseBookingDocument() {
return responseBookingDocument;
}
public void setResponseBookingDocument(List<ResponseBookingDocument> responseBookingDocument) {
this.responseBookingDocument = responseBookingDocument;
}
}
Here is ComplexPreference
public class ComplexPreferences {
private static ComplexPreferences complexPreferences;
private Context context;
private SharedPreferences preferences;
private SharedPreferences.Editor editor;
private static Gson GSON = new Gson();
Type typeOfObject = new TypeToken<Object>() {
}.getType();
private ComplexPreferences(Context context, String namePreferences, int mode) {
this.context = context;
if (namePreferences == null || namePreferences.equals("")) {
namePreferences = "complex_preferences";
}
preferences = context.getSharedPreferences(namePreferences, mode);
editor = preferences.edit();
}
public static ComplexPreferences getComplexPreferences(Context context,
String namePreferences, int mode) {
// if (complexPreferences == null) {
complexPreferences = new ComplexPreferences(context,
namePreferences, mode);
// }
return complexPreferences;
}
public void putObject(String key, Object object) {
if(object == null){
throw new IllegalArgumentException("object is null");
}
if(key.equals("") || key == null){
throw new IllegalArgumentException("key is empty or null");
}
editor.putString(key, GSON.toJson(object));
}
public void commit() {
editor.commit();
}
public void clearObject() {
editor.clear();
}
public <T> T getObject(String key, Class<T> a) {
String gson = preferences.getString(key, null);
if (gson == null) {
return null;
} else {
try{
return GSON.fromJson(gson, a);
} catch (Exception e) {
throw new IllegalArgumentException("Object storaged with key " + key + " is instanceof other class");
}
}
}
}
Here is PrefUtils Class
public class PrefUtils {
public static DocumentFetchModel getDoc(Context ctx) {
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(ctx, "get_doc", 0);
DocumentFetchModel currentUser = complexPreferences.getObject("docs", DocumentFetchModel.class);
return currentUser;
}
public static void setDoc(DocumentFetchModel currentUser, Context ctx) {
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(ctx, "get_doc", 0);
complexPreferences.putObject("docs", currentUser);
complexPreferences.commit();
}
}
you can save list in sharedpreference like this:-
public class AppPreferences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static Set<String> getName(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getStringSet("nameList", null);
}
public static void setName(Context ctx, ArrayList<String> value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
Set<String> set = new HashSet<>();
set.addAll(value);
mPrefsEditor.putStringSet("nameList", set);
mPrefsEditor.commit();
}
public static void clearNameList(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
Set<String> set = new HashSet<>();
mPrefsEditor.putStringSet("nameList", set);
mPrefsEditor.commit();
}
}
to set list :-
setCamEval(activity, list);
to get list :-
getCamEval(this);
I have a FirebaseRecyclerAdapter fetching data from the firebase database but when I am trying to access firebase data the getter method of the POJO returns null. I am able to get the database reference key.
final Query beveragesQuery = mDatabaseReference.child(FirebaseValues.PRODUCTS)
.child(FirebaseValues.BEVERAGES);
FirebaseRecyclerOptions<GenericProductModel> beveragesOptions =
new FirebaseRecyclerOptions.Builder<GenericProductModel>()
.setQuery(beveragesQuery, GenericProductModel.class)
.build();
adapter = new FirebaseRecyclerAdapter<GenericProductModel, Combos.MovieViewHolder>(
beveragesOptions
) {
#NonNull
#Override
public Combos.MovieViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cards_cardview_layout, parent, false);
return new Combos.MovieViewHolder(view);
}
#Override
protected void onBindViewHolder(#NonNull Combos.MovieViewHolder viewHolder, int position, #NonNull GenericProductModel model) {
Log.d(TAG, "Item received:"+getRef(position).getKey());
String json = new Gson().toJson(model);
Log.d(TAG, "Item received:"+ json);
Log.d(TAG, "Item received:"+ model.toString());
if (tv_no_item.getVisibility() == View.VISIBLE) {
tv_no_item.setVisibility(View.GONE);
}
Log.d(TAG, "card name:"+model.getCardname());
viewHolder.cardname.setText(model.getCardname());
viewHolder.cardprice.setText("₹ " + Float.toString(model.getCardprice()));
Picasso.get().load(model.getCardimage()).into(viewHolder.cardimage);
viewHolder.mView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Beverages.this, IndividualProduct.class);
intent.putExtra("product", getItem(position));
startActivity(intent);
}
});
}
#Override
public void onError(DatabaseError e) {
Log.e(TAG, "RV Adapter, Error occurred: " + e.getMessage());
}
};
mLayoutManager = new StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL);
mRecyclerView.setLayoutManager(mLayoutManager);
adapter.startListening();
mRecyclerView.setAdapter(adapter);
}
My POJO or model class is
public class GenericProductModel implements Serializable {
public int cardid;
public String cardname;
public String cardimage;
public String carddescription;
public float cardprice;
public GenericProductModel() {
}
public GenericProductModel(int cardid, String cardname, String cardimage, String carddescription, float cardprice) {
this.cardid = cardid;
this.cardname = cardname;
this.cardimage = cardimage;
this.carddescription = carddescription;
this.cardprice = cardprice;
}
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
public void setCardid(int cardid) {
this.cardid = cardid;
}
public void setCardname(String cardname) {
this.cardname = cardname;
}
public void setCardimage(String cardimage) {
this.cardimage = cardimage;
}
public void setCarddescription(String carddescription) {
this.carddescription = carddescription;
}
public void setCardprice(float cardprice) {
this.cardprice = cardprice;
}
}
I am implementing Serializable because I am sending this data as an intent to other activity.
Added some more log options for clearity
When I run the app the log output I am getting is:
03-17 15:05:55.200 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received, received:1
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received:{"a":0,"e":0.0}
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: Item received:com.vdeveloper.chaisutta.b.a#63d3fc
03-17 15:05:55.227 4501-4501/com.vdeveloper.chaisutta D/BeveragesTAG: card name:null
Database Screenshot:
I have found a solution myself. The problem was with my POJO. As this project was on androidx I need to add the annotation "#Keep" to stop the compiler from removing methods which it thinks are redundant.
import java.io.Serializable;
import androidx.annotation.Keep;
#Keep
public class GenericProductModel implements Serializable {
public int cardid;
public String cardname;
public String cardimage;
public String carddescription;
public float cardprice;
public GenericProductModel() {
}
public GenericProductModel(int cardid, String cardname, String cardimage, String carddescription, float cardprice) {
this.cardid = cardid;
this.cardname = cardname;
this.cardimage = cardimage;
this.carddescription = carddescription;
this.cardprice = cardprice;
}
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
public void setCardid(int cardid) {
this.cardid = cardid;
}
public void setCardname(String cardname) {
this.cardname = cardname;
}
public void setCardimage(String cardimage) {
this.cardimage = cardimage;
}
public void setCarddescription(String carddescription) {
this.carddescription = carddescription;
}
public void setCardprice(float cardprice) {
this.cardprice = cardprice;
}
}
Thanks, everyone for helping
You are getting null because all your values are null since you are returning in each getter this.fieldName instead of the fieldName. To solve this, please change your getters to:
public int getCardid() {
return cardid;
}
public String getCardname() {
return cardname;
}
public String getCardimage() {
return cardimage;
}
public String getCarddescription() {
return carddescription;
}
public float getCardprice() {
return cardprice;
}
See, there is no this anymore.
This is Fist time i'm asking question!! so bear with me.
The application is project(popular movie stage 2) from udacity where i need to fetch info of movies like tilte or poster_path or backdrop_path.
so when i fetch data from json it works perfectly fine but when i add another argument String backdrop in my Movies.java class.then getmBackdrop() shows empty and i couldn't get the data of backdrop overview and vote.but if i delete backdrop from constructor than it works fine. i dont know what is happening please help me.
this is Movies.javaclass
public class Movies implements Parcelable {
//Movies Data
public long mID;
private String mPosterPath;
private String mReleaseDate;
private String mTitle;
private String mVote;
private String mOverview;
private String mBackdrop;
private ArrayList<Trailers> trailers;
private ArrayList<Reviews> reviews;
public Movies() {
}
public Movies(String title, String releaseDate, String posterPath,
String backdrop,String vote, String overview) {
// this.mID=id;
this.mTitle = title;
this.mReleaseDate = releaseDate;
this.mPosterPath = posterPath;
this.mBackdrop = backdrop;
this.mVote = vote;
this.mOverview = overview;
this.trailers = new ArrayList<>();
this.reviews = new ArrayList<>();
}
public long getID(){ return mID ;}
public String getmBackdrop() { return mBackdrop; }
public String getPosterPath() {
return mPosterPath;
}
public String getTitle() {
return mTitle;
}
public String getReleaseDate() {
return mReleaseDate;
}
public String getOverview() {
return mOverview;
}
public String getVote() {
return mVote +"/10";
}
public void setTrailers(ArrayList<Trailers> trailers) {
this.trailers = trailers;
}
public void setReviews(ArrayList<Reviews> reviews) {
this.reviews = reviews;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeLong(mID);
dest.writeString(mTitle);
dest.writeString(mReleaseDate);
dest.writeString(mPosterPath);
dest.writeValue(mBackdrop);
dest.writeString(mVote);
dest.writeString(mOverview);
}
protected Movies(Parcel in) {
mID = in.readLong();
mTitle = in.readString();
mReleaseDate = in.readString();
mPosterPath = in.readString();
mBackdrop = in.readString();
mVote = in.readString();
mOverview = in.readString();
}
public static final Creator<Movies> CREATOR = new Creator<Movies>() {
public Movies createFromParcel(Parcel source) {
return new Movies(source);
}
public Movies[] newArray(int size) {
return new Movies[size];
}
};
}
MoviepediaJsonUtils.java where i'm parsing data
public class MoviepediaJsonUtils {
public static ArrayList<Movies> getParseMovieJson(String jsonMovies) throws JSONException {
final String IMAGE_BASE_URL = "https://image.tmdb.org/t/p/w500/";
final String BACKDROP_URL= "https://image.tmdb.org/t/p/w1280/";
JSONObject movieJson = new JSONObject(jsonMovies);
JSONArray movieArray = movieJson.getJSONArray("results");
ArrayList<Movies> movieArrayList = new ArrayList<>();
for (int i = 0; i < movieArray.length(); i++) {
JSONObject movieObject = movieArray.getJSONObject(i);
long id = movieObject.getLong("id");
String title = movieObject.getString("title");
String release_date = movieObject.getString("release_date");
String poster_path = movieObject.getString("poster_path");
String backdrop = movieObject.getString("backdrop_path");
String vote_average = movieObject.getString("vote_average");
String overview = movieObject.getString("overview");
Movies movies = new Movies(title, release_date,
IMAGE_BASE_URL + poster_path, BACKDROP_URL+backdrop,vote_average, overview);
movieArrayList.add(movies);
}
return movieArrayList;
}
public static String getResponseFromHttpUrl(InputStream stream) throws IOException {
Scanner scanner = new Scanner(stream);
scanner.useDelimiter("\\A");
boolean hasInput = scanner.hasNext();
if (hasInput) {
return scanner.next();
} else {
return null;
}
}
}
MainActivityFragments.java
public class MainActivityFragments extends Fragment {
private static final int COLUMN = 2;
private RecyclerView mRecyclerView;
SharedPreferences mSettings;
GridLayoutManager mGridLayoutManager;
private SharedPreferences.Editor mEditor;
private static final String SHARED_KEY_SORT = "sort";
private static final String POPULARITY = "popular";
private static final String RATINGS = "top_rated";
public static String[] backdrop;
public static final String SAVE_LAST_UPDATE_ORDER = "save_last_update_order";
private String mLastUpdateOrder;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater,
#Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.poster_fragment, container, false);
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
mGridLayoutManager = new GridLayoutManager(getActivity(),2, LinearLayoutManager.VERTICAL,false);
}else{
mGridLayoutManager = new GridLayoutManager(getActivity(), 4,LinearLayoutManager.VERTICAL,false);
}
mRecyclerView = view.findViewById(R.id.rv_movies);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(mGridLayoutManager);
mSettings = PreferenceManager.getDefaultSharedPreferences(getActivity());
mEditor = mSettings.edit();
mEditor.apply();
mRecyclerView.setAdapter(new MoviesAdapter(getActivity(), new ArrayList<Movies>()));
return view;
}
#Override
public void onStart() {
super.onStart();
if (needToUpdateUi()) {
updateUi();
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(SAVE_LAST_UPDATE_ORDER, mLastUpdateOrder);
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null) {
mLastUpdateOrder = savedInstanceState.getString(SAVE_LAST_UPDATE_ORDER);
}
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
updateUi();
}
// OnCreateOptionMenues will be here
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.poster_fragment, menu);
Drawable drawable = menu.findItem(R.id.icon).getIcon();
if (drawable != null) {
drawable.mutate();
drawable.setColorFilter(Color.WHITE, PorterDuff.Mode.SRC_ATOP);
}
}
// OnOptionitemSelected
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.poularity:
mEditor.putString(SHARED_KEY_SORT, POPULARITY);
mEditor.apply();
updateUi();
item.setChecked(true);
return true;
case R.id.top_rated:
mEditor.putString(SHARED_KEY_SORT, RATINGS);
mEditor.apply();
updateUi();
item.setChecked(true);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
String sortBy = mSettings.getString(SHARED_KEY_SORT, POPULARITY);
if (sortBy.equals(POPULARITY)) {
menu.findItem(R.id.poularity).setChecked(true);
} else {
menu.findItem(R.id.top_rated).setChecked(true);
}
}
private void updateUi() {
if (isNetworkAvailable()) {
OnTaskCompleted taskCompleted = new OnTaskCompleted() {
#Override
public void onFetchMoviesTaskCompleted(ArrayList<Movies> movies) {
mRecyclerView.setAdapter(new MoviesAdapter(getActivity(), movies));
}
};
MoviesAsyncTask moviesAsyncTask = new MoviesAsyncTask(taskCompleted);
mSettings = PreferenceManager.getDefaultSharedPreferences(getActivity());
String sortBy = mSettings.getString(SHARED_KEY_SORT, POPULARITY);
mLastUpdateOrder = sortBy;
moviesAsyncTask.execute(sortBy);
} else {
Toast.makeText(this.getActivity().getApplicationContext(), "Need Internet Connection", Toast.LENGTH_LONG).show();
}
}
private boolean needToUpdateUi() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
if (!mLastUpdateOrder.equals(prefs.getString(SHARED_KEY_SORT, POPULARITY))) {
return true;
} else {
return false;
}
}
//Based on a stackoverflow snippet
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) this.getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
DeatailActivityFragment
public class DetailActivityFragments extends Fragment {
private final String TAG = this.getClass().getSimpleName();
private static final String PARCEL_KEY = "movie_parcel";
Movies mMovie;
OnTaskCompleted mlistener;
ArrayList<Trailers> mTrailers;
ArrayList<Reviews> mReviews;
ImageView poster;
ImageView backdrop;
public DetailActivityFragments() {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_detail_fragment,
container, false);
Movies parceableExtra = getActivity().getIntent().getParcelableExtra(PARCEL_KEY);
poster = view.findViewById(R.id.poster_IV);
TextView title = view.findViewById(R.id.title_TV);
TextView releaseDate = view.findViewById(R.id.relaesedate_TV);
TextView vote = view.findViewById(R.id.vote_TV);
TextView overView = view.findViewById(R.id.overview_TV);
backdrop = view.findViewById(R.id.image_id);
final FloatingActionButton fab1 = view.findViewById(R.id.fab);
//String gotPosition = getStringExtra("position");
//intGotPosition=Integer.parseInt(gotPosition);
// String url = "https://image.tmdb.org/t/p/w1280"+DetailActivityFragments.backdrop[intGotPosition];
title.setText(parceableExtra.getTitle());
releaseDate.setText(parceableExtra.getReleaseDate());
vote.setText(parceableExtra.getVote());
overView.setText(parceableExtra.getOverview());
Picasso.with(view.getContext()).load(parceableExtra.getPosterPath())
.into(poster);
Picasso.with(this.getActivity()).load( parceableExtra.getmBackdrop())
.error(R.drawable.sam).into(backdrop);
fab1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context context = view.getContext();
Intent i=new Intent(context , TrailerActivity.class);
startActivity(i);
}
});
return view;
}
}
MoviesAsyncTask.java
public class MoviesAsyncTask extends AsyncTask<String, Void, ArrayList<Movies>> {
private final String LOG_TAG = MoviesAsyncTask.class.getSimpleName();
final String MY_API_KEY = "removed deliberately";
ArrayList<Movies> mMovies;
private OnTaskCompleted mListener;
public MoviesAsyncTask(OnTaskCompleted listener) {
mListener = listener;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected ArrayList<Movies> doInBackground(String... params) {
if (params.length == 0) {
return null;
}
final String MOVIEDB_BASE_URL =
"https://api.themoviedb.org/3/movie/";
final String APIKEY = "api_key";
Uri builtUri = Uri.parse(MOVIEDB_BASE_URL).buildUpon()
.appendPath(params[0])
.appendQueryParameter(APIKEY, MY_API_KEY)
.build();
URL url = null;
try {
url = new URL(builtUri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try {
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
String response = null;
try {
response = MoviepediaJsonUtils.getResponseFromHttpUrl(connection.getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
try {
return MoviepediaJsonUtils.getParseMovieJson(response);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(ArrayList<Movies> movies) {
super.onPostExecute(movies);
mListener.onFetchMoviesTaskCompleted(movies);
mMovies = movies;
}
}
Try to add your string at the end of your class or remove all the parcelable generated code, add your string, then apply again the parcelable implementation.
This happens because you're not updating the parcel methods.
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.
I've success to populate data into listview, but my way seems very bad because when i scroll the list view, the retrofit always get All the Repository. So, what is the best way to populate Endless List view's data with retrofit ? Thanks ...
MainActivity.java
public class MainActivity extends Activity {
public static final String ENDPOINT = "http://rfhan.com";
private List<Tempat> tempatList;
private TempatAdapter tadapter;
private EndlessListView lv;
private int start=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tempatList = new ArrayList<Tempat>();
tadapter = new TempatAdapter(this, R.layout.item_tempat, tempatList);
lv = (EndlessListView) findViewById(R.id.el);
lv.setLoadingView(R.layout.loading_layout);
lv.setAdapter(tadapter);
//init data to my list
requestData();
//scroll listener
lv.setListener(new EndlessListener() {
#Override
public void loadData() {
requestData();
}
});
}
private void requestData(){
RestAdapter adapter = new RestAdapter.Builder()
.setEndpoint(ENDPOINT)
.build();
TempatAPI api = adapter.create(TempatAPI.class);
api.getAllData(new Callback<List<Tempat>>() {
//here the problem
#Override
public void success(List<Tempat> data, Response arg1) {
updateData(data);
}
#Override
public void failure(RetrofitError arg0) {
Toast.makeText(MainActivity.this, "Retrofit Error!", Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, arg0+"", Toast.LENGTH_LONG).show();
}
});
}
//the tmpt list is contain all Tempat's data
//code below is to get some tmpt's data into new Arraylist
//and update the adapter's data
//it's work but seems bad way
private void updateData(List<Tempat> tmpt){
tempatList = new ArrayList<Tempat>();
start+=10;
for(int i=start-10;(i<start&&start<tmpt.size());i++)
tempatList.add(tmpt.get(i));
lv.addNewData(tempatList);
}
protected boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
} else {
return false;
}
}
}
Model Tempat.java
import java.math.BigInteger;
import android.graphics.Bitmap;
public class Tempat {
BigInteger idkoleksi;
String nama;
String kategori;
String alamat;
String notelp;
String jambuka;
String jamtutup;
String harga;
String imageHeaderURL;
double latitude;
double longitude;
int jumlahview;
int jumlatrate;
double rating;
String tanggal;
Bitmap bitmap;
public BigInteger getIdkoleksi() {
return idkoleksi;
}
public String getNama() {
return nama;
}
public String getKategori() {
return kategori;
}
public String getAlamat() {
return alamat;
}
public String getNotelp() {
return notelp;
}
public String getJambuka() {
return jambuka;
}
public String getJamtutup() {
return jamtutup;
}
public String getHarga() {
return harga;
}
public String getImageHeaderURL() {
return imageHeaderURL;
}
public double getLatitude() {
return latitude;
}
public double getLongitude() {
return longitude;
}
public int getJumlahview() {
return jumlahview;
}
public int getJumlatrate() {
return jumlatrate;
}
public double getRating() {
return rating;
}
public String getTanggal() {
return tanggal;
}
public void setIdkoleksi(BigInteger idkoleksi) {
this.idkoleksi = idkoleksi;
}
public void setNama(String nama) {
this.nama = nama;
}
public void setKategori(String kategori) {
this.kategori = kategori;
}
public void setAlamat(String alamat) {
this.alamat = alamat;
}
public void setNotelp(String notelp) {
this.notelp = notelp;
}
public void setJambuka(String jambuka) {
this.jambuka = jambuka;
}
public void setJamtutup(String jamtutup) {
this.jamtutup = jamtutup;
}
public void setHarga(String harga) {
this.harga = harga;
}
public void setImageHeaderURL(String imageHeaderURL) {
this.imageHeaderURL = imageHeaderURL;
}
public void setLatitude(double latitude) {
this.latitude = latitude;
}
public void setLongitude(double longitude) {
this.longitude = longitude;
}
public void setJumlahview(int jumlahview) {
this.jumlahview = jumlahview;
}
public void setJumlatrate(int jumlatrate) {
this.jumlatrate = jumlatrate;
}
public void setRating(double rating) {
this.rating = rating;
}
public void setTanggal(String tanggal) {
this.tanggal = tanggal;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
}
Repository TempatAPI.java
import java.util.List;
import retrofit.Callback;
import retrofit.http.GET;
public interface TempatAPI {
#GET("api/tempat/get_all_data.php")
public void getAllData(Callback<List<Tempat>> response);
}
Webservice API get_all_data.php
<?php
$response = array();
require_once __DIR__ . '/db_connect.php';
$db = new DB_CONNECT();
$nama=$_GET["nama"];
$query = "SELECT DataKoleksi.* , DataStatistikKoleksi.* FROM DataKoleksi, DataStatistikKoleksi WHERE DataKoleksi.idkoleksi = DataStatistikKoleksi.idkoleksi";
$result = mysql_query($query) or die(mysql_error());
$response = array();
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)) {
$koleksi = array();
$koleksi["idkoleksi"] = $row["idkoleksi"];
$koleksi["nama"] = $row["nama"];
$koleksi["kategori"] = $row["kategori"];
$koleksi["alamat"] = $row["alamat"];
$koleksi["notelp"] = $row["notelp"];
$koleksi["jambuka"] = $row["jambuka"];
$koleksi["jamtutup"] = $row["jamtutup"];
$koleksi["harga"] = $row["harga"];
$koleksi["imageHeaderURL"] = $row["imageHeaderURL"];
$koleksi["latitude"] = $row["latitude"];
$koleksi["longitude"] = $row["longitude"];
$koleksi["jumlahview"] = $row["jumlahview"];
$koleksi["jumlahrate"] = $row["jumlahrate"];
$koleksi["rating"] = $row["rating"];
$koleksi["tanggal"] = $row["tanggal"];
array_push($response, $koleksi);
}
echo json_encode($response);
} else {
// no found
echo json_encode($response);
}
?>
You need to add a listener to your listview to see if you have scrolled to the end of the list. In my example below, we check if we have reached the end of the list and if we have, we try to load 10 more items. The listview is then updated.
lvEvents.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {}
#Override
public void onScroll(AbsListView absListView, int firstVisible, int visibleCount, int totalCount) {
boolean loadMore = firstVisible + visibleCount >= totalCount;
if (loadMore && !isLoadingEvents && futureEvents.size() >= 10 && !noMoreEvents) {
Log.d(TAG, "LOADING MORE EVENTS");
isLoadingEvents = true;
networkManager.getTenMoreEvents(getActivity(), new NetworkManager.Request() {
#Override
public void finished() {
updateEventsFeed();
isLoadingEvents = false;
}
});
}
}
});