How to write Gson for this code? - java

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);

Related

How to convert JsonArray object to Array of string to be used on spinner java android?

I have created an API, (check the picture)
and i need to get sumber[] from api and store it to my spinner. But i got error:
is there any best practice way to cast the jsonArray object to my spinner?
java.lang.ArrayStoreException: source[0] of type Item_sumber cannot be stored in destination array of type java.lang.String[]
Activity_addcontact.java
private ArrayList Arraylist_sumber, Arraylist_budget;
....
Call<Formdata> call = jsonPlaceHolderApi.getFormdata();
call.enqueue(new Callback<Formdata>() {
#Override
public void onResponse(Call<Formdata> call, Response<Formdata> response) {
Formdata jsonResponse = response.body();
String[] string_sumber = Arrays.copyOf(jsonResponse.getSumber(), jsonResponse.getSumber().length,String[].class);
ArrayAdapter<String> adapter_sumber = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, string_sumber);
dropdown_sumber.setAdapter(adapter_sumber);
dropdown_sumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
id_sumber = String.valueOf(i + 1);
}
Item_sumber
private String id;
private String nama_sumber;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNama_sumber() {
return nama_sumber;
}
public void setNama_sumber(String nama_sumber) {
this.nama_sumber = nama_sumber;
}
Formdata.java
public class Formdata {
private Item_sumber[] sumber;
private Item_budget[] budget;
public Item_sumber[] getSumber() {
return sumber;
}
public void setSumber(Item_sumber[] sumber) {
this.sumber = sumber;
}
public Item_budget[] getBudget() {
return budget;
}
public void setBudget(Item_budget[] budget) {
this.budget = budget;
}
}
You can use ObjectMapper class of Jackson libraries.
It will convert the response that are coming from API in object,
syntax--
objectMapper om = new ObjectMapper();
om.readValue(response.body().asString(),FormData[].class);
I think, it would help you.
you are storing Object elements from 'sumber' array in string array 'string_sumber'.
try this
JSONArray sumberArray = jsonresponse.getJsonArray("sumber");
String[] string_sumber = new String[sumberArray.length];
for(int i=0;i<sumberArray.length;i++){
string_summber[i] = get(i).toString();
}
My friend helped me, and I've solved it.
Make and convert the jsonarray to Arraylist (object)
Make Iteration so you can store it to Array of String[]
Done! now cast it to your spinner
Call<Formdata> call = jsonPlaceHolderApi.getFormdata();
call.enqueue(new Callback<Formdata>() {
#Override
public void onResponse(Call<Formdata> call, Response<Formdata> response) {
Formdata jsonResponse = response.body();
ArrayList<Item_sumber> arraylist_sumber = new ArrayList<>(Arrays.asList(jsonResponse.getSumber()));
ArrayList<String> list_sumber = new ArrayList<>();
for (int i = 0; i < jsonResponse.getSumber().length; i++) {
Item_sumber item_sumber = arraylist_sumber.get(i);
list_sumber.add(item_sumber.getId());
}
string_sumber = new String[arraylist_sumber.size()];
/* If 2 dimensional array convert
private String[][] string_sumber2, string_budget2;
string_sumber2 = new String[arraylist_sumber.size()][6];
for (int i = 0; i < jsonResponse.getSumber().length; i++) {
Item_sumber data = arraylist_sumber.get(i);
string_sumber2[i] = new String[]{data.getId(),data.getNama_sumber()};
}*/
for (int i = 0; i < jsonResponse.getSumber().length; i++) {
Item_sumber data = arraylist_sumber.get(i);
string_sumber[i] = data.getNama_sumber();
}
ArrayAdapter<String> adapter_sumber = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, string_sumber);
dropdown_sumber.setAdapter(adapter_sumber);
dropdown_sumber.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
id_sumber = String.valueOf(i + 1);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
#Override
public void onFailure(Call<Formdata> call, Throwable t) {
call.cancel();
}
});

Unable to save ArrayList value in Shared Preference in Andorid

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);

Parsing a Json to a ListView

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);
}

how can i compare a json with < or >

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.

How can I pass object from ArrayList to new Activity and then receive that? [duplicate]

This question already has answers here:
How to pass ArrayList<CustomeObject> from one activity to another? [duplicate]
(3 answers)
Closed 7 years ago.
I try pass an object to new activity but I have a problem. My ArrayList use another class in this way:
ArrayList<ListData> myList = new ArrayList<>();
All is great, I'm adding to mList a few objects and my listview work fine.
I try pass an object after click in this way:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
ListData listdata = myList.get(position);
ListData dataToSend = new ListData();
dataToSend.setStrefa(listdata.getStrefa());
dataToSend.setDzielnica(listdata.getDzielnica());
dataToSend.setAdres(listdata.getAdres());
dataToSend.setKryteria(listdata.getKryteria());
dataToSend.setTelefon(listdata.getTelefon());
dataToSend.setData(listdata.getData());
Intent intent = new Intent(Zlecenia.this, Zlecenie.class);
intent.putExtra("myData", dataToSend);
startActivity(intent);
overridePendingTransition(R.anim.fade_in, R.anim.no_animation);
}
});
Here is a problem because "bundle.putParcelableArrayList("listdata", listdata);" is marked on red. This forces on me using extends Parcelable in ListData Class but when I added this extends then my ArrayList is empty. What schould I do?
My ListData:
public class ListData implements Parcelable{
String Strefa;
String Adres;
String Kryteria;
String Telefon;
String Data;
String Dzielnica;
String Ilosc;
/* Zlecenia */
public String getStrefa() {
return Strefa;
}
public void setStrefa(String strefa) {
this.Strefa = strefa;
}
public String getAdres() {
return Adres;
}
public void setAdres(String adres) {
this.Adres = adres;
}
public String getKryteria() {
return Kryteria;
}
public void setKryteria(String kryteria) {
this.Kryteria = kryteria;
}
public String getTelefon() {
return Telefon;
}
public void setTelefon(String telefon) {
this.Telefon = telefon;
}
public String getData() {
return Data;
}
public void setData(String data) {
this.Data = data;
}
/* Statystyki */
public String getDzielnica() {
return Dzielnica;
}
public void setDzielnica(String dzielnica) {
this.Dzielnica = dzielnica;
}
public String getIlosc() {
return Ilosc;
}
public void setIlosc(String ilosc) {
this.Ilosc = ilosc;
}
public ListData() {
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(Strefa);
dest.writeString(Dzielnica);
dest.writeString(Adres);
dest.writeString(Kryteria);
dest.writeString(Telefon);
dest.writeString(Data);
}
private ListData(Parcel in) {
Strefa = in.readString();
Dzielnica = in.readString();
Adres = in.readString();
Kryteria = in.readString();
Telefon = in.readString();
Data = in.readString();
}
public static final Parcelable.Creator<ListData> CREATOR
= new Parcelable.Creator<ListData>() {
#Override
public ListData createFromParcel(Parcel in) {
return new ListData(in);
}
#Override
public ListData[] newArray(int size) {
return new ListData[size];
}
};
}
Try this in your class
public class ListData implements Serializable

Categories

Resources