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.
Related
I have a trouble finding a way how to parse JSONArray
This is my JSON:
{
"result": [
[
"id",
"name",
"origin",
"destination"
],
[
1,
"A S Peta",
0,
0
],
[
2,
"Aachara",
0,
0
],
.
.
.
[
2238,
"sydney",
0,
0
]
]
}
I need to access it in Android app. I have tried and I am able to receive values, but they are displaying in a single row, and I am unable to split the fields.
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");
for (int i = 1; i < contacts.length(); i++) {
String name = contacts.getString(i).replaceAll("\\[|\\]", "");
HashMap<String, String> contact = new HashMap<>();
contact.put("name", name);
contactList.add(contact);
}
}
This is my output, I need to get the values separately like:
1
A S Peta
0
0
But not in single row:
Json String ca be parsed in JSONObject like:
try {
List<HashMap<String,String>> cityDetails= new ArrayList<HashMap<String,String>>();
JSONObject jsonObject = new JSONObject("your json string");
JSONArray jsonArray = jsonObject.getJSONArray("result");
JSONArray cityKeyArray =jsonArray.getJSONArray(0);
for(int index=1; index<jsonArray.length();index++){
HashMap<String, String> cityData = new HashMap<String, String>();
for(int dataIndex=0; dataIndex<cityKeyArray.length();dataIndex++) {
cityData.put(cityKeyArray.getString(dataIndex), jsonArray.getJSONArray(index).getString(dataIndex));
}
cityDetails.add(cityData);
}
} catch (Exception e) {
e.printStackTrace();
}
cityDetails can be used in the adapter to show value according to the keys which are in the first array of the JSON String i.e. cityKeyArray.
So, the collections will show the data as user requirements.
Hope this will help to solve your query.
Thanks and Happy coding!!!
update your code with this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");
for (int i = 1; i < contacts.length(); i++) {
JSONArray contactArray = contacts.getJSONArray(i);
int id = contactArray.getInt(0);
String name = contactArray.getString(1);
String origin= contactArray.getString(2);
String destination= contactArray.getString(3);
HashMap<String, String> contact = new HashMap<>();
contact.put("id", id);
contact.put("name", name);
contact.put("origin", origin);
contact.put("destination", destination);
contactList.add(contact);
}
}
String name = contacts.getString(i).replaceAll("\\[|\\]", "");
Do not do this; it seems you do not have strings for your arrays.
You have nested lists, it seems, so you can access those JSON arrays via another getJSONArray(index) method
Or you could fix the source of the JSON (your server?) to return better parsable JSON
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");
for (int i = 1; i < contacts.length(); i++) {
HashMap<String, String> contact = new HashMap<>();
contact.put("name", contacts.getString("name"));
contactList.add(contact);
}
}
Do this
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JSONArray contacts = jsonObj.getJSONArray("result");
for (int i = 1; i < contacts.length(); i++) {
JsonArray array=contacts.get(i);
String name = array.getString("name");
HashMap<String, String> contact = new HashMap<>();
contact.put("name", name);
contactList.add(contact);
}
}
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 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);
I have JSON array like below format
{
"get": [],
"post": {
"_event": "get_buyers_guide_detail",
"_deviceID": "490154203237518",
"type": "cars",
"model_id": "1007"
},
"cars": [
{
"ID": 6119,
"post_title": "COROLLA",
"interior_images": [
"http://.....e8664969d20654bf2a58f1b26de70d2.jpg",
"http://........02/3bdfae250e3ce14514fe8f2f9dc3e58f.jpg",
"http://........1d14a554a2ed78d1659463ec.jpg"
],
}
]
}
I have create JSONArray for this:
JSONArray Array = entries.getJSONArray("cars");
for (int i = 0; i < Array.length(); i++) {
JSONObject detailObject = Array.getJSONObject(i);
String ID = detailObject.getString("ID");
String title = detailObject.getString("post_title");
JSONArray galleryArray = detailObject.getJSONArray("interior_images");
for(int j=0; j<galleryArray.length(); j++){
// What to do here ????
}
}
now i am confused with this format of JSON data. There is no JSONObject to get the values. How to insert these string on Array please help me find out the solution
Try this,
galleryArray.getString(j);
this should get the string at position j.
galleryArray.getString(index);
This function will return String object of corresponding index
try this
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray galleryArray = detailObject.getJSONArray("interior_images");
for(int j=0; j<galleryArray.length(); j++){
try {
JSONObject jsonObject = galleryArray.getJSONObject(j);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
Try this way,hope this will help you to solve your problem.
try{
String jsonRespone="{\"get\":[],\"post\":{\"_event\":\"get_buyers_guide_detail\",\"_deviceID\":\"490154203237518\",\"type\":\"cars\",\"model_id\":\"1007\"},\"cars\":[{\"ID\":6119,\"post_title\":\"COROLLA\",\"interior_images\":[\"http://.....e8664969d20654bf2a58f1b26de70d2.jpg\",\"http://........02/3bdfae250e3ce14514fe8f2f9dc3e58f.jpg\",\"http://........1d14a554a2ed78d1659463ec.jpg\"],}]}";
JSONObject responeJson = new JSONObject(jsonRespone);
ArrayList<HashMap<String,Object>> data = new ArrayList<HashMap<String, Object>>();
JSONArray carsJsonArray = responeJson.getJSONArray("cars");
for (int i=0;i<carsJsonArray.length();i++){
HashMap<String,Object> row = new HashMap<String, Object>();
row.put("ID",carsJsonArray.getJSONObject(i).getString("ID"));
row.put("TITLE",carsJsonArray.getJSONObject(i).getString("post_title"));
JSONArray galleryArray = carsJsonArray.getJSONObject(i).getJSONArray("interior_images");
ArrayList<String> interiorImages = new ArrayList<String>();
for(int j=0; j<galleryArray.length(); j++){
interiorImages.add(galleryArray.getString(j));
}
row.put("INTERIORIMAGES",carsJsonArray.getJSONObject(i).getString("interiorImages"));
data.add(row);
}
for (HashMap<String,Object> row :data){
System.out.print("ID : "+row.get("ID"));
System.out.print("TITLE : "+row.get("TITLE"));
ArrayList<String> interiorImages = (ArrayList<String>) row.get("INTERIORIMAGES");
for (int j=0;j<interiorImages.size();j++){
System.out.print("INTERIORIMAGES +"+j+" : "+interiorImages.get(j));
}
}
}catch (Throwable e){
e.printStackTrace();
}
I think you need to use List of Map
Example:
List<Map> list = new ArrayList<Map>();
Map map = new HashMap();
map.put("userIcon", R.drawable.scott);
map.put("username", "Shen");
map.put("usertext", "This is a simple sample for SimpleAdapter");
list.add(map);
map = new HashMap();
map.put("userIcon", R.drawable.ricardo);
map.put("username", "Ricardo");
map.put("usertext", "This is a simple sample for SimpleAdapter");
list.add(map);
add this in loop
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.