Get image from server and sets to int array in Android - android

I want to take image in integer Array just like when you take R.drawable.img in integer array.
e.g : int[] images = {R.drawable.a , R.drawable.b , R.drawable.c , R.drawable.d};
I want same like this when you take image from server.
Declaration of Array:
String images[] = new String[1000];
Get Image from server and sets it to int array which is not happening.
public void onResponse(String response) {
Log.d("TAG", "Message Response: " + response.toString());
hideDialog();
try {
JSONObject jsonObj = new JSONObject(response);
boolean error = false;
p = jsonObj.getJSONArray("response");
for (int i = 0 ; i < p.length(); i++) {
JSONObject c = p.getJSONObject(i);
String profilepicture = c.getString("profile_picture");
byte[] decodedString = Base64.decode(profilepicture, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
Drawable drawable = new BitmapDrawable(getResources(),decodedByte);
images[i] = drawable;
}
The drawable values is android.graphics.drawable.BitmapDrawable#269a3b6d. But it not sets on the integer array.

You're getting a Drawable. You can't save a Drawable to an integer array or a String array- you have to make it a Drawable array. This approach is really NOT recommended btw- you're storing all of your images in memory, which will take a lot of memory. If its a non-trivial number you'll likely hit an OOM exception. For that matter, sending down all these images as Base64 encoded strings is not recommended either. The better way to do things is to have the server send down a URL of the image to download, and to download it only when you're sure you need it.

create an array for drawables then it would work, and you can get the image from that array via its integer index. but the case you are trying is that, you would have got that number BitmapDrawable#269a3b6d from debugging the code? right? this is a reference to the object in the memorey and not an integer! so don't try to put it in the integer array.
now either make your array type to drawable or change your scenario!

Related

How to set a JSONObject default string for a null value

I am passing data to a recycler view using JSON, which works perfectly.
The problem is this, I want to alter the fetched json data. Let's say the user doesn't upload a profile image, that means the database field for image would be blank and our json wont parse any data for data.
So I want to set to a deafault url string if image == null
Heres what ive tried
//traversing through all the object
for (int i = 0; i < array.length(); i++) {
//getting product object from json array
JSONObject allTime = array.getJSONObject(i);
//adding the product to product list
allTimeEarnersList.add(new LeaderProfile(
allTime.getInt("id"),
allTime.getString("image"),
allTime.getString("username"),
allTime.getInt("earnings")
));
//My attempt to set a default value
if(allTime.getString("image").equals(null)){
allTime.put("image", "https://10.0.0.0/uploads/blank.png");
}
}
This doesn't work, it doesn't alter the output at all.
It is obvious i'm not doing this right.
Please how can I go about this? what is the best way to achieve this?
You aren't putting the value back into the object after you use the .put in the JSON, to avoid blanks/null in an object it's recommended to have a default value in case of nulls in your initializer.
public LeaderProfile(int id, String image, String username, int earnings) {
this.id = id;
if(image.equals("") || image.equals(null) ){
this.image = "defaulturl.png";
}else{
this.image = image;
}
this.username = username;
this.earnings = earnings;
}
Try this code block
if(allTime.getString("image") != null){
//set imageview glide or picasso
}else{
//set image view glide or picasso but R.drawable.empty_avatar
}

Saving Multiple Values in a Key with JSON

I tried to do it with multiple Shared Preferences keys, but it goes quiet complicated.
I saw some said that it is possible with JSON, but have no idea how to do it.
My app has many items in ListView, and I want to save several values in each item.
You can imagine a contact management app.
When the Item(person name) is clicked, you can check the values like phone number, address, and picture. And of course, they can be edited, added and deleted.
Is it possible to save values in single KEY with JSON?
So that I can load the values for each item when it is clicked.
To be able to save multiple values inside a jsonObject you can do this
try {
JSONObject Contacts = new JSONObject();
Contacts.put("Name", "Saul Goodman");
Contacts.put("Address", "Ocean Drive");
Contacts.put("Phone", "13456");
Contacts.put("Contacts", Contacts);
} catch (JSONException e) {
e.printStackTrace();
}
So that will create a structure like this
"Contacts":{
"Name":"Saul Goodman",
"Address":"Ocean Drive",
"Phone":"123456"
}
};
To retrieve this values you should do this
JSONArray array = object.getJSONArray("Contacts");
for(int i = 0; i < array.length; i++) {
JSONObject object = (JSONObject) array.get(i);
String name = object.get("Name");
String address = object.get("Address");
String phone = object.get("Phone");
//you also can use object.getString(""); to get the strings
}
hope it helps
Happy coding !

Android, Iterate over JSON-fied dictionary

I have the following string, which was created using javascript JSON. (It's passed from a Webview to the native code using JavascriptInterface.)
{"var1":1,"var2":8}
How do I convert that into an object and then iterate over the key/value pairs? The names of the keys are NOT known in advance.
I have seen this JSON Array iteration in Android/Java and this Converting json string to java object? and this how to convert JSON string to object in JAVA android.
None of those seem to fit with my example, which is a dictionary with unknown key names. At least, it's certainly not clear to me which of the 15+ answers is relevant for my case.
The org.json library comes "for free" with Android, so I'd go with that. Usage when you don't know the keys ahead of time could be something like this:
try {
JSONObject jsonObject = new JSONObject(/* your json String here */);
Iterator<String> keys = jsonObject.keys();
while (keys.hasNext()) {
String key = keys.next();
String value = jsonObject.getString(key);
// do whatever you want with key/value
}
}
catch (JSONException e) {
// thrown when:
// - the json string is malformed (can't be parsed)
// - there's no value for a requested key
// - the value for the requested key can't be coerced to String
}
You can use it by converting the getting the json length like this:-
JSONObject obj = new JSONObject(response);
for (int i = 0; i < obj.length(); i++) {
//getting the json object of the particular index inside the array
JSONObject heroObject = obj.getJSONObject(i);
String aka=heroObject.getString("your key here");
}

Android Load Image From URL Into ListView

I have a ListView onto which I would like to load image from url where images names are an ID.jpg (eg: 1.jpg / 2.jpg / 3.jpg.. etc). The IDs are from the database, however the images loaded into my ListView for all rows is one image (1.jpg).
txtDate.setText(Request_Date.get(position));
txtTime.setText(Request_Time.get(position));
//ivImage.setImageResource(imgid[position]); <-- this works from drawable and not from database
Picasso.with(context).load(url_poster + request_eventID + ".jpg").into(ivImage);
The request_eventID are IDs from DB, this is my problem, it only returns 1 (and not the rest of the IDs) so therefore only 1.jpg is loaded into the ListView on all rows.
EDIT:
How I retrieve IDs
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("read_columns");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
String request_date = jsonChildNode.optString("Date");
String request_time = jsonChildNode.optString("Time");
request_eventID = jsonChildNode.optString("EID");
arrRequest_Date.add(request_date);
arrRequest_Time.add(request_time);
arrRequest_EID.add(request_eventID);
Note that I can see all IDs if I do a System.out.println("IDs" +request_eventID)
Ok, just as I suspected, I played around with the code a bit and indeed get(position) was what I needed on the IDs.
Solution:
Picasso.with(context).load(url_poster + Request_EID.get(position) + ".jpg").into(ivImage);
Thank you all for responding.

How to take multiple image paths and convert to a bitmap

My app takes a photo using the camera. It then gets the URI, then the path of that photo and stores the path in a SQLite database. All of that seems to work fine, however when I go to view the images as bitmaps, this code only shows the same image (the last one) for every record (all others informations on each record displays correctly).
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
mPhoto = BitmapFactory.decodeFile(timage.toString(), options);
viewHolder.img_image = (ImageView) convertView.findViewById(R.id.image);
viewHolder.img_image.setImageBitmap(mPhoto);
This is where I get the information for timage, and the rest of the record details :
public ArrayList<ProductModel> _productlist = new ArrayList<ProductModel>();
ArrayList<ProductModel> product_list = db.getProducts();
for (int i = 0; i < product_list.size(); i++) {
String tidno = product_list.get(i).getIdno();
System.out.println("tidno>>>>>" + tidno);
timage = product_list.get(i).getImage();
System.out.println(timage);
String tname = product_list.get(i).getProductname();
String tdesc = product_list.get(i).getproductdesc();
ProductModel _ProductModel = new ProductModel();
_ProductModel.setIdno(tidno);
_ProductModel.setImage(timage);
_ProductModel.setProductname(tname);
_ProductModel.setproductdesc(tdesc);
_productlist.add(_ProductModel);
}
totalrecords.setText("Total Records :-" + _productlist.size());
listview.setAdapter(new ListAdapter(this));
db.close();
The first 3 lines are based on Vino's answer from Suggestions to avoid bitmap Out of Memory error - scaling the images to get rid of the out of memory errors I was receiving otherwise.
mPhoto is simply a Bitmap variable, timage is the images paths (which prints onto the console correctly).
Anyone able to give me a hint in the right direction to get the app showing every image, rather than just the last one taken ?
That variable timage is conserving the value of the last item in the for iteration.
for (int i = 0; i < product_list.size(); i++)
{
//...
timage = product_list.get(i).getImage();
//...
}
So after exiting the loop timage will have the value of the last item. And of course here
mPhoto = BitmapFactory.decodeFile(timage.toString(), options);
it's being used for all your images. Shouldn't you be using _ProductModel.getImage() instead?

Categories

Resources