Getting BLOB from JSON Object in Android - android

I want to read a data from php and I used JSON Object to get the data. And one of the data I want to get from the database is BLOB. I tried by myself with the following code.
products = new JSONArray(getJSONUrl(url));
// looping through product
for (int i = 0; i < products.length(); i++) {
JSONObject jsonObj = products.getJSONObject(i);
try {
placeName = jsonObj.getString(String.valueOf(TAG_PlaceName));
placeDesc = jsonObj.getString(TAG_PlaceDesc);
Blob blob = (Blob) jsonObj.get(TAG_placeIcon);
byte[] byteBlob = blob.getBytes(0, (int) blob.length());
Bitmap bmp = BitmapFactory.decodeByteArray(byteBlob, 0, byteBlob.length);
rowItems.add(new RowItem(placeName, placeDesc, bmp));
} catch (SQLException e) {
e.printStackTrace();
}
}
RowItem is the class that I keep the data.
Can anyone point out what is wrong in my code. I tried to look around for like many hours but I still can't find a solution.
By the way when I tried running the app, It seems that UI doesn't have any problem. Only that the listview that I use to show the data seems to have nothing in it.

use this code
#Override
protected Bitmap doInBackground(String... params) {
String id = params[0];
String add = "http://user localhost/ImageUpload/getImage.php?id="+id;
URL url = null;
Bitmap image = null;
try {
url = new URL(add);
image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return image;
}

Related

why can't I parsing value 'fields' in my code?

When I run my app, In logcat, "Problem parsing the earthquake Json results
org.json.JSONException: No value for fields"
Could you check my JSON code..? I'm beginner of JSON Parsing, So I searched a lot inf But I'm not sure about my code.
public class Utils {
private static List<News> extractFromJson(String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
// Create a JSONObject from the JSON response string
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject response = baseJsonResponse.getJSONObject("response");
JSONArray jsonArray = response.getJSONArray("results");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject currentNews = jsonArray.getJSONObject(i);
JSONObject fields = currentNews.getJSONObject("fields");
Drawable thumbnail = LoadImageFromUrl (fields.getString("thumbnail"));
String section = currentNews.getString("sectionName");
String title = currentNews.getString("webTitle");
String url = currentNews.getString("webUrl");
String date = currentNews.getString("webPublicationDate");
news.add(new News( section, title, url, date,thumbnail));
}
return news;
} catch (JSONException e) {
Log.e("Utils", "Problem parsing the news Json results", e);
}
return null;
}
private static Drawable LoadImageFromUrl(String imageurl) {
Drawable drawable = null;
InputStream inputStream = null;
try {
inputStream = new URL(imageurl).openStream();
drawable = Drawable.createFromStream(inputStream, null);
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
return drawable;
}
}
Try this to validate
Problem occur may be you dont have a field jsonobject in your json list. It may be not present in the some of other jsonobjects. So check if jsonobject has actual field jsonobject before parsing.
Use this condition whenever your json value might give null sometimes.
if(currentNews.has("fields"))
{
JSONObject fields = currentNews.getJSONObject("fields");
}
else
{
Log.d("JSON_TAG","NO FIELD JSON OBJECT");
}

Android - getString method error

