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.
Related
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 just want to implement in-app-purchasement into my app. It is a card game with different rulesets. So now want to implement 2 new rulesets which should work as my products and with in-app-purchasement.
I have this:
`go = (Button)findViewById(R.id.go);
go.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ArrayList skuList = new ArrayList();
skuList.add(inappid);
Bundle querySkus = new Bundle();
querySkus.putStringArrayList("ITEM_ID_LIST", skuList);
Bundle skuDetails;
try {
skuDetails = mservice.getSkuDetails(3, getPackageName(),
"inapp", querySkus);
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList =
skuDetails.getStringArrayList("DETAILS_LIST");
for (String thisResponse : responseList) {
JSONObject object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
if (sku.equals(inappid)) {
System.out.println("price " + price);
Bundle buyIntentBundle =
mservice.getBuyIntent(3, getPackageName(), sku,
"inapp",
"blablabla");
PendingIntent pendingIntent =
buyIntentBundle.getParcelable("BUY_INTENT");
startIntentSenderForResult(
pendingIntent.getIntentSender(), 1001,
new Intent(), Integer.valueOf(0),
Integer.valueOf(0), Integer.valueOf(0));
}
}
}
} catch (RemoteException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IntentSender.SendIntentException e ) {
e.printStackTrace();
}
}
});`
First click on my ruleset works fine. The second click triggers the app to break down with the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.IntentSender android.app.PendingIntent.getIntentSender()' on a null object reference
Do you have some good in-app tutorials or a tipp for me?
Thanks in advance
JD
Here is my BaseClass that i use everywhere i need. Just extend your activity by this BaseInAppPurchaseActivity
Bonus in this class.
You can get what items are available for purchase so user can not get future exception if item is not available like
checkAvailablePurchases(skuList, new OnResultInApp() {
#Override
public void onResult(ArrayList<AvailablePurchase> availablePurchaseArrayList) {
.. logic for showing view with available purchaseItem
}
});
For purchasing an item
purchaseItem(googleInAppId, new OnResultPurchase() {
#Override
public void onSuccess(PurchaseResponseBean purchaseResponseBean, String inAppPurchaseData) {
// your stuff
}
#Override
public void onError() {
showToast(R.string.something_went_wrong);
}
});
Isn't this look pretty clean and nice.
BaseInAppPurchaseActivity.class
package in.kpis.nearyou.base;
import android.app.PendingIntent;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import com.android.vending.billing.IInAppBillingService;
import com.google.gson.Gson;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import in.kpis.nearyou.entity.AvailablePurchase;
import in.kpis.nearyou.entity.Helper;
import in.kpis.nearyou.entity.PurchaseResponseBean;
import in.kpis.nearyou.entity.UserPurchaseItemsBean;
import in.kpis.nearyou.utilities.AppPreference;
import static in.kpis.nearyou.base.BaseInAppPurchaseActivity.ConsuptionResponseType.SUCCESS;
import static in.kpis.nearyou.base.BaseInAppPurchaseActivity.PurchaseStateTypes.PURCHASED;
public class BaseInAppPurchaseActivity extends BaseAppCompatActivity {
private static final String TAG = BaseInAppPurchaseActivity.class.getSimpleName();
private IInAppBillingService mService;
private static final char[] symbols = new char[36];
static {
for (int idx = 0; idx < 10; ++idx)
symbols[idx] = (char) ('0' + idx);
for (int idx = 10; idx < 36; ++idx)
symbols[idx] = (char) ('a' + idx - 10);
}
public void startInAppPurchaseServices() {
Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
}
private String appPackageName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
appPackageName = this.getPackageName();
startInAppPurchaseServices();
}
ServiceConnection mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
startAsyncForCheckingAvailablePurchase();
}
};
private void startAsyncForCheckingAvailablePurchase() {
if (skuListByNearyouServer != null && skuListByNearyouServer.size() > 0 & onResultInApp != null) {
AvailablePurchaseAsyncTask mAsyncTask = new AvailablePurchaseAsyncTask(appPackageName, skuListByNearyouServer, onResultInApp);
mAsyncTask.execute();
}
}
private ArrayList<String> skuListByNearyouServer = new ArrayList<>();
OnResultInApp onResultInApp;
public void checkAvailablePurchases(ArrayList<String> skuList, OnResultInApp onResultInApp) {
skuListByNearyouServer = skuList;
this.onResultInApp = onResultInApp;
if (mService == null) startInAppPurchaseServices();
else startAsyncForCheckingAvailablePurchase();
}
public interface OnResultPurchase {
void onSuccess(PurchaseResponseBean purchaseResponseBean, String inAppPurchaseData);
void onError();
}
private OnResultPurchase onResultPurchase;
private String itemToPurchaseSku;
public void purchaseItem(String sku, OnResultPurchase onResultPurchase) {
this.onResultPurchase = onResultPurchase;
itemToPurchaseSku = sku;
if (isBillingSupported()) {
String generatedPayload = getPayLoad();
AppPreference.getInstance(BaseInAppPurchaseActivity.this).setDeveloperPayload(generatedPayload);
try {
Bundle buyIntentBundle = mService.getBuyIntent(3, getPackageName(), sku, "inapp", generatedPayload);
PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT");
try {
startIntentSenderForResult(pendingIntent.getIntentSender(), Helper.RESPONSE_CODE, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0));
} catch (IntentSender.SendIntentException e) {
e.printStackTrace();
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == Helper.RESPONSE_CODE) {
if (data != null && data.getExtras() != null && data.getStringExtra("INAPP_DATA_SIGNATURE") != null & data.getStringExtra("INAPP_PURCHASE_DATA") != null) {
int responseCode = data.getIntExtra("RESPONSE_CODE", 0);
String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA");
String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE");
if (resultCode == RESULT_OK && responseCode == 0) {
try {
PurchaseResponseBean purchaseResponseBean = new Gson().fromJson(purchaseData, PurchaseResponseBean.class);
String sku = purchaseResponseBean.getProductId();
String developerPayload = purchaseResponseBean.getDeveloperPayload();
int responseCodeConsuption = consumePurchaseItem(purchaseResponseBean.getPurchaseToken());
if (responseCodeConsuption == SUCCESS) {
if (purchaseResponseBean.getPurchaseState() == PURCHASED && itemToPurchaseSku.equals(sku) && developerPayload.equals(AppPreference.getInstance(BaseInAppPurchaseActivity.this).getDeveloperPayload())) {
if (onResultPurchase != null)
onResultPurchase.onSuccess(purchaseResponseBean, purchaseData);
} else onErrorOfPurchase();
} else onResultPurchase.onSuccess(purchaseResponseBean, purchaseData);
} catch (Exception e) {
e.printStackTrace();
onErrorOfPurchase();
}
} else onErrorOfPurchase();
}
} else onErrorOfPurchase();
}
private void onErrorOfPurchase() {
if (onResultPurchase != null) onResultPurchase.onError();
}
interface PurchaseStateTypes {
int PURCHASED = 0;
int CANCELED = 1;
int REFUNDED = 2;
}
interface ConsuptionResponseType {
int SUCCESS = 0;
}
private String getPayLoad() {
RandomString randomString = new RandomString(36);
String payload = randomString.nextString();
return payload;
}
private class RandomString {
private final Random random = new Random();
private final char[] buf;
RandomString(int length) {
if (length < 1)
throw new IllegalArgumentException("length < 1: " + length);
buf = new char[length];
}
String nextString() {
for (int idx = 0; idx < buf.length; ++idx)
buf[idx] = symbols[random.nextInt(symbols.length)];
return new String(buf);
}
}
public final class SessionIdentifierGenerator {
private SecureRandom random = new SecureRandom();
public String nextSessionId() {
return new BigInteger(130, random).toString(32);
}
}
public interface OnResultInApp {
void onResult(ArrayList<AvailablePurchase> canPurchaseList);
}
private class AvailablePurchaseAsyncTask extends AsyncTask<Void, Void, Bundle> {
String packageName;
ArrayList<String> skuList;
OnResultInApp OnResultInApp;
AvailablePurchaseAsyncTask(String packageName, ArrayList<String> skuList, OnResultInApp OnResultInApp) {
this.packageName = packageName;
this.skuList = skuList;
this.OnResultInApp = OnResultInApp;
}
#Override
protected Bundle doInBackground(Void... voids) {
Bundle query = new Bundle();
query.putStringArrayList(Helper.ITEM_ID_LIST, skuList);
Bundle skuDetails = null;
try {
skuDetails = mService.getSkuDetails(3, packageName, "inapp", query);
} catch (RemoteException e) {
e.printStackTrace();
}
return skuDetails;
}
#Override
protected void onPostExecute(Bundle skuDetails) {
ArrayList<AvailablePurchase> availablePurchaseArrayList = new ArrayList<>();
if (skuDetails != null) {
int response = skuDetails.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST");
if (responseList != null) {
for (String thisResponse : responseList) {
JSONObject object = null;
try {
object = new JSONObject(thisResponse);
String sku = object.getString("productId");
String price = object.getString("price");
availablePurchaseArrayList.add(new AvailablePurchase(sku, price, false));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
}
for (AvailablePurchase availablePurchase : availablePurchaseArrayList) {
for (String sku : skuList) {
if (sku.equals(availablePurchase.getSku())) {
availablePurchase.setActive(true);
}
}
}
if (OnResultInApp != null) {
OnResultInApp.onResult(availablePurchaseArrayList);
}
}
}
public boolean isBillingSupported() {
int response = 1;
try {
response = mService.isBillingSupported(3, getPackageName(), "inapp");
} catch (RemoteException e) {
e.printStackTrace();
}
if (response > 0) {
return false;
}
return true;
}
public int consumePurchaseItem(String purchaseToken) {
if (isBillingSupported()) {
try {
int response = mService.consumePurchase(3, getPackageName(), purchaseToken);
return response;
} catch (RemoteException e) {
e.printStackTrace();
return -1;
}
} else return -1;
}
public Bundle getAllUserPurchase() {
Bundle ownedItems = null;
try {
ownedItems = mService.getPurchases(3, getPackageName(), "inapp", null);
} catch (RemoteException e) {
e.printStackTrace();
}
return ownedItems;
}
public List<UserPurchaseItemsBean> extractAllUserPurchase(Bundle ownedItems) {
List<UserPurchaseItemsBean> mUserItems = new ArrayList<UserPurchaseItemsBean>();
int response = ownedItems.getInt("RESPONSE_CODE");
if (response == 0) {
ArrayList<String> ownedSkus = ownedItems.getStringArrayList("INAPP_PURCHASE_ITEM_LIST");
ArrayList<String> purchaseDataList = ownedItems.getStringArrayList("INAPP_PURCHASE_DATA_LIST");
ArrayList<String> signatureList = ownedItems.getStringArrayList("INAPP_DATA_SIGNATURE_LIST");
String continuationToken = ownedItems.getString("INAPP_CONTINUATION_TOKEN");
if (purchaseDataList != null) {
for (int i = 0; i < purchaseDataList.size(); ++i) {
String purchaseData = purchaseDataList.get(i);
assert signatureList != null;
String signature = signatureList.get(i);
assert ownedSkus != null;
String sku = ownedSkus.get(i);
UserPurchaseItemsBean allItems = new UserPurchaseItemsBean(sku, purchaseData, signature);
mUserItems.add(allItems);
}
}
}
return mUserItems;
}
#Override
public void onDestroy() {
super.onDestroy();
stopInAppPurchaseService();
}
private void stopInAppPurchaseService() {
if (mService != null) {
unbindService(mServiceConn);
}
}
}
AvailablePurchase.class
/**
* Created by KHEMRAJ on 7/13/2017.
*/
public class AvailablePurchase {
private String sku;
private String price;
private boolean isActive;
public AvailablePurchase(String sku, String price, boolean isActive) {
this.sku = sku;
this.price = price;
this.isActive = isActive;
}
public String getSku() {
return sku;
}
public String getPrice() {
return price;
}
public boolean isActive() {
return isActive;
}
public void setActive(boolean active) {
isActive = active;
}
}
Helper.class
/**
* Created by KHEMRAJ on 7/13/2017.
*/
import android.content.Context;
import android.widget.Toast;
public class Helper {
public static final String ITEM_ID_LIST = "ITEM_ID_LIST";
public static final String ITEM_ONE_ID = "android.test.purchased";
public static final String ITEM_TWO_ID = "2";
public static final String ITEM_THREE_ID = "3";
public static final String ITEM_FIVE_ID= "4";
public static final String ITEM_SIX_ID = "5";
public static final int RESPONSE_CODE = 1001;
public static void displayMessage(Context context, String message){
Toast.makeText(context.getApplicationContext(), message, Toast.LENGTH_LONG).show();
}
}
PurchaseResponseBean.class
/**
* Created by KHEMRAJ on 7/15/2017.
*/
public class PurchaseResponseBean {
private String productId;
private String developerPayload;
private String purchaseToken;
private String orderId;
private String purchaseTime;
private int purchaseState;
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
public String getDeveloperPayload() {
return developerPayload;
}
public void setDeveloperPayload(String developerPayload) {
this.developerPayload = developerPayload;
}
public String getPurchaseToken() {
return purchaseToken;
}
public void setPurchaseToken(String purchaseToken) {
this.purchaseToken = purchaseToken;
}
public String getOrderId() {
return orderId;
}
public void setOrderId(String orderId) {
this.orderId = orderId;
}
public String getPurchaseTime() {
return purchaseTime;
}
public void setPurchaseTime(String purchaseTime) {
this.purchaseTime = purchaseTime;
}
public int getPurchaseState() {
return purchaseState;
}
public void setPurchaseState(int purchaseState) {
this.purchaseState = purchaseState;
}
}
UserPurchaseItemsBean.class
public class UserPurchaseItemsBean {
private String sku;
private String purchasedata;
private String signature;
public UserPurchaseItemsBean(String sku, String purchasedata, String signature) {
this.sku = sku;
this.purchasedata = purchasedata;
this.signature = signature;
}
public String getSku() {
return sku;
}
public String getPurchasedata() {
return purchasedata;
}
public String getSignature() {
return signature;
}
}
AppPreference.java
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class AppPreference {
String DEVELOPERPAYLOAD = "DEVELOPERPAYLOAD";
String PURCHASETOKEN = "PURCHASETOKEN";
//Configuration Variable
private static AppPreference singletonPreference = null;
private SharedPreferences sp;
private Context context;
private AppPreference(Context context) {
if (context == null)
return;
this.context = context;
sp = context.getSharedPreferences(Constants.sharedPreference.PREFERENCE, 0);
}
public static AppPreference getInstance(Context context) {
if (singletonPreference == null)
singletonPreference = new AppPreference(context);
return singletonPreference;
}
public void clearOnlogout() {
Editor prefsEditor = sp.edit();
prefsEditor.clear();
prefsEditor.apply();
}
void removeData(String key) {
SharedPreferences.Editor editor = sp.edit();
editor.remove(key);
editor.apply();
}
public void setStringData(String pKey, String pData) {
SharedPreferences.Editor editor = sp.edit();
editor.putString(pKey, pData);
editor.apply();
}
public void setBooleanData(String pKey, boolean pData) {
SharedPreferences.Editor editor = sp.edit();
editor.putBoolean(pKey, pData);
editor.apply();
}
void setIntegerData(String pKey, int pData) {
SharedPreferences.Editor editor = sp.edit();
editor.putInt(pKey, pData);
editor.apply();
}
public String getStringData(String pKey) {
return sp.getString(pKey, "");
}
public boolean getBooleanData(String pKey) {
return sp.getBoolean(pKey, false);
}
public int getIntegerData(String pKey) {
return sp.getInt(pKey, 0);
}
public String getDeveloperPayload() {
return sp.getString(DEVELOPERPAYLOAD, "");
}
public void setDeveloperPayload(String developerPayload) {
SharedPreferences.Editor editor = sp.edit();
editor.putString(DEVELOPERPAYLOAD, developerPayload);
editor.apply();
}
}
Happy coding :)
In this code I'm parsing JSON and using ArrayList displaying it in a searchable spinner. The code works perfectly but when it comes to parse large JSON then it takes time and memory on mobile data.
Can any one suggest me a better idea to parse large JSON or can any one explain me how to parse it with Gson and loading into the searchable spinner?
try {
if (response.has("products_data")) {
jsonArray = new JSONArray();
jsonArray = response.getJSONArray("products_data");
for (int t = 0; t < jsonArray.length(); t++) {
object = jsonArray.getJSONObject(t);
retailer_id = object.getString("retailer_id");
retailer_name = object.getString("retailer_name");
product_code = object.getString("product_code");
product_name = object.getString("product_name");
pro_packing = object.getString("pro_packing");
pro_company=object.getString("pro_company");
pro_generic_code=object.getString("pro_generic_code");
pro_generic_name=object.getString("pro_generic_name");
pro_stock = object.getInt("product_stock");
product_MRP=object.getDouble("product_MRP");
p = new Product();
p.setRetailer_id(retailer_id);
p.setRetailer_name(retailer_name);
p.setProduct_code(product_code);
p.setProduct_name(product_name);
p.setPro_packing(pro_packing);
p.setPro_company(pro_company);
p.setPro_generic_code(pro_generic_code);
p.setPro_generic_name(pro_generic_name);
p.setPro_stock(pro_stock);
p.setProduct_MRP(product_MRP);
productlist.add(p);
}
progressDialog.dismiss();
final List<String> pname = new ArrayList<String>();
final List<String> pcode = new ArrayList<String>();
pname.clear();
pname.add(0,"Select Products");
for (int i = 0; i < productlist.size(); i++) {
pname.add(productlist.get(i).getProduct_name());
}
// Creating adapter for spinner
final ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.custom_spinnertxt, pname);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
runOnUiThread(new Runnable() {
#Override
public void run() {
// attaching data adapter to spinner
autoCompleteTextView.setAdapter(spinnerAdapter);
autoCompleteTextView.setSelection(0);
}
});
autoCompleteTextView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long id) {
if(i>0) {
p_id = productlist.get(i - 1).getProduct_code();
p_stock = productlist.get(i - 1).getPro_stock();
ppack = productlist.get(i - 1).getPro_packing();
pcomp = productlist.get(i - 1).getPro_company();
mrp = productlist.get(i - 1).getProduct_MRP();
pseller = productlist.get(i - 1).getRetailer_name();
// Log.i("pID:", p_id);
//Log.i("pStock:", String.valueOf(p_stock));
//Log.i("PMRP:", String.valueOf(mrp));
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
This is my JSON Response:
"products_data": [
{
"retailer_id": "mum0022",
"retailer_name": "SAKTI MEDICO",
"product_code": "6474",
"product_name": "EPISOFT CLEANSING LOTION",
"pro_packing": "125ML",
"pro_company": "GLENMARK-GRACEWELLSPECIALITY",
"pro_generic_code": "",
"pro_generic_name": "",
"product_stock": "7",
"product_MRP": "209"
},
{
"retailer_id": "mum0022",
"retailer_name": "SAKTI MEDICO",
"product_code": "8403",
"product_name": "ELOVERA LOTION 150ML (BIG)",
"pro_packing": "150ML",
"pro_company": "GLENMARK (DERMAX)",
"pro_generic_code": "",
"pro_generic_name": "",
"product_stock": "3",
"product_MRP": "324.5"
},
...
Try this
public class Products_data implements Parcelable {
#SerializedName("retailer_id")
private String retailer_id;
#SerializedName("retailer_name")
private String retailer_name;
#SerializedName("product_code")
private String product_code;
#SerializedName("product_name")
private String product_name;
#SerializedName("pro_packing")
private String pro_packing;
#SerializedName("pro_company")
private String pro_company;
#SerializedName("pro_generic_code")
private String pro_generic_code;
#SerializedName("pro_generic_name")
private String pro_generic_name;
#SerializedName("product_stock")
private Integer product_stock;
#SerializedName("product_MRP")
private Double product_MRP;
public Products_data() {
}
protected Products_data(Parcel in) {
retailer_id = in.readString();
retailer_name = in.readString();
product_code = in.readString();
product_name = in.readString();
pro_packing = in.readString();
pro_company = in.readString();
pro_generic_code = in.readString();
pro_generic_name = in.readString();
product_stock = in.readInt();
product_MRP = in.readDouble();
}
public static final Creator<Products_data> CREATOR = new Creator<Products_data>() {
#Override
public Products_data createFromParcel(Parcel in) {
return new Products_data(in);
}
#Override
public Products_data[] newArray(int size) {
return new Products_data[size];
}
};
public String getRetailer_id() {
return retailer_id;
}
public void setRetailer_id(String retailer_id) {
this.retailer_id = retailer_id;
}
public String getRetailer_name() {
return retailer_name;
}
public void setRetailer_name(String retailer_name) {
this.retailer_name = retailer_name;
}
public String getProduct_code() {
return product_code;
}
public void setProduct_code(String product_code) {
this.product_code = product_code;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getPro_packing() {
return pro_packing;
}
public void setPro_packing(String pro_packing) {
this.pro_packing = pro_packing;
}
public String getPro_company() {
return pro_company;
}
public void setPro_company(String pro_company) {
this.pro_company = pro_company;
}
public String getPro_generic_code() {
return pro_generic_code;
}
public void setPro_generic_code(String pro_generic_code) {
this.pro_generic_code = pro_generic_code;
}
public String getPro_generic_name() {
return pro_generic_name;
}
public void setPro_generic_name(String pro_generic_name) {
this.pro_generic_name = pro_generic_name;
}
public Integer getProduct_stock() {
return product_stock;
}
public void setProduct_stock(Integer product_stock) {
this.product_stock = product_stock;
}
public Double getProduct_MRP() {
return product_MRP;
}
public void setProduct_MRP(Double product_MRP) {
this.product_MRP = product_MRP;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(retailer_id);
parcel.writeString(retailer_name);
parcel.writeString(product_code);
parcel.writeString(product_name);
parcel.writeString(pro_packing);
parcel.writeString(pro_company);
parcel.writeString(pro_generic_code);
parcel.writeString(pro_generic_name);
parcel.writeInt(product_stock);
parcel.writeDouble(product_MRP);
}
}
After making this POJO class
gson.fromJson(json, Products_data.class);
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.
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;
}
});
}
}
});