I am getting array list from Global class and getting value with index , but i am getting error on sub-string is that (Sub-string cannot be resolved).
Glide.with(ChooseCategoryProductsActivity.this)
.load("file:///" + GlobalClass.IMAGES_PATH + "/" + GlobalClass.categoriesAr.get(GlobalClass.currentIndex)
.substring(categoriesAr.get(GlobalClass.currentIndex)
.lastIndexOf("/") + 1))
.placeholder(R.drawable.stub)
.into(categoryImage);
Category class :
public class Category {
public String catId = "";
public String catName = "";
public String catImage = "";
public String catDesc = "";
public String displayOrder = "";
public String createdDate = "";
public ArrayList<Product> productsAr = new ArrayList<Product>();
public Category(String catId, String catName, String catImage, String catDesc, String displayOrder, String createdDate) {
this.catId = catId;
this.catName = catName;
this.catImage = catImage;
this.catDesc = catDesc;
this.displayOrder = displayOrder;
this.createdDate = createdDate;
}
}
As you Declared
ArrayList<Category> categoriesAr = new ArrayList<Category>();
subString() is only applied on String not on custom object
There is no such method called subString() with glide as far as i know and hence the compile time error Sub string cannot be resolved. subString works with String
So finally i did just like following, but i don't know whether is it right or not :
GlobalClass.categoriesAr.get(GlobalClass.currentIndex).toString().substring(categoriesAr.get(GlobalClass.currentIndex)
Related
I have this kind of JSON response
{"error":false,"country":"United Kingdom","country_id":"903",
"currency":"GBP","product_list":["5","10","15","20","25","30","40","50"]}
And I am able to parse country, country_id, and currency without a problem, problem starts with the product list when I am trying to parse it! below the code
try {
boolean error = response.getBoolean("error");
if (!error){
String country = response.getString("country");
int country_id = response.getInt("country_id");
String currency = response.getString("currency");
List<Tarif> tarifs = new
Gson().fromJson(response.getJSONArray("product_list").toString(), new
TypeToken<List<Tarif>>(){}.getType());
new DtoneTarifs(country, country_id, currency, tarifs);
}
}
And here is my Tarif and Other Class
public class Tarifs {
public String country;
public int country_id;
public String currency;
public List<Tarif> tarifList;
public Tarifs (String country, int country_id, String currency, List<Tarif> tarif){
this.country = country;
this.country_id = country_id;
this.currency = currency;
this.tarifList = tarif;
}
}
I want to fill the product_list in Tarif class where only one parameter accept and show them in recycler_view
{"error":false,"country":"United Kingdom","country_id":"903",
"currency":"GBP","product_list":["5","10","15","20","25","30","40","50"]}
You can see that product_list is JSON Array of string values. But you are converting it into list of Tarif type. It should be converted into list of string type.
Either set values of Tarif as custom objects to JSON Array or change your list type to string.
It should be like this:
try {
boolean error = response.getBoolean("error");
if (!error){
String country = response.getString("country");
int country_id = response.getInt("country_id");
String currency = response.getString("currency");
List<String> tarifs = new
Gson().fromJson(response.getJSONArray("product_list").toString(), new
TypeToken<List<String>>(){}.getType());
Tarifs result = new Tarifs(country, country_id, currency, tarifs);
}
}
Tarifs Class
public class Tarifs {
public String country;
public int country_id;
public String currency;
public List<String> tarifList;
public Tarifs (String country, int country_id, String currency, List<String> tarif){
this.country = country;
this.country_id = country_id;
this.currency = currency;
this.tarifList = tarif;
}
}
Here you go!
I am working on FatSecretAPI and trying to get the recipes list.
for accessing that need to send some parameters which are:
oauth_consumer_key String --Your API key when you registered as a developer
oauth_signature_method String-- The method used to generate the signature (only HMAC-SHA1 is supported)
oauth_timestamp Int-- The date and time, expressed in the number of seconds since January 1, 1970 00:00:00 GMT. The timestamp value must be a positive integer and must be equal or greater than the timestamp used in previous requests
oauth_nonce String --A randomly generated string for a request that can be combined with the timestamp to produce a unique value
oauth_version String-- MUST be "1.0"
oauth_signature String-- The signature, a consistent reproducible concatenation of the request elements into a single string. The string is used as an input in hashing or signing algorithms.
method String --MUST be "recipes.search"
And in response I will these:
recipe_id – the unique recipe identifier.
recipe_name – the name of the recipe.
recipe_url – URL of this recipe item on www.fatsecret.com.
recipe_description – A short description of the recipe.
recipe_image – URL of this recipe item's default image, only if this is available
I have a json response like this:
{
"recipes":{
"recipe":{
"recipe_description":"Healthy fish with a tasty sauce.",
"recipe_id":"91",
"recipe_image":"http:\/\/www.fatsecret.com\/static\/recipe\/bf0c5912-9cf8-4e7a-b07a-6703c4b77082.jpg",
"recipe_name":"Baked Lemon Snapper",
"recipe_url":"http:\/\/www.fatsecret.com\/recipes\/baked-lemon-snapper\/Default.aspx"
}
}
}
And my Apicall looks like:
public interface MyCallApi {
String BASE_URL = "http://platform.fatsecret.com/";
#POST("rest/server.api/")
Call<Recipes> getRecipes(#Query("oauth_consumer_key") String oauth_consumer_key,
#Query("oauth_signature_method") String oauth_signature_method,
#Query("oauth_timestamp") int oauth_timestamp,
#Query("oauth_nonce") String oauth_nonce,
#Query("oauth_version") String oauth_version,
#Query("oauth_signature") String oauth_signature,
#Query("method") String method);
And my POJO class for recipes is like:
public class Recipes {
#SerializedName("recipe")
#Expose
private Recipe recipe;
public Recipe getRecipe() {
return recipe;
}
public void setRecipe(Recipe recipe) {
this.recipe = recipe;
}
#NonNull
#Override
public String toString() {
return "ClassPojo [recipe = " + recipe + "]";
}
}
And for the data inside the recipes object are:
public class Recipe {
#SerializedName("recipe_name")
#Expose
private String recipe_name;
#SerializedName("recipe_url")
#Expose
private String recipe_url;
#SerializedName("recipe_description")
#Expose
private String recipe_description;
#SerializedName("recipe_image")
#Expose
private String recipe_image;
#SerializedName("recipe_id")
#Expose
private String recipe_id;
public String getRecipe_name() {
return recipe_name;
}
public void setRecipe_name(String recipe_name) {
this.recipe_name = recipe_name;
}
public String getRecipe_url() {
return recipe_url;
}
public void setRecipe_url(String recipe_url) {
this.recipe_url = recipe_url;
}
public String getRecipe_description() {
return recipe_description;
}
public void setRecipe_description(String recipe_description) {
this.recipe_description = recipe_description;
}
public String getRecipe_image() {
return recipe_image;
}
public void setRecipe_image(String recipe_image) {
this.recipe_image = recipe_image;
}
public String getRecipe_id() {
return recipe_id;
}
public void setRecipe_id(String recipe_id) {
this.recipe_id = recipe_id;
}
#NonNull
#Override
public String toString() {
return "ClassPojo [recipe_name = " + recipe_name + "," +
" recipe_url = " + recipe_url + ", " +
"recipe_description = " + recipe_description + "," +
" recipe_image = " + recipe_image + "," +
" recipe_id = " + recipe_id + "]";
}
}
Retrofit implementations are:
public class RecipeActivity extends AppCompatActivity {
final static private String APP_METHOD = "GET";
final static private String APP_KEY = "here api key";
final static private String APP_SECRET = "ssecret key";
final static private String APP_URL = "http://platform.fatsecret.com/rest/server.api";
private static final String HMAC_SHA1_ALGORITHM = "HMAC-SHA1";
private static String paramify(String[] params) {
String[] p = Arrays.copyOf(params, params.length);
Arrays.sort(p);
return join(p, "&");
}
private static String join(String[] array, String separator) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i > 0)
b.append(separator);
b.append(array[i]);
}
return b.toString();
}
private static String nonce() {
Random r = new Random();
StringBuilder n = new StringBuilder();
for (int i = 0; i < r.nextInt(8) + 2; i++)
n.append(r.nextInt(26) + 'a');
return n.toString();
}
Long tsLong = System.currentTimeMillis() / 1000;
int ts = Integer.parseInt(tsLong.toString());
private static String[] generateOauthParams() {
return new String[]{
"oauth_consumer_key=" + APP_KEY,
"oauth_signature_method=HMAC-SHA1",
"oauth_timestamp=" +
Long.valueOf(System.currentTimeMillis() * 2).toString(),
"oauth_nonce=" + nonce(),
"oauth_version=1.0",
"format=json"};
}
private static String signature(String[] params) {
String[] p = {RecipeActivity.APP_METHOD, Uri.encode(RecipeActivity.APP_URL), Uri.encode(paramify(params))};
String s = join(p, "&");
SecretKey sk = new SecretKeySpec(APP_SECRET.getBytes(), HMAC_SHA1_ALGORITHM);
try {
Mac m = Mac.getInstance(HMAC_SHA1_ALGORITHM);
m.init(sk);
return Uri.encode(new String(Base64.encode(m.doFinal(s.getBytes()), Base64.DEFAULT)).trim());
} catch (java.security.NoSuchAlgorithmException | java.security.InvalidKeyException e) {
Log.w("FatSecret_TEST FAIL", e.getMessage());
return null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(MyCallApi.BASE_URL)
.build();
MyCallApi myCallApi = retrofit.create(MyCallApi.class);
Call<Recipes> call = myCallApi.getRecipes("c30f50a1c5474070b4db11a506d99666",
"HMAC-SHA1", ts
, nonce()
, "1.0", signature(generateOauthParams()),
"recipes.search");
call.enqueue(new Callback<Recipes>() {
#Override
public void onResponse(#NonNull Call<Recipes> call, #NonNull Response<Recipes> response) {
Log.i("if works", response.toString());
}
#Override
public void onFailure(#NonNull Call<Recipes> call, #NonNull Throwable t) {
Log.i("if not", t.getMessage());
}
});
}
}
But I am getting the mostly asked error. And I am not able to solve it on my own. I am new to retrofit. I don't know what and where I am doing wrong, kindly check the implementations and guide me to get the response successfully*. Remember I have to send those parameters along with the retrofit request.*
make one more pojo class like this ..
public class RecipeResponse{
#SerializedName("recipes")
private Recipes recipes;
public void setRecipes(Recipes recipes){
this.recipes = recipes;
}
public Recipes getRecipes(){
return recipes;
}
}
after that change api call when you used..
Call<RecipeResponse>
Is it possible to turn a two table(relational tabel) from sqlite in to a JSON object? I've googling but still cannot find a way to convert those table. So far, i've only manage to turn one table into JSON object. If it's possible, can you tell me how to do it? if it's not, can you give me an alternatives? thanks.
here's the code that turn one table to JSON object:
private JSONArray getResults()
{
Context context = this;
String myPath = String.valueOf(context.getDatabasePath("ekantin1.db"));// Set path to database
String myTable = DatabaseHelper.ORDER_TABLE_NAME;//Set name of table
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null );
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for( int i=0 ; i< totalColumn ; i++ )
{
if( cursor.getColumnName(i) != null )
{
try
{
if( cursor.getString(i) != null )
{
Log.d("TAG_NAME", cursor.getString(i) );
rowObject.put(cursor.getColumnName(i) , cursor.getString(i) );
}
else
{
rowObject.put( cursor.getColumnName(i) , "" );
}
}
catch( Exception e )
{
Log.d("TAG_NAME", e.getMessage() );
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
Log.d("TAG_NAME", resultSet.toString() );
Intent pass_data = new Intent(this,BluetoothOut.class);
pass_data.putExtra("pindah",resultSet.toString());
startActivity(pass_data);
return resultSet;
}
}
And this is my table in my DatabaseHelper :
//tabel order
public static final String ORDER_TABLE_NAME="tb_order";
public static final String COL_1="ORDERID";
public static final String COL_2="USERID";
public static final String COL_3="PASSWORD";
public static final String COL_4="MEJA";
public static final String COL_5="TOPUP";
public static final String COL_6="SALDO";
//tabel lineitems
public static final String LINEITEMS_TABLE_NAME="tb_lineitems";
public static final String COL1 = "FOODID";
public static final String COL2 = "PRICE";
public static final String COL3 = "NUM";
public static final String COL4 = "RES";
public static final String COL6 = "ORDERID_FK";
table line items and orderid related to each other where orderid in tb_order as PK and orderid_fk in tb_lineitems as FK.
A good way to export data from your database is to use Gson, which is Google's Json serialization/deserialization library.
Fetch your Objects from your database like normally, and then use Gson to convert it into Json and export it.
Here is an example of how you could do it.
private void exportDatabase() {
// Create an instance of Gson.
Gson gson = new Gson();
// You can easily convert Objects into Json.
MyItem item = new MyItem();
String json = gson.toJson(item);
// Fetch your items from your database.
ArrayList<MyItems> items = database.getAll();
// Arrays are a bit harder to convert, but not very.
json = gson.toJson(items, new TypeToken<ArrayList<MyItems>>(){}.getType());
// Now export it to some easily copy-pasted location.
System.out.println(json);
}
I have a listview that shows this paramaters. But 2 of the parameters returns the same value? How can I differentiate this two? Its email and voucher.
VoucherObj obj = new VoucherObj();
obj.customerID=item[0];
obj.type=item[1];
obj.name=item[2];
obj.searchStr=item[3]; <---- SAME PARAMETER
obj.searchStr=item[4]; <---- SAME PARAMETER
obj.branch=item[5];
obj.issued=item[6];
obj.expiration=item[7];
obj.status=item[8];
obj.vouchername=item[9];
obj.employeeid=item[10];
items.add(obj);
Voucher.class
public class VoucherObj {
public String customerID="";
public String type="";
public String name="";
public String email="";
public String voucher="";
public String branch="";
public String issued = "";
public String expiration="";
public String status = "";
public String vouchername = "";
public String employeeid = "";
public String searchStr;
}
If you'll have a static amount of items, you can declare the searchStr field of your VoucherObj as a static array with a fixed size. Assuming you're storing Strings, this would be:
String[] searchStr = new String[10];
If the number of items of that field is unknown, just use a more advanced data structure, for instance:
ArrayList<String> searchStr = new ArrayList<String>();
Afterwards you can use this method to add a value:
obj.searchStr.add("value1");
obj.searchStr.add("value2");
...
public class VoucherObj(){
int customerId;
..............
..............
ArrayList<String> searchStr;
..............
/*other parameters here*/
}
and in your main class use
obj.searchStr.add(item[3]);
obj.searchStr.add(item[4]);
I have trouble with a JSON array, and I really hope there is someone who can help me.
Lets say I have a class with JSON data and I'm sending "intent putextra" to another activity.
How can I change the value of null before I send it to another activity? I did a few prints to discover the null values and they are different, example :
Monday : null
Tuesday : 08:30 - 18:00
Wednesday : 09:00 - 17:00
**and so on.**
The problem is that --> I have all json data and I parsing them into objects, but I would like to before "intent.putextra" and send them to another activity finds null and replace them with "Closed"
so it will look like
Monday : Closed
Tuesday : 08:30 - 18:00
Wednesday : 09:00 - 17:00
EDIT
public class LocationBased extends ListActivity{
// JSON Node names
private static final String TAG_Location = "location_id";
private static final String TAG_Company = "company_id";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_PLACE = "place";
private static final String TAG_POSTAL = "postal";
private static final String TAG_CITY = "city";
private static final String TAG_MONDAY = "monday";
private static final String TAG_TUESDAY = "tuesday";
private static final String TAG_WEDNESDAY = "wednesday";
private static final String TAG_THURSDAY = "thursday";
private static final String TAG_FRIDAY = "friday";
private static final String TAG_SATURDAY = "saturday";
private static final String TAG_SUNDAY = "sunday";
private static final String TAG_TYPE = "type";
private static final String TAG_LAT = "lat";
private static final String TAG_LNG = "lng";
private static final String TAG_NOCAR = "nocar";
private static final String TAG = "Debug of Project"; //
private String a;
private String b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db = openOrCreateDatabase("mydb.db", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS gps_kordinater (ID INTEGER PRIMARY KEY AUTOINCREMENT, Latitude REAL, Longitude REAL);");
String query = "SELECT Latitude,Longitude FROM gps_kordinater WHERE Id = (SELECT MAX(Id) FROM gps_kordinater)";
Cursor cursor = db.rawQuery(query, null);
if(cursor != null)
{
cursor.moveToFirst();
a = cursor.getString(0);
b = cursor.getString(1);
}
String url = "http://webservice.XXX.XX/webservice/getLocationList.php?lat="+ a +"&lng="+ b +"";
Log.d(TAG, "Leyth URL = Lat : " + a +" Long : " + b);
// now enabled if disabled = ingen support for jb aka 4.0
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
try {
for(int i = 0; i < json.length(); i++){
JSONObject c = json.getJSONObject(i);
String location_id = c.getString(TAG_Location);
String company_id = c.getString(TAG_Company);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String place = c.getString(TAG_PLACE);
String postal = c.getString(TAG_POSTAL);
String city = c.getString(TAG_CITY);
String monday = c.getString(TAG_MONDAY);
String tuesday = c.getString(TAG_TUESDAY);
String wednesday = c.getString(TAG_WEDNESDAY);
String thursday = c.getString(TAG_THURSDAY);
String friday = c.getString(TAG_FRIDAY);
String saturday = c.getString(TAG_SATURDAY);
String sunday = c.getString(TAG_SUNDAY);
String type = c.getString(TAG_TYPE);
String lat = c.getString(TAG_LAT);
String lng = c.getString(TAG_LNG);
String nocar = c.getString(TAG_NOCAR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_Location, location_id);
map.put(TAG_Company, company_id);
map.put(TAG_NAME, name);
map.put(TAG_ADDRESS, address);
map.put(TAG_PLACE, place);
map.put(TAG_POSTAL, postal);
map.put(TAG_CITY, city);
map.put(TAG_MONDAY, monday);
map.put(TAG_TUESDAY, tuesday);
map.put(TAG_WEDNESDAY, wednesday);
map.put(TAG_THURSDAY, thursday);
map.put(TAG_FRIDAY, friday);
map.put(TAG_SATURDAY, saturday);
map.put(TAG_SUNDAY, sunday);
map.put(TAG_TYPE, type);
map.put(TAG_LAT, lat);
map.put(TAG_LNG, lng);
map.put(TAG_NOCAR, nocar);
// Log.d(TAG, "Leyth Days = Mandag : " + monday +" Onsdag : " + wednesday);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_LAT, TAG_LNG, TAG_POSTAL }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
String mandag = ((TextView) view.findViewById(R.id.mandag)).getText().toString();
String tirsdag = ((TextView) view.findViewById(R.id.tirsdag)).getText().toString();
String onsdag = ((TextView) view.findViewById(R.id.onsdag)).getText().toString();
String torsdag = ((TextView) view.findViewById(R.id.torsdag)).getText().toString();
String fredag = ((TextView) view.findViewById(R.id.fredag)).getText().toString();
String lordag = ((TextView) view.findViewById(R.id.lordag)).getText().toString();
String sondag = ((TextView) view.findViewById(R.id.sondag)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), dk.mitaffald.maps.MainActivity.class);
in.putExtra(TAG_LAT, name);
in.putExtra(TAG_LNG, cost);
in.putExtra(TAG_Company, description);
in.putExtra(TAG_MONDAY, mandag);
in.putExtra(TAG_TUESDAY, tirsdag);
in.putExtra(TAG_WEDNESDAY, onsdag);
in.putExtra(TAG_THURSDAY, torsdag);
in.putExtra(TAG_FRIDAY, fredag);
in.putExtra(TAG_SATURDAY, lordag);
in.putExtra(TAG_SUNDAY, sondag);
startActivity(in);
}
});
}
}
I am also suffering for this problem in past but i do not know this is good solution but it works for me. Hope it is usefull to you also.
String jsonObject_string ;
try {
if (jsonObject != null) {
// ur stuff when not null
}
} catch (Exception e) {
// TODO: handle exception
// when null it automatic fill value
jsonObject_string = "Closed";
}
As I understand you want to replace any null string with a specific string , say "Closed".
This doesn't have anything todo with JSON, if this were my code I would do a simple check before adding those values to my intent. the code will look something like this:
Intent in = new Intent(getApplicationContext(), dk.mitaffald.maps.MainActivity.class);
in.putExtra(TAG_LAT, name == null ? "Closed" : name);
in.putExtra(TAG_LAT, cost== null ? "Closed" : cost);
in.putExtra(TAG_Company, description == null ? "Closed" : description );
in.putExtra(TAG_MONDAY, mandag == null ? "Closed" : mandag);
....
And so on.
name == null ? "Closed" : name ;
Simple asks if name is null then the value is closed, else return name.
it is the same as :
if (name == null){
in.putExtra(TAG_LAT, "Closed");
} else {
in.putExtra(TAG_LAT, name);
}
I hope that is what you're looking for
Why not try to replace all null strings in the JSON as a string before you parse the JSON file/object?
Possible other solution could be looping through every object checking if they're null. then replacing that for Closed
EDIT:
Load the JSON object as a string and then replace all null to Closed like this:
String JSON = JsonObject.toString();
JSON.replace("null", "Closed");
EDIT 2:
add this below JSONArray json = jParser.getJSONFromUrl(url);:
String s = json.toString(); // converts json object to string
json.replace("null", "Closed"); // replaces null for Closed
JSONArray json = new JSONArray(s); // converts back to json object
if(c.getString(TAG_MONDAY!=null && c.getString(TAG_MONDAY).length>0 && !(c.getString(TAG_MONDAY).equals("")))
{
String monday=c.getString(TAG_MONDAY);
}
else
{
String monday="Closed";
}