I was trying to put a JSON array of object into a hashmap.The object contains images which is in base64 format.I converted the image to bit map and need to put the image in a List view using a hashmap.But i am getting a null pointer exception
#Main Activity#
protected void onPostExecute(JSONObject json) {
try {
// Getting JSON Array from URL
details = json.getJSONArray(TAG_Root);
for(int i = 0; i < details.length(); i++){
JSONObject c = details.getJSONObject(i);
// Storing JSON item in a Variable
String branch = c.getString(TAG_Branch);
String address = c.getString(TAG_Add);
String uname = c.getString(TAG_User);
String photo = c.getString(TAG_Photo);
//decoding the base64 image to an png format
byte[] imageAsBytes = Base64.decode(photo.getBytes(), Base64.DEFAULT);
ImageView image = (ImageView)findViewById(R.id.imageView1);
image.setImageBitmap(
BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length)
);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_Branch, branch);
map.put(TAG_Add, address);
map.put(TAG_User, uname);
oslist.add(map);
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(TAG_Photo,image);
oslist.add(map);
//String.valueOf(TAG_Photo
//,R.id.imageView1
list=(ListView)findViewById(R.id.listView1);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_activity,
new String[] { TAG_Branch,TAG_Add, TAG_User }, new int[] {
R.id.textView1,R.id.textView2, R.id.textView3});
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
int pos=position;
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+pos).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
You're getting null because of the map
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(TAG_Photo,image);
the adapter won't find the needed tags in it so it will give null exception.
If photo's value is base64 string content, I think you don't need photo.getBytes()
String photo = jsonObject.getString(TAG_Photo);
byte[] bytes = Base64.decode(photo, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
Related
There's someway for me to adapt a encoded string image in a Listview?
I got from my server, in base64 format, a image in a string, and I want to set it in a Listview with some text.
Here is part of my code:
for (int i = 0; i < makers.length(); i++) {
JSONObject c = makers.getJSONObject(i);
// Storing each json item in variable
String name = c.getString(TAG_NAME);
String age = c.getString(TAG_AGE);
String username = c.getString(TAG_USERNAME);
String rating = c.getString(TAG_RATING);
String disc = c.getString(TAG_DISC);
Long date = c.getLong(TAG_DATE);
String num = c.getString(TAG_NUM);
// creating new HashMap
//HashMap<String, String> map = new HashMap<String, String>();
Map map = new HashMap<String, Bitmap>();
String image=c.getString(TAG_IMAGE1);
byte[] decodedString = Base64.decode(image, Base64.DEFAULT);
Bitmap bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
map.put(TAG_NAME, name);
map.put(TAG_USERNAME, username);
map.put(TAG_AGE, age);
map.put(TAG_RATING, rating);
map.put(TAG_DISC, disc);
map.put(TAG_NUM, num);
map.put(TAG_IMAGE1, bitmap);
// map.put(TAG_CIDADE, cidade);
long curdate = System.currentTimeMillis();
long onem = curdate - date;
long intm = 3*30*24*60*60*1000 ;
if(onem >= intm){
} else {
// adding HashList to ArrayList
userdataList.add((HashMap<String, String>) map);
}
}
}
And here is my Adapter:
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting the related idioms
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
ListResult1.this, userdataList,
R.layout.list_view, new String[] { TAG_NAME, TAG_USERNAME, TAG_AGE, TAG_RATING, TAG_DISC, TAG_NUM, TAG_IMAGE1},
new int[] {R.id.name, R.id.username, R.id.age, R.id.rating, R.id.disc, R.id.num, R.id.ivimage1s});
// updating listview
setListAdapter(adapter);
}
});
}
And i want also to transfer that image through a intent, it's possible?
The actual problem is that I can't set a adapter for my image, all the text part work just fine, but the image did not loaded.
Sorry for any English issue, it's not my mother language.
I'm trying to do listview with base64 images.
Listviews data is json-array from server and created to hashmap.
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString("pid");
String createdAt = c.getString("created_at");
String description = c.getString("description");
String image = c.getString("image");
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put("pid", id);
map.put("description", description);
map.put("image", image);
// adding HashList to ArrayList
productsList.add(map);
}
And:
protected void onPostExecute(String file_url) {
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/*Updating parsed JSON data into ListView*/
ListAdapter adapter = new SimpleAdapter(
listActivity.this, productsList,
R.layout.list_item, new String[] { "product_id",
"product_description", "product_image" },
new int[] { R.id.pid, R.id.description, R.id.image });
// updating listview
setListAdapter(adapter);
}
});
}
How can I make that image string converted to imageview?
I'm new with Android Studio, so I don't know if thats smart way to do that..
Above code is from: http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
If that helps.
First what you have to do is to convert base64 to bitmap, and then you can set it on imageView.
How to decode base64 to bitMap:
byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
How to set bitmap to imageView:
ImageView mImg = (ImageView) findViewById(R.id.(your xml img id));
mImg.setImageBitmap(decodedByte );
PHP file
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$row['EventPic'] = base64_encode($row['EventPic']);
$json['event'][]=$row;
}
}
dbDisconnect($conn);
echo json_encode($json);
?>
I followed online solution to base64_encode the blob array
Android side
try{
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("event");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
name = jsonChildNode.optString("TITLE");
number = jsonChildNode.optString("EVENTID");
diploma = jsonChildNode.optString("DIPLOMA");
date = jsonChildNode.optString("DATE").toString();
BlobPicture = jsonChildNode.optString("EventPic");
byte[] decodedString = Base64.decode(BlobPicture, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put(TAG_DATE, diploma);
map.put(TAG_TITLE, name);
map.put(TAG_ID, number);
map.put(TAG_DAY, date);
map.put(TAG_PIC, decodedByte);
// adding HashList to ArrayList
eventsList.add(map);
}
} catch (JSONException e) {
Toast.makeText(getActivity(), "No events on this date" , Toast.LENGTH_SHORT).show();
}
ListAdapter adapter = new SimpleAdapter(
getActivity(), eventsList, R.layout.eventuse, new String[] { TAG_DATE, TAG_TITLE, TAG_ID, TAG_DAY, TAG_PIC},
new int[] { R.id.title1, R.id.date1, R.id.hideeventid, R.id.course1, R.id.imh });
listView.setAdapter(adapter);
I need help to retrieve from the Android side, my method doesn't seems to work as my SimpleAdapter requires R.id.
Any advice or solutions are much appreciated.
I have a little problem with putting an image to a list view using simple adapter. I'm getting the image from my online server(AMAZON). After downloading the image based on the user id, i try to set them in my listview but nothing was display and no error is occured.
Below is my code:
// looping through All applicants
for (int i = 0; i < applicant.length(); i++) {
JSONObject c = applicant.getJSONObject(i);
// Storing each JSON item in variable
String uid = c.getString(TAG_UID);
String name = c.getString(TAG_NAME);
String overall = c.getString(TAG_OVERALL);
String apply_datetime = c.getString(TAG_APPLY_DATETIME);
String photo = c.getString(TAG_PHOTO);
// creating new HashMap
//HashMap<String, String> map = new HashMap<String, String>();
//IMAGE
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key (value)
map.put(TAG_UID, uid);
map.put(TAG_NAME, name);
map.put(TAG_OVERALL, overall);
map.put(TAG_APPLY_DATETIME, apply_datetime);
// adding HashList to ArrayList
// applicantsList.add(map);
// LISTING IMAGE TO LISTVIEW
try {
imageURL = c.getString(TAG_PHOTO);
InputStream is = (InputStream) new URL(
"my url link/images/"
+ imageURL).getContent();
d = Drawable.createFromStream(is, "src name");
} catch (Exception e) {
e.printStackTrace();
}
map.put(TAG_PHOTO, d);
// adding HashList to ArrayList
applicantsList.add(map);
}
As you can see, after i download the image. i set to listview using simpleAdapter below:
SimpleAdapter adapter = new SimpleAdapter(
SignUpApplicantActivity.this, applicantsList,
R.layout.list_applicant, new String[] {
TAG_UID, TAG_NAME, TAG_OVERALL,
TAG_APPLY_DATETIME, TAG_PHOTO }, new int[] {
R.id.applicantUid, R.id.applicantName,
R.id.applicantOverall,
R.id.apply_datetime, R.id.list_image });
// updating listView
setListAdapter(adapter);
Did you called notifyDatasetChange() ? your adapter may not be invalidated if you don't call it.
From the SimpleAdapter documentation the image data is expected to be a resource ID or a string (an image URI) - see setViewImage(ImageView,String)
I see 2 solutions:
Provide a URI in the data map, not a drawable.
Implement your own view binder to bind the drawable to the ImageView:
adapter.setViewBinder(new SimpleAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Object data, String textRepresentation) {
if(view.getId() == R.id.list_image) {
ImageView imageView = (ImageView) view;
Drawable drawable = (Drawable) data;
imageView.setImageDrawable(drawable);
return true;
}
return false;
}
});
Try
try{
for (int i = 0; i < applicant.length(); i++) {
JSONObject c = applicant.getJSONObject(i);
// Storing each JSON item in variable
String uid = c.getString(TAG_UID);
String name = c.getString(TAG_NAME);
String overall = c.getString(TAG_OVERALL);
String apply_datetime = c.getString(TAG_APPLY_DATETIME);
String photo = c.getString(TAG_PHOTO);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key (value)
map.put(TAG_UID, uid);
map.put(TAG_NAME, name);
map.put(TAG_OVERALL, overall);
map.put(TAG_APPLY_DATETIME, apply_datetime);
map.put(TAG_PHOTO, photo);
// adding HashList to ArrayList
applicantsList.add(map);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
SimpleAdapter adapter = new SimpleAdapter(
SignUpApplicantActivity.this, applicantsList,
R.layout.list_applicant, new String[] {
TAG_UID, TAG_NAME, TAG_OVERALL,
TAG_APPLY_DATETIME, TAG_PHOTO }, new int[] {
R.id.applicantUid, R.id.applicantName,
R.id.applicantOverall,
R.id.apply_datetime, R.id.list_image });
// updating listView
setListAdapter(adapter);
Maybe my code can help you!?!
I have made
convertDrawable(int Integer)
and String.valueOf(convertDrawable(iconId))
HashF.put(TAG_ID, String.valueOf(convertDrawable(iconId)));
private void getList(JSONObject json) {
try {
details = json.getJSONArray(TAG_LIST);
for (int i = 0; i < details.length(); i++) {
JSONObject main = details.getJSONObject(i);
Integer date = main.getInt(TAG_DATE);
JSONArray nArray = main.getJSONArray(TAG_NOW);
JSONObject detail = nArray.getJSONObject(0);
Integer iconId = detail.getInt(TAG_ID);
HashMap<String, String> HashF = new HashMap<String, String>();
HashF.put(TAG_DATE, convertDate(date));
HashF.put(TAG_ID, String.valueOf(convertDrawable(iconId)));
fList.add(HashF);
}
} catch (Exception e) {
}
ListAdapter adapter =
new SimpleAdapter(getActivity(),
fList, R.layout.list_item,
new String[]{
TAG_DATE,
TAG_ID
},
new int[]{
R.id.datum,
R.id.icon_fore
});
setListAdapter(adapter);
}
public static String convertDate(Integer Time) {
SimpleDateFormat sdf =
new SimpleDateFormat(
"dd, MMMM", Locale.getDefault());
Calendar kal =
Calendar.getInstance();
kal.setTimeInMillis(Time * 1000L);
sdf.setTimeZone(kal.getTimeZone());
return sdf.format(kal.getTime());
}
public static int convertDrawable(int aId){
int icon = 0;
if(aId == 8300){
icon = R.drawable.draw1;
}
if (aId >= 7010 && actualId < 7919){
icon = R.drawable.draw2;
}
if (aId >= 2010 && actualId <3010) {
icon = R.drawable.draw3;
}
if (aId >= 3010 && actualId < 4010) {
icon = R.drawable.draw4;
}
if (aId >= 6010 && actualId < 7010) {
icon = R.drawable.draw5;
}
if (aId >= 5010 && actualId < 6010) {
icon = R.drawable.draw6;
}
if (aId == 3801){
icon = R.drawable.draw7;
}
if (aId == 8032){
icon = R.drawable.draw8;
}
if (aId == 8083){
icon = R.drawable.draw9;
}
if (aId == 8704) {
icon = R.drawable.draw10;
}
return icon;
}
Anyway make a look at Bitmap is not a Drawable
i need to set a listview with custom text and custom setbackgroundresource when i create the listview
This is my code:
The listView receive the data from URL by JSON encdoe like that:
{"results":[
{"db_id":"6","discount":"active","db_description":"bla bla bla ","db_num":"137","db_num2":"260"},
{"db_id":"14","db_type":"discount","db_description":"blaaaaaaa","db_num":"39","db_num2":"46"},
{"db_id":"18","db_type":"discount","db_description":"blaaaaaaa","db_num":"335","db_num2":"456"},
]}
Adding the data to map
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("type",RESULTS_PARAMS));
JSONObject json = jsonParser.makeHttpRequest(RESULTS_URL, "GET",
params);
Log.d("JSON RESULT: ", json.toString());
try {
queues = json.getJSONArray(TAG_RESULTS);
for (int i = 0; i < queues.length(); i++) {
JSONObject c = queues.getJSONObject(i);
String id = c.getString(TAG_ID);
String type = c.getString(TAG_TYPE);
String description = c.getString(TAG_DESCRIPTION);
String num = c.getString(TAG_NUM);
String num2 = c.getString(TAG_NUM2);
int imageint = getResources().getIdentifier(c.getString(TAG_TYPE) , "drawable", getPackageName());
String image = String.valueOf(imageint);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, id);
map.put(TAG_TYPE, type);
map.put(TAG_DESCRIPTION, description);
map.put(TAG_NUM, num);
map.put(TAG_NUM2, num2);
map.put(TAG_IMAGE, image);
QueueList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
the code the set the DATA into the listview
ListAdapter adapter = new SimpleAdapter(
QueueActivity.this,
QueueList,
R.layout.queue_row,
new String[] { TAG_ID, TAG_DESCRIPTION, TAG_NUM, TAG_NUM2, TAG_IMAGE},
new int[] { R.id.queueid, R.id.description, R.id.num, R.id.num2, R.id.list_image });
setListAdapter(adapter);
now i want to set a setBackgroundResource to R.drawable.customlistviewback
if the db_id (TAG_ID) = int info
For ex, int info = 6;
To do row-level view modifications you will probably need to use a custom Adapter. Typically you override the getView function and make your changes there. See how to customize listview row android for a decent example.