I have this json form this URL: Website Here
The problem is that I'm trying to retrieve some of the data in the JSON like: block_height, total, fees and size. I have 2 days trying to make it work but I have no idea why my code is not working. The last I've tried was showing the data in a alert dialog. But this isn't working yet.
JSON:
{
"block_hash": "0000000000000397a165d83cc4640321a3b8ff4cce1f8aa2570deabf14ac14e7",
"block_height": 154598,
"block_index": 63,
"hash": "b6f6991d03df0e2e04dafffcd6bc418aac66049e2cd74b80f14ac86db1e3f0da",
"addresses": [
"13AMPUTTwryLGX3nrMvumaerSqNXkL3gEV",
"14pDqB95GWLWCjFxM4t96H2kXH7QMKSsgG",
"1FwYmGEjXhMtxpWDpUXwLx7ndLNfFQncKq"
],
"total": 100000000,
"fees": 0,
"size": 258,
"preference": "low",
"confirmed": "2011-11-24T11:45:54Z",
"received": "2011-11-24T11:45:54Z",
"ver": 1,
"double_spend": false,
"vin_sz": 1,
"vout_sz": 2,
"confirmations": 339633,
"confidence": 1,
"inputs": [
{
"prev_hash": "9fa4e0e33aba41623bc3618827d2a6495e6828ce04f26c97771a1369210e8201",
"output_index": 2,
"script": "48304502210098a2851420e4daba656fd79cb60cb565bd7218b6b117fda9a512ffbf17f8f178022005c61f31fef3ce3f906eb672e05b65f506045a65a80431b5eaf28e0999266993014104f0f86fa57c424deb160d0fc7693f13fce5ed6542c29483c51953e4fa87ebf247487ed79b1ddcf3de66b182217fcaf3fcef3fcb44737eb93b1fcb8927ebecea26",
"output_value": 100000000,
"sequence": 4294967295,
"addresses": [
"1FwYmGEjXhMtxpWDpUXwLx7ndLNfFQncKq"
],
"script_type": "pay-to-pubkey-hash",
"age": 154567
}
],
"outputs": [
{
"value": 98000000,
"script": "76a91429d6a3540acfa0a950bef2bfdc75cd51c24390fd88ac",
"spent_by": "df0f8a4f0988de2875705a79ec826c8b9f8b08c9ffa4e5b4a5ea1b7bf956306c",
"addresses": [
"14pDqB95GWLWCjFxM4t96H2kXH7QMKSsgG"
],
"script_type": "pay-to-pubkey-hash"
},
{
"value": 2000000,
"script": "76a91417b5038a413f5c5ee288caa64cfab35a0c01914e88ac",
"spent_by": "0c45329983279acf2f9e9c7976774ef11bdb2646d934836c53e6679281e09ac8",
"addresses": [
"13AMPUTTwryLGX3nrMvumaerSqNXkL3gEV"
],
"script_type": "pay-to-pubkey-hash"
}
]
}
JAVA - Android Studio Fragment
private void setUpData() {
// Retrieve the city data from the web service
// In a worker thread since it's a network operation.
new Thread(new Runnable() {
public void run() {
try {
retrieveData();
} catch (IOException e) {
Log.e(LOG_TAG, "Cannot retrive Data", e);
return;
}
}
}).start();
}
protected void retrieveData() throws IOException {
HttpURLConnection conn = null;
final StringBuilder json = new StringBuilder();
try {
// Connect to the web service
URL url = new URL("https://api.blockcypher.com/v1/btc/main/txs/"+TxsHashs);
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Read the JSON data into the StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
json.append(buff, 0, read);
}
} catch (Exception e) {
Log.e(LOG_TAG, "Error connecting to service", e);
throw new IOException("Error connecting to service", e);
}
// Create markers for the city data.
// Must run this on the UI thread since it's a UI operation.
getActivity().runOnUiThread(new Runnable() {
public void run() {
try {
DataAdapter(json.toString());
} catch (Exception e) {
Log.e(LOG_TAG, "Error processing JSON", e);
}
}
});
}
private void DataAdapter(String json)
{
try
{
JSONObject jsonObject = new JSONObject(json);
String block_height = jsonObject.getString("block_height");
String total = jsonObject.getString("total");
String fee = jsonObject.getString("fee");
String size = jsonObject.getString("size");
String received = jsonObject.getString("received");
String confirmations = jsonObject.getString("confirmations");
showalert(TxsHashs,received);
}
catch (JSONException e)
{
e.printStackTrace();
}
}
private void showalert(String title, String msj)
{
AlertDialog.Builder MSGbox = new AlertDialog.Builder(getActivity());
MSGbox.setTitle(title);
String mensaje = msj;
MSGbox.setMessage(mensaje)
.setPositiveButton("OKEY", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = MSGbox.create();
alertDialog.show();
}
Please, someone Help Me
Link to the working code
Add these to the build.gradle
compile 'com.android.support:appcompat-v7:26.+'
compile 'com.android.support:cardview-v7:26.+'
compile 'com.android.support:recyclerview-v7:26.+'
compile 'com.android.support:design:26.+'
compile 'com.android.volley:volley:1.0.0'
compile 'com.google.code.gson:gson:2.6.2'
Create 3 model classes for Cyphers, Inputs, Outputs
package com.project.blockcypher.models;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Cyphers {
#SerializedName("block_height")
private int block_height;
#SerializedName("block_index")
private int block_index;
#SerializedName("hash")
private String hash;
#SerializedName("addresses")
private List<String> addresses;
#SerializedName("total")
private int total;
#SerializedName("fees")
private int fees;
#SerializedName("size")
private int size;
#SerializedName("preference")
private String preference;
#SerializedName("relayed_by")
private String relayed_by;
#SerializedName("received")
private String received;
#SerializedName("ver")
private int ver;
#SerializedName("double_spend")
private boolean double_spend;
#SerializedName("vin_sz")
private int vin_sz;
#SerializedName("vout_sz")
private int vout_sz;
#SerializedName("confirmations")
private int confirmations;
#SerializedName("inputs")
private List<Inputs> inputs;
#SerializedName("outputs")
private List<Outputs> outputs;
public int getBlock_height() {
return block_height;
}
public void setBlock_height(int block_height) {
this.block_height = block_height;
}
public int getBlock_index() {
return block_index;
}
public void setBlock_index(int block_index) {
this.block_index = block_index;
}
public String getHash() {
return hash;
}
public void setHash(String hash) {
this.hash = hash;
}
public List<String> getAddresses() {
return addresses;
}
public void setAddresses(List<String> addresses) {
this.addresses = addresses;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public int getFees() {
return fees;
}
public void setFees(int fees) {
this.fees = fees;
}
public int getSize() {
return size;
}
public void setSize(int size) {
this.size = size;
}
public String getPreference() {
return preference;
}
public void setPreference(String preference) {
this.preference = preference;
}
public String getRelayed_by() {
return relayed_by;
}
public void setRelayed_by(String relayed_by) {
this.relayed_by = relayed_by;
}
public String getReceived() {
return received;
}
public void setReceived(String received) {
this.received = received;
}
public int getVer() {
return ver;
}
public void setVer(int ver) {
this.ver = ver;
}
public boolean getDouble_spend() {
return double_spend;
}
public void setDouble_spend(boolean double_spend) {
this.double_spend = double_spend;
}
public int getVin_sz() {
return vin_sz;
}
public void setVin_sz(int vin_sz) {
this.vin_sz = vin_sz;
}
public int getVout_sz() {
return vout_sz;
}
public void setVout_sz(int vout_sz) {
this.vout_sz = vout_sz;
}
public int getConfirmations() {
return confirmations;
}
public void setConfirmations(int confirmations) {
this.confirmations = confirmations;
}
public List<Inputs> getInputs() {
return inputs;
}
public void setInputs(List<Inputs> inputs) {
this.inputs = inputs;
}
public List<Outputs> getOutputs() {
return outputs;
}
public void setOutputs(List<Outputs> outputs) {
this.outputs = outputs;
}
}
Code to MainActivity.java
public class MainActivity extends AppCompatActivity {
private String URL = "https://api.blockcypher.com/v1/btc/main/txs/b6f6991d03df0e2e04dafffcd6bc418aac66049e2cd74b80f14ac86db1e3f0da";
private RequestQueue mRequestQueue;
private Gson gson;
private static ArrayList<Cyphers> cyphersList = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(mRequestQueue == null){
mRequestQueue = Volley.newRequestQueue(this);
}
requestJsonThroughVolley();
}
private void requestJsonThroughVolley(){
JsonObjectRequest objectRequest = new JsonObjectRequest(Request.Method.GET, URL, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
gson = new Gson();
Cyphers cyphers;
cyphers = gson.fromJson(response.toString(), Cyphers.class);
String block_height = String.valueOf(cyphers.getBlock_height());
String total = String.valueOf(cyphers.getTotal());
String fee = String.valueOf(cyphers.getFees());
String size = String.valueOf(cyphers.getSize());
String received = String.valueOf(cyphers.getReceived());
String confirmations = String.valueOf(cyphers.getConfirmations());
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
mRequestQueue.add(objectRequest);
}
private void showalert(String title, String msj)
{
AlertDialog.Builder MSGbox = new AlertDialog.Builder(this);
MSGbox.setTitle(title);
String mensaje = msj;
MSGbox.setMessage(mensaje)
.setPositiveButton("OKEY", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertDialog = MSGbox.create();
alertDialog.show();
}
}
Try below code if you are using Gson library
private void DataAdapter(String json)
{
JsonObject jsonObject = gson.fromJson(json, JsonElement.class).getAsJsonObject();
String block_height = jsonObject.get("block_height").getAsString();
String total = jsonObject.get("total").getAsString();
String fee = jsonObject.get("fee").getAsString();
String size = jsonObject.get("size").getAsString();
String received = jsonObject.get("received").getAsString();
String confirmations = jsonObject.get("confirmations").getAsString();
showalert(TxsHashs,received);
}
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 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 :)
I have following JSON returned from server
{
"matches": [
{
"unique_id": 1122278,
"date": "2018-01-24T00:00:00.000Z",
"team-2": "India",
"team-1": "South Africa",
"type": "Test",
"dateTimeGMT": "2018-01-24T08:00:00.000Z",
"squad": true,
"toss_winner_team": "India",
"matchStarted": true
},
{
"unique_id": 1116929,
"team-2": "India Under-19s",
"team-1": "Bangladesh Under-19s",
"type": "YouthODI",
"date": "2018-01-25T00:00:00.000Z",
"dateTimeGMT": "2018-01-25T21:30:00.000Z",
"squad": true,
"toss_winner_team": "India Under-19s",
"winner_team": "India Under-19s",
"matchStarted": true
},
{
"unique_id": 1115781,
"team-2": "England",
"team-1": "New Zealand",
"type": "Test",
"date": "2018-03-29T00:00:00.000Z",
"dateTimeGMT": "2018-03-29T22:00:00.000Z",
"squad": false,
"matchStarted": false
}
],
"v": "1",
"ttl": 43,
"provider": {
"source": "Various",
"url": "https://cricapi.com/",
"pubDate": "2018-01-27T13:18:55.717Z"
},
"creditsLeft": 250
}
Using Volley library and gson.
I am trying to push JSON array match to Match Model(Pojo). I think I can insert it using a loop, but there any other way to add all JSON array to model?
public class Main2Activity extends AppCompatActivity {
RecyclerView recyclerView;
ArrayList<Match> matches;
MyAdapter myAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recylcer_1);
recyclerView=(RecyclerView) findViewById(R.id.recyler);
myAdapter=new MyAdapter(matches);
RecyclerView.LayoutManager layoutManager=new LinearLayoutManager(getApplicationContext());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAnimation(n);
recyclerView.setAdapter(myAdapter);
callCricket();
}
public void callCricket() {
CallApi callApi = new CallApi();
callApi.setVolleyInterface(new VolleyInterface() {
#Override
public void onSucess(String string) {
Log.d("ApiCall_success", string);
Gson gson = new Gson();
Type type = new TypeToken<ArrayList<Match>>(){}.getType();
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(string);
JSONArray jsonArray = jsonObject.getJSONArray("matches");
matches.addAll(gson.fromJson(jsonArray,type));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onError(String string) {
}
});
}
}
I have tried using gson but I got an error.
Create pojo classes as below as per your JSON by using jsonschema2pojo:
There are No Need of loop in GSON to insert data in pojo classes.
Example.java
package com.example;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Example {
#SerializedName("matches")
#Expose
private List<Match> matches = null;
#SerializedName("v")
#Expose
private String v;
#SerializedName("ttl")
#Expose
private Integer ttl;
#SerializedName("provider")
#Expose
private Provider provider;
#SerializedName("creditsLeft")
#Expose
private Integer creditsLeft;
public List<Match> getMatches() {
return matches;
}
public void setMatches(List<Match> matches) {
this.matches = matches;
}
public String getV() {
return v;
}
public void setV(String v) {
this.v = v;
}
public Integer getTtl() {
return ttl;
}
public void setTtl(Integer ttl) {
this.ttl = ttl;
}
public Provider getProvider() {
return provider;
}
public void setProvider(Provider provider) {
this.provider = provider;
}
public Integer getCreditsLeft() {
return creditsLeft;
}
public void setCreditsLeft(Integer creditsLeft) {
this.creditsLeft = creditsLeft;
}
}
Match.java
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Match {
#SerializedName("unique_id")
#Expose
private Integer uniqueId;
#SerializedName("date")
#Expose
private String date;
#SerializedName("team-2")
#Expose
private String team2;
#SerializedName("team-1")
#Expose
private String team1;
#SerializedName("type")
#Expose
private String type;
#SerializedName("dateTimeGMT")
#Expose
private String dateTimeGMT;
#SerializedName("squad")
#Expose
private Boolean squad;
#SerializedName("toss_winner_team")
#Expose
private String tossWinnerTeam;
#SerializedName("matchStarted")
#Expose
private Boolean matchStarted;
#SerializedName("winner_team")
#Expose
private String winnerTeam;
public Integer getUniqueId() {
return uniqueId;
}
public void setUniqueId(Integer uniqueId) {
this.uniqueId = uniqueId;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public String getTeam2() {
return team2;
}
public void setTeam2(String team2) {
this.team2 = team2;
}
public String getTeam1() {
return team1;
}
public void setTeam1(String team1) {
this.team1 = team1;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDateTimeGMT() {
return dateTimeGMT;
}
public void setDateTimeGMT(String dateTimeGMT) {
this.dateTimeGMT = dateTimeGMT;
}
public Boolean getSquad() {
return squad;
}
public void setSquad(Boolean squad) {
this.squad = squad;
}
public String getTossWinnerTeam() {
return tossWinnerTeam;
}
public void setTossWinnerTeam(String tossWinnerTeam) {
this.tossWinnerTeam = tossWinnerTeam;
}
public Boolean getMatchStarted() {
return matchStarted;
}
public void setMatchStarted(Boolean matchStarted) {
this.matchStarted = matchStarted;
}
public String getWinnerTeam() {
return winnerTeam;
}
public void setWinnerTeam(String winnerTeam) {
this.winnerTeam = winnerTeam;
}
}
Provider.java
package com.example;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
public class Provider {
#SerializedName("source")
#Expose
private String source;
#SerializedName("url")
#Expose
private String url;
#SerializedName("pubDate")
#Expose
private String pubDate;
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getPubDate() {
return pubDate;
}
public void setPubDate(String pubDate) {
this.pubDate = pubDate;
}
}
In your Activity class do coding like this :
public static final String TAG = DoctorHome.class.getSimpleName();
ArrayList<DoctorsCatPojo> doctorCatList = new ArrayList<>();
DoctorsCatAdapter doctorsCatAdapter;
RecyclerView recyclerView;
private void getDoctorCategory() {
pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
String url = Constant.DOCTOR_CATEGORY;
Log.e("URL",""+url);
JsonObjectRequest request = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.e("onResponse",""+response);
try {
status = response.getString("status");
if(status.equals("success")){
String info = response.getString("list");
JSONArray jsonArray = new JSONArray(info);
Gson gson = new Gson();
Type listType = new TypeToken<ArrayList<DoctorsCatPojo>>() {
}.getType();
doctorCatList = gson.fromJson(jsonArray.toString(), listType);
if(doctorCatList!=null && doctorCatList.size()!=0){
doctorsCatAdapter = new DoctorsCatAdapter(DoctorHome.this,doctorCatList);
recyclerView.setAdapter(doctorsCatAdapter);
Log.d(TAG, response.toString());
}
}
else {
message = response.getString("message");
// Toast.makeText(getApplicationContext(),""+message,Toast.LENGTH_SHORT).show();
pDialog.hide();
}
} catch (Exception e) {
Log.e("Exception",""+e);
e.printStackTrace();
}
pDialog.hide();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("error",""+error.getMessage());
pDialog.hide();
}
});
AppController.getInstance(DoctorHome.this).addToRequestQueue(request, "doctor_category");
}
your adapter class will be like this :
public class DoctorsCatAdapter extends RecyclerView.Adapter<DoctorsCatAdapter.MyViewHolder> {
ArrayList <DoctorsCatPojo> doctorCatList;
Context context;
public DoctorsCatAdapter( Context context,ArrayList<DoctorsCatPojo> doctorCatList) {
this.doctorCatList = doctorCatList;
this.context= context;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.doctors_category_row, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(final MyViewHolder holder, int position) {
DoctorsCatPojo doc = doctorCatList.get(position);
// holder.doctorsCatImg.setImageURI(doc.getCategory_img());
if(doc.getCategory_name()!=null){
holder.doctorsCatName.setText(doc.getCategory_name());
}
if(doc.getCategory_img()!=null){
Picasso.with(context)
.load(doc.getCategory_img().replace(" ", "%20").trim())
.placeholder(R.drawable.no_image)
.into(holder.doctorsCatImg);
}
}
#Override
public int getItemCount() {
return doctorCatList.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
ImageView doctorsCatImg;
TextView doctorsCatName;
MyViewHolder(final View view) {
super(view);
itemView.setOnClickListener(this);
doctorsCatImg = (ImageView)view.findViewById(R.id.doctorsCatImg);
doctorsCatName = (TextView) view.findViewById(R.id.doctorsCatName);
}
#Override
public void onClick(View view) {
doctorCatList.get(getPosition()).getCategory_id();
((DoctorHome)context).callDoctorListActivity(doctorCatList.get(getPosition()).getCategory_id(),doctorCatList.get(getPosition()).getCategory_name());
}
}
}
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 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.