I've got a slight problem with a getString function in my Android code.
I create a string and I want to use it to retrieve a String which is part of a JSON Array but I get the following error:
The method getString(String) is undefined for the type String
This is the specific code for this section:
private void read_JSON()
{
JSONArray jsa2 = new JSONArray();
for (int i=0; i < jsa2.length(); i++)
{
try
{
JSONObject jso2 = new JSONObject();
jso2 = jsa2.getJSONObject(i);
String one = one.getString("Blur");
//esbrinar com arreglar aixo!!
}catch (JSONException e)
{
e.printStackTrace();
}
}
}
"Blur" is a String which is part of a JSONArray, defined here:
private void create_JSON()
{
JSONObject jso = new JSONObject();
try {
jso.put("Nombre","Miguel");
jso.put("Apellidos", "Garcia");
jso.put("Año_nacimiento", 1990);
JSONArray jsa = new JSONArray();
jsa.put("Blur");
jsa.put("Clur");
jso.put("Nombres_Hijos", jsa);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Could you help me understand what I'm doing wrong?
Thank you very much.
Yours sincerely,
Mauro.
jso2.getString("Blur") might be what you're trying to call. I believe you want to extract a string from the JSONObject you just got from JSONArray. What you actually wrote is to extract string from the string you just defined.

how to maintain array list for new added element?

Hello every one i am working on app which is similar to the facebook.In that currently i am stuck in one point like we have posts in facebook which shows on our wall in that all the post is shows in bulk like 20 20 fashion that same thing i want to apply in my app. For that thing i use listview which get value form server and create view according to that i also get all value but the problem is that when i add 1st 20 value then it work fine but when i add another 20 value it will delete the previous data in listview.
any idea how i can do this thing in my app and thanks in advance....
my function get value from the server
private void getPostnew(String start) {
String URL = start;
System.out.println("start value new :" + start);
final String usernamefor = "";
aq = new AQuery(getParent());
listitem = new ArrayList<BeanTop>();
aq.ajax(URL, JSONObject.class, 10 * 1000,
new AjaxCallback<JSONObject>() {
#Override
public void callback(String url, JSONObject json1,
AjaxStatus status) {
System.out.println("json " + json1);
if (json1 == null) {
} else {
try {
JSONArray jarray = json1
.getJSONArray("subject");
for (int j = 0; j < jarray.length(); j++) {
try {
JSONObject j1 = jarray.getJSONObject(j);
try {
listcount = j1
.getString("likecount");
} catch (Exception e) {
listcount = "0";
}
AddObject(j1.getString("text"),
j1.getString("leftpic"),
j1.getString("rightpic"),
j1.getString("rightvotecount"),
j1.getString("leftvotecount"),
j1.getString("textleft"),
j1.getString("textright"),
j1.getString("date_created"),
j1.getString("voteid"),
j1.getString("user"),
j1.getString("dom"),
j1.getString("Isvoted"),
j1.getString("Islike"),
j1.getString("profilepic"),
listcount,
j1.getString("commentcount"));
} catch (Exception e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
FriendlistAdapter ad = new FriendlistAdapter(Top.this,
listitem);
subjectlist.setAdapter(ad);
ad.notifyDataSetChanged();
}
});
}
method for save the data in bean class
private void AddObject(String string1, String string2, String string3,
String string5, String string6, String string7, String string8,
String string9, String string10, String string11,
String usernamefor, String isvoted, String isliked,
String profilepic, String likecount, String commentcount) {
BeanTop ib = new BeanTop();
Date date = null;
try {
System.out.println("date " + string9);
date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(string9);
} catch (Exception e) {
e.printStackTrace();
}
ib.setText(string1);
ib.setLeftpic(string2);
ib.setRightpic(string3);
ib.setRightVote(string5);
ib.setLeftVote(string6);
ib.setLefttext(string7);
ib.setRighttext(string8);
ib.setDate(string9);
ib.setDate1(date);
ib.setVoteid(string10);
ib.setUsername(string11);
ib.setDom(usernamefor);
ib.setIsvoted(isvoted);
ib.setIsliked(isliked);
ib.setProfilepic(profilepic);
ib.setLikecount(likecount);
ib.setCommentcount(commentcount);
List<BeanTop> bookingList = new ArrayList<BeanTop>();
bookingList.addAll(listitem);
Collections.sort(bookingList, new Comparator<BeanTop>() {
public int compare(BeanTop m1, BeanTop m2) {
return m1.getDate().compareTo(m2.getDate());
}
});
Collections.reverse(bookingList);
try {
listitem.clear();
} catch (Exception e) {
e.printStackTrace();
}
listitem.addAll(bookingList);
try {
bookingList.clear();
} catch (Exception e) {
e.printStackTrace();
}
listitem.add(ib);
}
Cant say without seeing your code, but I can show you general way of doing this...
First you should maintain a list, say at class level like...
List<MyPost> posts = ArrayList<MyPost>();
Then you can create you adapter by passing 'posts' list in it.
And just call '.addAll(xxx)' to you 'posts' list everytime you get items from server like,
posts.addAll(newItems);
and right after that, call yourAdapter.notifyDatasetChanged(); so that list can redraw/update its views...
And in you code...use,
if (listitem == null) {
listitem = new ArrayList<BeanTop>();
}
in you getPostnew() instead of only listitem = new ArrayList<BeanTop>();.
Hope this helps...
You are re-initializing listitem = new ArrayList<BeanTop>(); eveytime the getPostnew methood is called. This is why your old posts are lost. Try change that line to:
if (listitem == null) {
listitem = new ArrayList<BeanTop>();
}
you should use a global variable to store the data which you get from server ,in your method
getPostnew(String start) every time you execute it ,the listitem will be recreated;so the last data will be lost.

Android displaying images dynamically

I've been having lots of troubles using adapter to display my images properly into my imageView. So basically I have a JSON string and I am parsing through it to get the url of each image. Then I want to display the each image with its title in a list view fashion.
I found this code online where it works perfectly when only one image needs to be displayed, but it doesn't work when I have to do this dynamically. Anyone has some good suggestions on how to get it to work? I attached parts of my codes for references.
Thank you!!!
//results => JSON string
ArrayList<HashMap<String, Object>> resultList = new ArrayList<HashMap<String, Object>>();
for(int i = 0; i < results.length(); i++){
JSONObject c = results.getJSONObject(i);
// Storing each json item in variable
cover = c.getString(TAG_COVER);
String title = c.getString(TAG_TITLE);
try {
URL urlS = new URL(cover);
new MyDownloadTask().execute(urlS);
}catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// creating new HashMap
HashMap<String, Object> map = new HashMap<String, Object>();
// adding each child node to HashMap key => value
map.put(TAG_COVER, cover);
map.put(TAG_TITLE, title);
// adding HashList to ArrayList
resultList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, resultList,
R.layout.list_item,
new String[] {TAG_TITLE}, new int[] {
R.id.title});
setListAdapter(adapter);
And here is the image downloaded codes I found :
private class MyDownloadTask extends AsyncTask<URL, Integer, Bitmap> {
#Override
protected Bitmap doInBackground(URL... params) {
URL url = params[0];
Bitmap bitmap = null;
try {
URLConnection connection = url.openConnection();
connection.connect();
InputStream is = connection.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
bitmap = BitmapFactory.decodeStream(bis);
bis.close();
//is.close(); THIS IS THE BROKEN LINE
} catch (Exception e) {
e.printStackTrace();
return null;
}
return bitmap;
}
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
ImageView myImage = (ImageView) findViewById(R.id.list_image);
myImage.setImageBitmap(bitmap);
} else {
Toast.makeText(getApplicationContext(), "Failed to Download Image", Toast.LENGTH_LONG).show();
}
}
}
There is pretty good library calling AQuery. YOu can use it and simple get all this stuff by writting only 2 line of code, plus it will cache all images for you and it's very good especcially if you are using them in ListView
AQuery aq = new AQuery(activity);
aq.id(R.id.image).image(url, false, true);
Also i think it will be better to use CustomAdapter. I'm not sure it's possible to handle this situation using SimpleAdapter.
Hope this will help you.

nested AsyncTask and onPostExecute

I am using a AsyncTask (1) in another AsyncTask (2).
AsyncTask 1 fetches online user data, counts the number of entries in the response and for each entry, in onPostExecute displays a username and runs a new AsyncTask (2) to fetch a image from a server and load it into a ImageView. This all happens in onPostExecute.
This is working flawlessly, the user data is fetched and shown, and the images are shown one by one for each entry.
However, the itteration through the array and the updating of the TextView in AsyncTask 1's onPostExecute happens so fast, it basically only shows the last user name in the array, the other ones are loaded, but impossible to detect with the human eye :)
Meanwhile, AsyncTask 2 is still fetching images from online, and showing profile images for the wrong users.
The problem I have here obviously, is these 2 need to be in sync.
So I thought I just wait for the output in AsyncTask 2 with the get() method, but now nothing is updated at all anymore, no TextView...this is unexpected behaviour for me.
So, the question is how to sync the 2 AsyncTasks?
bit of code to clarify, if it's still needed
//instantiate first AsyncTask
new AsyncRequest().execute(bundle);
private class AsyncRequest extends AsyncTask<Bundle, Void, String> {
protected String doInBackground(Bundle... bundle) {
String data = null;
try {
data = request(null, bundle[0]); //request the data
return data;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}// end method
protected void onPostExecute(String response) {
JSONArray data = null;
try {
JSONObject response2 = Util.parseJson(response);
data = response2.optJSONArray("data");
int amount = data.length();
TextView s1 = (TextView) findViewById(R.id.some_id);
s1.setText("" + amount); //displays number of items
//display the data
for(int i=0; i<amount; i++){
String email = "";
String id = "";
JSONObject json_obj = data.getJSONObject(i);
Log.d("JSONObject ", ""+json_obj);
String name = json_obj.getString("name");
if (json_obj.has("email")){
email = json_obj.getString("email");
}
if (json_obj.has("id")){
id = json_obj.getString("id");
}
String picture = "http://www.domain.com/"+id+"/picture";
TextView s2 = (TextView) findViewById(R.id.name_placeholder);
s2.setText(name);
//here we do a new AsynTask for each entry and wait until the data is fetched
new DownloadProfileImageTask().execute(picture, name).get();
}
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}// end method
It is not quite clear why you are calling setText of the single TextView with the name of multiple names. As you have mentioned, although you had setText of all the names, you only see a single name. May be you need to use a ListView or something like that.
Now regarding your question: probably you don't need two AsyncTasks. You can do everything in a single AsyncTask. The code will be something like below:
//Create a Holder class as a data holder.
//For simplicity, public attributes are used
class Holder{
public String name;
public String email;
public String id;
public BitmapDrawable imageDrawable;
}
//instantiate the AsyncTask
new AsyncRequest().execute(bundle);
private class AsyncRequest extends AsyncTask<Bundle, Holder, Integer> {
protected Integer doInBackground(Bundle... bundle) {
int amount = 0;
try {
data = request(null, bundle[0]); //request the data
JSONArray data = null;
JSONObject response2 = Util.parseJson(response);
data = response2.optJSONArray("data");
amount = data.length();
//display the data
for(int i=0; i<amount; i++){
Holder holder = new Holder();
holder.email = "";
holder.id = "";
JSONObject json_obj = data.getJSONObject(i);
Log.d("JSONObject ", ""+json_obj);
holder.name = json_obj.getString("name");
if (json_obj.has("email")){
holder.email = json_obj.getString("email");
}
if (json_obj.has("id")){
holder.id = json_obj.getString("id");
}
String picture = "http://www.domain.com/"+id+"/picture";
//Fetch the image and create a Drawable from it - Synchronously
holder.imageDrawable = getImageDrawable(picture, name);
publishProgress(holder);
}
} catch (Exception e) {
e.printStackTrace();
}
return amount;
}// end method
protected void onProgressUpdate(Holder... holder) {
//Update the user name and image
TextView s2 = (TextView) findViewById(R.id.name_placeholder);
s2.setText(holder[0].name);
ImageView imgView = (ImageView) findViewById(R.id.imageViewId);
imgView.setImageDrawable(holder[0].imageDrawable);
}
protected void onPostExecute(Integer amount) {
TextView s1 = (TextView) findViewById(R.id.some_id);
s1.setText(amount.toString()); //displays number of items
}// end method

Categories

Resources