Decoding a jpeg in Android - android

I have JSON data that I am viewing from a URL. There are many JSON objects in the JSON array, one of which is a jpeg image.
I would like to send that image to a listview in an Android app.
Right now I have the image JSON object linked to a private static final String TAG in my Java file. However, I realize that I must decode the image or I will receive an error of: Unable to decode stream: java.io.FileNotFoundException and resolveUri failed on bad bitmap uri.
I am in a long and ongoing search to understand how to decode the JSON jpeg image, much of such research taken place by viewing posts on this website so please do not mark as a duplicate question.
public class JSONBuilderActivity extends ListActivity {
private ProgressDialog pDialog;
//URL to get JSON
private static String url = "";
//JSON Node names
private static final String TAG_CARS = "cars"; //root
private static final String TAG_CARID = "CarID";
private static final String TAG_CARVIN = "CarVIN";
private static final String TAG_IMG= "CarMainImage";
JSONArray carid = null; //Initializes JSON array
static String response = null;
//Hashmap for ListView
ArrayList<HashMap<String, Object>>caridList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ListView lv = getListView();
//Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Gets values from selected ListItem
String cars = ((TextView) view.findViewById(R.id.cars)).getText().toString();
String car_id = ((TextView) view.findViewById(R.id.car_id)).getText().toString();
String car_vin = ((TextView) view.findViewById(R.id.car_vin)).getText().toString();
String model_img = ((ImageView) view.findViewById(R.id.model_img)).getTag().toString();
Intent in = new Intent(JSONBuilderActivity.this, MainActivity.class);
//Sends data to MainActivity
in.putExtra("TAG_CARS", cars);
in.putExtra("TAG_CARID", car_id);
in.putExtra("TAG_CarVin", car_vin);
in.putExtra("TAG_IMG", model_img);
startActivity(in);
}
});
//Calls async task to get json
new GetCars().execute();
}
public class ServiceHandler {
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Makes service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Makes service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,ArrayList<NameValuePair> params) {
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
//Checks http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
//Adds post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
//Appends params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
/*
* Async task class to get json by making HTTP call
*/
private class GetCars extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caridList = new ArrayList<HashMap<String, Object>>();
//Shows progress dialog
pDialog = new ProgressDialog(JSONBuilderActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
//Creates service handler class instance
ServiceHandler sh = new ServiceHandler();
//Makes a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
//Prints the json response in the log
Log.d("GetCars response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
String car_vin = c.getString(TAG_CARVIN);
Log.d("car_vin", car_vin);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), R.id.model_img, options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
String imageType = options.outMimeType;
// byte[] byteArray = Base64.decode(jsonObj.getString(TAG_IMG), Base64.DEFAULT) ;
//Bitmap bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
//String model_img = c.getString(TAG_IMG);
//Log.d("model_img", model_img);
//Hashmap for single match
HashMap<String, Object> matchGetCars = new HashMap<String, Object>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
matchGetCars.put(TAG_CARVIN, car_vin);
matchGetCars.put(TAG_IMG, ); //idk
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Dismisses the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updates parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item,
new String[]{TAG_CARID, TAG_CARVIN, TAG_IMG}, new int[]{R.id.car_id, R.id.car_vin, R.id.model_img});
setListAdapter(adapter);
Log.v("List parsed", caridList.toString());
}
}
So any suggestions of how to decode a JSON jpeg image would be greatly appreciated. Thank you.
}
Update:
public Uri getImageUri(Context inContext, Bitmap inImage){
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(), inImage, "CarMainImage", null);
return Uri.parse(path);
}
public void saveBmpToFile(File filename, Bitmap bmp){
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//------------------------
public boolean renameFileExtension(String source, String newExtension)
{
String target;
String currentExtension = getFileExtension(source);
if (currentExtension.equals(""))
{
target = source + "." + newExtension;
}
else
{
target = source.replaceFirst(Pattern.quote("." +
currentExtension) + "$", Matcher.quoteReplacement("." + newExtension));
}
return new File(source).renameTo(new File(target));
}
//---------------------------------------------------
public String getFileExtension(String f)
{
String ext = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() - 1)
{
ext = f.substring(i + 1);
}
return ext;
}
/*
* Async task class to get json by making HTTP call
*/
private class GetCars extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
caridList = new ArrayList<HashMap<String, Object>>();
//Shows progress dialog
pDialog = new ProgressDialog(JSONBuilderActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
//Creates service handler class instance
ServiceHandler sh = new ServiceHandler();
//Makes a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
//Prints the json response in the log
Log.d("GetCars response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(jsonStr);
Log.d("jsonObject", "new json Object");
//Gets JSON Array node
carid = jsonObj.getJSONArray(TAG_CARS);
Log.d("json array", "user point array");
int len = carid.length();
Log.d("len", "get array length");
for (int i = 0; i < carid.length(); i++) {
JSONObject c = carid.getJSONObject(i);
String car_id = c.getString(TAG_CARID);
Log.d("car_id", car_id);
String car_vin = c.getString(TAG_CARVIN);
Log.d("car_vin", car_vin);
String model_img=c.getString(TAG_IMG);
// byte[] byteArray = Base64.decode(jsonObj.getString(TAG_IMG), Base64.DEFAULT) ;
//Bitmap bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
// String model_img = c.getString(TAG_IMG);
//Log.d("model_img", model_img);
//Hashmap for single match
HashMap<String, Object> matchGetCars = new HashMap<String, Object>();
//Adds each child node to HashMap key => value
matchGetCars.put(TAG_CARID, car_id);
matchGetCars.put(TAG_CARVIN, car_vin);
matchGetCars.put(TAG_IMG, model_img);
caridList.add(matchGetCars);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//Dismisses the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updates parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(JSONBuilderActivity.this, caridList, R.layout.list_item,
new String[]{TAG_CARID, TAG_CARVIN, TAG_IMG}, new int[]{R.id.car_id, R.id.car_vin, R.id.model_img});
setListAdapter(adapter);
Log.v("List parsed", caridList.toString());
}
}
Logcat:
V/List parsedīš• [{CarMainImage=/images/image.php?w=200&i
Unable to decode stream: java.io.FileNotFoundException: /images/image.php?w=200....
unable to resolveUri failed on bad bitmap uri: /images/image.php?w=200....
I do not understand why the parsed list is correctly logged and then those to error pop up. However, the JSON jpeg in the URL is not fully formatted like the jpeg in the log cat because the jpeg in JSON looks like: /images/image.php?w=200... and the jpeg in logcat looks like: /images/image.php?200.. So the difference is the ..can anyone elaborate if that could why the error messages are shown and/or offer suggestions to fix the errors?
I am very willing to research and go back and forth to understand anything that you suggest. Thanks.

without thinking I will post you some conversion code:
**this is a place holder.**
required understanding:
Bitmap
Uri Provides an object representation of a "uniform resource identifier"
URL (Universal resourse loacator) reference (an address) to a resource on the Internet.
file extensions. *.png *.jpg
this will be up-dated when my brain is not without sleep ;O)
more to come as I think , my brain hurts:
//------------------------
public Uri getImageUri(Context inContext, Bitmap inImage)
{
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
public void saveBmpToFile(File filename, Bitmap bmp)
{
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
//------------------------
public static boolean renameFileExtension(String source, String newExtension)
{
String target;
String currentExtension = getFileExtension(source);
if (currentExtension.equals(""))
{
target = source + "." + newExtension;
}
else
{
target = source.replaceFirst(Pattern.quote("." +
currentExtension) + "$", Matcher.quoteReplacement("." + newExtension));
}
return new File(source).renameTo(new File(target));
}
//---------------------------------------------------
public static String getFileExtension(String f)
{
String ext = "";
int i = f.lastIndexOf('.');
if (i > 0 && i < f.length() - 1)
{
ext = f.substring(i + 1);
}
return ext;
}
//-----------------------

Any of the BitmapFactory methods suit you? There's a couple that can take a byte array and give you a Bitmap. Then you can put your Bitmap into an ImageView fairly easily.

I would suggest to use Picasso
As you just need to provide your image url and your imageView inside getView() function of your adapter. All work starting from download image from url to bitmap conversion and set to image view will be handle by Picasso.
For example : Picasso.with(context).load(url).into(view/*Your image view*/);

Related

Get URL image from MySQL and display on android listView (setImageURI)

I'm new to Android and PHP. I've successfully uploaded the image URI from Android to MySQL and now getting trouble to get the image URI back and display on the listView Activity A. Any help would be greatly appreciated. Thanks a lot.
MySQL
Sending to MySQL:
I'm sending the image uri to server, and store the image path to MySQL, images are saved in PhotoUpload folder.
#Override
protected String doInBackground(String... params) {
for (int index = 0; index < jsonArray.length(); index++) {
try {
JSONObject jsonObject = jsonArray.getJSONObject(index);
String strUri = jsonObject.getString("image");
HashMap<String, String> data = new HashMap<String, String>();
data.put(Configs.KEY_IMAGE, getStringImage(Uri.parse(strUri)));
RequestHandler rh = new RequestHandler();
String result = rh.sendPostRequest(Configs.SEND, data);
return result;
} catch (Exception e) {
}
}
return "";
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_LONG).show();
}
public String getStringImage(Uri imgUri) {
try {
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imgUri);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageBytes = baos.toByteArray();
String encodedImage = Base64.encodeToString(imageBytes, Base64.DEFAULT);
return encodedImage;
} catch (Exception e) {
}
return "";
}
And now I'm trying to fetch the url from MySQL and display the image into listView, but the image cannot be retrieved out, only String can be retrieved.
Retrieved from server:
public void BuildEditStaffList(final String id) {
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://192.168.107.115/Android/CRUD/staffRetrieve.php?id=" + id);
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {
}
}
return result;
}
#Override
protected void onPostExecute(String result) {
myJSON = result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void showList() {
try {
JSONObject jsonObj = new JSONObject(myJSON);
details = jsonObj.getJSONArray(Configs.TAG_RESULTS);
for (int i = 0; i < details.length(); i++) {
JSONObject c = details.getJSONObject(i);
String type = c.getString(Configs.TAG_TYPE);
String description = c.getString(Configs.TAG_DESCRIPTION);
String amount = c.getString(Configs.TAG_AMOUNT);
String image = c.getString(Configs.TAG_IMAGE);
int ID = c.getInt(Configs.TAG_ID);
Staff staff = new Staff(ID, type, description, amount, image);
staffs.add(staff);
}
CVAdapter adapter = new CVAdapter(getActivity(), staffs);
listViewEdit.setAdapter(adapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
CVAdapter:
public class CVAdapter extends ArrayAdapter<Staff> {
Activity context;
List<Staff> staffs;
static class ViewHolder {
public ImageView image;
public TextView type;
public TextView amount;
public TextView description;
}
#Override
public int getCount() {
return staffs.size();
}
public CVAdapter(Activity context, List<Staff> staffs) {
super(context, R.layout.retrieve_staff, staffs);
this.context = context;
this.staffs = staffs;
}
#Override
public Staff getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
ViewHolder v = new ViewHolder();
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(R.layout.retrieve_staff, null);
v.image = (ImageView)convertView.findViewById(R.id.image);
v.amount = (TextView)convertView.findViewById(R.id.amount);
v.type = (TextView)convertView.findViewById(R.id.type);
v.description = (TextView)convertView.findViewById(R.id.description);
convertView.setTag(v);
}
holder = (ViewHolder)convertView.getTag();
Log.v("TEST", staffs.get(position).getImage());
holder.image.setImageURI(Uri.parse(staffs.get(position).getImage()));
holder.amount.setText(staffs.get(position).getAmount());
holder.type.setText(staffs.get(position).getType());
holder.description.setText(staffs.get(position).getDescription());
return convertView;
}
}
RetrieveImageAndText.php
<?php
define('HOST','127.0.0.1:3307');
define('USER','root');
define('PASS','');
define('DB','androiddb');
$con = mysqli_connect(HOST,USER,PASS,DB) or die('unable to connect');
$tws = $_GET['id'];
$sql = "select * from staff_benefit WHERE ts_id= '". $tws."' ";
$res = mysqli_query($con,$sql);
$result=array();
while($row=mysqli_fetch_array($res)){
array_push($result,array('id'=>$row[0],'type'=>$row[1],'amount'=>$row[2],'description'=>$row[3],'image'=>$row[4],
'ts_id'=>$row[5]));
}
echo (json_encode(array("result"=>$result)));
mysqli_close($con);
?>
Output
Use a networking library like Volley, Picasso, etc to GET the image over a network call as a Bitmap response and then you can set it to the ImageView via:
holder.image.setImageBitmap(bitmapResponse)
Here is tutorial for using Volley for image requests:
Image Requests with Volley
So I solved it by using Picasso
Just change holder.image.setImageURI(Uri.parse(staffs.get(position).getImage())); to Picasso.with(getContext()).load(staffs.get(position).getImage()).into(holder.image);
Use just a simple codes to get your image
String imageUrl="http://newhabari.000webhostapp.com/db_name/table_name/your_image";
Example
imageUrl="http://newhabari.000webhostapp.com/home_db/nhldb/boeing_787_2.png
Context context=image.getContext();
Picasso.with(context)
.load(imageUrl)
.placeholder(R.drawable.gazetter2)
.error(R.drawable.hands)
.into(image);
return view;
This will give you an image from your db

JSON from php file to java array

I know that there are a few question about this subject, but I read them and I tried the soluttion but it didn't work :(
the PHP script give this json array result: data[x] =
["alon","62","1.82","22","0","70","0","1"]
(this is the data[x] variable)
I have to convert this result to Java variabls like name,weight,height etc.. but I don't know how..
please help me
my function:
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Error = null;
protected void onPreExecute() {
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
data[x] = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error2" , Toast.LENGTH_LONG).show();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error34" , Toast.LENGTH_LONG).show();
cancel(true);
}
return null;
}
public void onPostExecute(Void unused) {
String name = null,weight = null;
if (Error != null) {
} else {
// here I have to do something with the arrays...
Toast.makeText(getApplicationContext(),"d:" + data[x] + "o:" + name + " : " + weight, Toast.LENGTH_LONG).show();
}
x++;
}
}
Create a Modal Class for that.
class myModal {
private String name, weight, height, ...;
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
//and more getters and setters
}
JSONObject json = new JSONObject(data[x]); // in your sample its a JSONArray but its wrong formatted. make sure you encode it properply with php json_encode(array("data", yourdata))...);
myModal modal = new myModal();
modal.setName(json.getString("name"));
php should be something like
<?php
$data = array("name" => "myname", "weight" => 20);
print json_encode( $data );
?>
while the json can be parsed in this case with
JSONArray json = new JSONArray(data);
for (int i = 0; i <= json.length();i++){
JSONObject jsonObj = json.getJsonObject(i);
myModal modal = new myModal();
modal.setString(jsonObj.getString("name"));
//and so on
}
make sure to read the basics for understanding

Show data from world weather online api

I am developing weather application by using world weather online API
for android.How i show data in application? data is showing in logcat.Following is my code.
MainActivity.java
public class MainActivity extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static String url = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
// JSON Node names
private static final String TAG_DATA = "data";
private static final String TAG_NAME = "name";
// contacts JSONArray
JSONArray data = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> dataList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
data = jsonObj.getJSONArray(TAG_DATA);
// looping through All Contacts
for (int i = 0; i < data.length(); i++) {
JSONObject c = data.getJSONObject(i);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
// adding contact to contact list
dataList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(MainActivity.this,
dataList, R.layout.list_item, new String[] { TAG_NAME }, new int[] {
R.id.name });
setListAdapter(adapter);
}
}
}
ServiceHandler.java
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/**
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
* */
public String makeServiceCall(String url, int method,
List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils
.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
First of all, this format will refer to the V1 free version. World Weather Online has released v2, which is superior. I was in the process of updating and saw this question sitting out there so I'll answer based off of what I had that did work.
You are on the right track to use the AsyncTask, here is my call to AsyncTask. You should know I use my "DataPoint" class to simply contain the data from WWO that I need to use. Based on your question, you can show the data that I will put in the DataPoint object in anyway you see fit on the screen, since at the end of the queryWeatherService(), you will end up with a parsed set of data.
//Some call to query the weather, which executes the AsyncTask
private DataPoint queryWeatherService()
{
// This method will retrieve the data from the weather service
DataPoint newDataPoint = new DataPoint();
if (!waiting)
{
try{
newDataPoint = new WeatherServiceClass().execute(
String.valueOf(getlatitude()), //Not shown here: pass in some String of a float value of of your lat coordinate.
String.valueOf(getlongitude())) //Not shown here: pass in some String of a float value of of your long coordinate.
.get();
} catch (InterruptedException | ExecutionException e)
{
e.printStackTrace();
}
}
return newDataPoint;
// Documentation:
// https://developer.worldweatheronline.com/page/documentation
}
The WeatherServiceClass that extends the AsyncTask
public class WeatherServiceClass extends AsyncTask<String, String, DataPoint> {
private String latitude;
private String longitude;
public WeatherServiceClass() {
}
#Override
protected DataPoint doInBackground(String... params) {
DataPoint dp = new DataPoint();
JSONWeatherParser jparser = new JSONWeatherParser();
latitude = params[0];
longitude = params[1];
String data = ((new WeatherHttpClient().getWeatherData(latitude, longitude)));
try {
dp = jparser.getWeather(data);
} catch (JSONException e) {
e.printStackTrace();
}
return dp;
//Reference:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
}
}
Here is the WeatherHttpClient class:
public class WeatherHttpClient {
private static String BASE_URL = "http://api.worldweatheronline.com/free/v1/weather.ashx?q=";
private static String BASE_URL_PT2 = "&format=json&num_of_days=5&date=today&key=[ENTER YOUR KEY HERE, I'M NOT GIVING YOU MINE]";
public String getWeatherData(String latitude, String longitude){
HttpURLConnection con = null;
InputStream is=null;
try{
con = (HttpURLConnection)(new URL(BASE_URL + latitude+","+longitude+BASE_URL_PT2)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
//Reading the response
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while ((line=br.readLine()) != null)
buffer.append(line + "\r\n");
is.close();
con.disconnect();
return buffer.toString();
}
catch(Throwable t) {
t.printStackTrace();
}
finally {
try { is.close();} catch(Throwable t){}
try { con.disconnect();} catch(Throwable t){}
}
return null;
}
Finally, here is my JSONWeatherParser:
public class JSONWeatherParser {
public JSONWeatherParser() {
}
public DataPoint getWeather(String data) throws JSONException {
DataPoint dp = new DataPoint();
Weather weather = new Weather(); //This is just a class that has a bunch of strings in it for the weather info.
JSONObject jObj = new JSONObject(data);
//Parsing JSON data
JSONObject dObj = jObj.getJSONObject("data");
JSONArray cArr = dObj.getJSONArray("current_condition");
JSONObject JSONCurrent = cArr.getJSONObject(0);
weather.setCurrent_temp(getString("temp_F",JSONCurrent));
weather.setHour(getString("observation_time",JSONCurrent));
JSONArray jArr = dObj.getJSONArray("weather");
JSONObject JSONWeather = jArr.getJSONObject(0);
JSONArray jArrIcon = JSONWeather.getJSONArray("weatherIconUrl");
JSONObject JSONIcon = jArrIcon.getJSONObject(0);
weather.setDate(getString("date",JSONWeather));
weather.setPrecipmm(getString("precipMM",JSONWeather));
weather.setTempMaxc(getString("tempMaxC",JSONWeather));
weather.setTempMaxf(getString("tempMaxF",JSONWeather));
weather.setTempMinf(getString("tempMinF",JSONWeather));
weather.setTempMinc(getString("tempMinC",JSONWeather));
weather.setWeatherCode(getString("weatherCode",JSONWeather));
weather.setWeatherIconURL(getString("value",JSONIcon));
weather.setWinddir16point(getString("winddir16Point",JSONWeather));
weather.setWinddirDegree(getString("winddirDegree",JSONWeather));
weather.setWindspeedKmph(getString("windspeedKmph",JSONWeather));
weather.setWindspeedMiles(getString("windspeedMiles",JSONWeather));
dp.setWeather(weather); //assigns and converts the relevant weather strings to DataPoint
// For details of these operations and how each works go here:
// http://www.javacodegeeks.com/2013/06/android-build-real-weather-app-json-http-and-openweathermap.html
return dp;
}
private static String getString(String tagName, JSONObject jObj)
throws JSONException {
return jObj.getString(tagName);
}
}

JSON POST request for download image from server in android

I need to download image and set it in to imageview . for parsing i use JSON POST request and for this i use base64 . I got base64 type data for the image tag in to log but the problem is that how t separate the value of that image and convert it in to string and then display it in to list view ??is there any alternative way without using base64 to display image then please suggest us.
For parsing of data i use JSON parser with HttpPost .
Now how to get the value of image from response JSON format that i display above that the confusion ??
Thanks in advance ..
You can do like this.
Create folder in server. put images in that folder. get the URL of the image and insert in to db.
then get the JSON value of that url
add this method and pass that url to this method.
Bitmap bitmap;
void loadImage(String image_location) {
URL imageURL = null;
try {
imageURL = new URL(image_location);
}
catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection connection = (HttpURLConnection) imageURL
.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
bitmap = BitmapFactory.decodeStream(inputStream);// Convert to
// bitmap
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
Try below code:
JSONObject res = jsonObj.getJSONObject("root");
JSONObject data = jsonObj.getJSONObject("data");
JSONArray imgs= jsonObj.getJSONArray ("images");
for(int i=0;i<imgs.length();i++){
JSONObject Ldetails = Ldtls.getJSONObject(i);
String img= Ldetails.getString("image");
byte[] decodedString = Base64.decode(img,Base64.NO_WRAP);
InputStream inputStream = new ByteArrayInputStream(decodedString);
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
imagevw.setImageBitmap(bitmap);
}
where imagevw is your ImageView.
Use a Gson Parser and then parse the base64 image string to a byte array and apply on the image.
Your model classes will be as follows:
public class JsonWrapper
{
private Root root ;
public Root getroot()
{
return this.root;
}
public void setroot(Root root)
{
this.root = root;
}
}
public class Root
{
private Response response ;
public Response getresponse()
{
return this.response;
}
public void setresponse(Response response)
{
this.response = response;
}
}
public class Response
{
private Message message ;
public Message getmessage()
{
return this.message;
}
public void setmessage(Message message)
{
this.message = message;
}
private Data data ;
public Data getdata()
{
return this.data;
}
public void setdata(Data data)
{
this.data = data;
}
}
public class Message
{
private String type ;
public String gettype()
{
return this.type;
}
public void settype(String type)
{
this.type = type;
}
private String message ;
public String getmessage()
{
return this.message;
}
public void setmessage(String message)
{
this.message = message;
}
}
import java.util.ArrayList;
public class Data
{
private ArrayList<Image> images ;
public ArrayList<Image> getimages()
{
return this.images;
}
public void setimages(ArrayList<Image> images)
{
this.images = images;
}
private String last_synchronized_date ;
public String getlast_synchronized_date()
{
return this.last_synchronized_date;
}
public void setlast_synchronized_date(String last_synchronized_date)
{
this.last_synchronized_date = last_synchronized_date;
}
}
public class Image
{
private String web_id ;
public String getweb_id()
{
return this.web_id;
}
public void setweb_id(String web_id)
{
this.web_id = web_id;
}
private String blob_image ;
public String getblob_image()
{
return this.blob_image;
}
public void setblob_image(String blob_image)
{
this.blob_image = blob_image;
}
}
Once you have the json parse using Gson as follows:
JsonWrapper jsonWrapper = new JsonWrapper();
Gson gsonParser = new Gson();
jsonWrapper = gsonParser.fromJson(data, jsonWrapper.getClass());
Next you can iterate through all the images
ArrayList<Image> images = jsoinWrapper.getRoot().getResponse().getData().getImages();
for(Image image : images)
{
byte[] decodedString = Base64.decode(image.getblob_image(), Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
if (decodedString != null) {
imageViewtype.setImageBitmap(decodedByte);
}
}
public class SingleContactActivity extends Activity implements OnClickListener {
private static final String TAG_ImageList = "CatList";
private static final String TAG_ImageID = "ID";
private static final String TAG_ImageUrl = "Name";
private static String url_MultiImage;
TextView uid, pid;
JSONArray contacts = null;
private ProgressDialog pDialog;
String details;
// String imagepath = "http://test2.sonasys.net/Content/WallPost/b3.jpg";
String imagepath = "";
String imagepath2;
Bitmap bitmap;
ImageView image;
SessionManager session;
TextView myprofileId;
TextView pending;
TextView Categories, visibleTo;
int count = 0;
ImageButton btn;
// -----------------------
ArrayList<HashMap<String, String>> ImageList;
JSONArray JsonArray = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
url_MultiImage = "http://test2.sonasys.net/Android/GetpostImg?UserID=1&PostId=80";
new MultiImagePath().execute();
ImageList = new ArrayList<HashMap<String, String>>();
}
private class MultiImagePath extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url_MultiImage,
ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
JsonArray = jsonObj.getJSONArray(TAG_ImageList);
if (JsonArray.length() != 0) {
for (int i = 0; i < JsonArray.length(); i++) {
JSONObject c = JsonArray.getJSONObject(i);
String Img_ID = c.getString(TAG_ImageID);
String Img_Url = c.getString(TAG_ImageUrl);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ImageID, Img_ID);
contact.put(TAG_ImageUrl, Img_Url);
// adding contact to contact list
ImageList.add(contact);
}
}
Log.e("JsonLength", "length is ZERO");
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
AutoGenImgBtn();
}
}
#SuppressWarnings("deprecation")
public void AutoGenImgBtn() {
int count = ImageList.size();
LinearLayout llimage = (LinearLayout) findViewById(R.id.llimage);
ImageButton[] btn = new ImageButton[count];
for (int i = 0; i < count; i++) {
btn[i] = new ImageButton(this);
btn[i].setId(Integer.parseInt(ImageList.get(i).get(TAG_ImageID)));
btn[i].setOnClickListener(this);
btn[i].setTag("" + ImageList.get(i).get(TAG_ImageUrl));
btn[i].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
btn[i].setImageDrawable(getResources().getDrawable(drawable.di1));
btn[i].setAdjustViewBounds(true);
// btn[i].setTextColor(getResources().getColor(color.white));
llimage.addView(btn[i]);
}
}
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
btn = (ImageButton) v;
String s = btn.getTag().toString();
new ImageDownloader().execute(s);
}
private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
#Override
protected Bitmap doInBackground(String... param) {
// TODO Auto-generated method stub
return downloadBitmap(param[0]);
}
#Override
protected void onPreExecute() {
Log.i("Async-Example", "onPreExecute Called");
pDialog = new ProgressDialog(SingleContactActivity.this);
pDialog.setMessage("Loading...");
pDialog.setCancelable(true);
pDialog.setTitle("In progress...");
// pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setIcon(android.R.drawable.stat_sys_download);
pDialog.setMax(100);
// pDialog.setTitle("Post Details");
pDialog.show();
}
#Override
protected void onPostExecute(Bitmap result) {
Log.i("Async-Example", "onPostExecute Called");
if (bitmap != null) {
btn.setImageBitmap(bitmap);
}
if (pDialog.isShowing())
pDialog.dismiss();
}
private Bitmap downloadBitmap(String url) {
// initilize the default HTTP client object
final DefaultHttpClient client = new DefaultHttpClient();
// forming a HttoGet request
final HttpGet getRequest = new HttpGet(url);
try {
HttpResponse response = client.execute(getRequest);
// check 200 OK for success
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
Log.w("ImageDownloader", "Error " + statusCode
+ " while retrieving bitmap from " + url);
return null;
}
final HttpEntity entity = response.getEntity();
if (entity != null) {
InputStream inputStream = null;
try {
// getting contents from the stream
inputStream = entity.getContent();
// decoding stream data back into image Bitmap that
// android understands
bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
} finally {
if (inputStream != null) {
inputStream.close();
}
entity.consumeContent();
}
}
} catch (Exception e) {
// You Could provide a more explicit error message for
// IOException
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while"
+ " retrieving bitmap from " + url + e.toString());
}
return null;
}
}
# Add Service Handler Class#
public class ServiceHandler {
static String response = null;
public final static int GET = 1;
public final static int POST = 2;
public ServiceHandler() {
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* */
public String makeServiceCall(String url, int method) {
return this.makeServiceCall(url, method, null);
}
/*
* Making service call
* #url - url to make request
* #method - http request method
* #params - http request params
*
* */
public String makeServiceCall(String url, int method,List<NameValuePair> params) {
try {
// http client
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
// Checking http request method type
if (method == POST) {
HttpPost httpPost = new HttpPost(url);
// adding post params
if (params != null) {
httpPost.setEntity(new UrlEncodedFormEntity(params));
}
httpResponse = httpClient.execute(httpPost);
} else if (method == GET) {
// appending params to url
if (params != null) {
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
}
HttpGet httpGet = new HttpGet(url);
httpResponse = httpClient.execute(httpGet);
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}

How to display image in ImageView from Bitmap... ImageView variable returns null

I have a problem with displaying the image from bitmap.
I'm getting the base64 encoded string from JsonObject and decoded to get byte array and bitmap after.
I was unlucky with this so I'm trying now with the same image from drawable.
Now the problem is i'm getting the null pointer exceptions when setting image bitmap in imageView
and have no idea why...
Have read this : ImageView variable returning null even after defined; Android
The code for whole class is: `package com.statsports.subjectiveandroid;
public class PlayersListActivity extends Activity {
// URL to make request
private static String URL = "http://000.000.00.0/index.php";
private static int userID;
ArrayList<HashMap<String, Object>> playersList;
ListView playerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.list_view);
Bundle extras = getIntent().getExtras();
userID = extras.getInt("id");
initLayout();
}
private void initLayout() {
playerView = (ListView) findViewById(R.id.list);
playersList = new ArrayList<HashMap<String, Object>>();
playerView.setAdapter(new SimpleAdapter(PlayersListActivity.this,
playersList, R.layout.activity_players_list, null, null));
//playerView.setDividerHeight(0);
}
#Override
protected void onResume() {
if (!ConnectivityStatus.isNetworkAvailable(getApplicationContext())) {
Toast.makeText(PlayersListActivity.this, R.string.network_failed,
Toast.LENGTH_SHORT).show();
} else {
playerView.setAdapter(null);
new PlayersLoadTask().execute();
}
super.onResume();
}
ProgressDialog pDialog;
class PlayersLoadTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(PlayersListActivity.this);
pDialog.setMessage("Reading data");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
playersList.clear();
}
#Override
protected String doInBackground(String... arg0) {
try {
ArrayList<BasicNameValuePair> parameters = new ArrayList<BasicNameValuePair>();
parameters.add(new BasicNameValuePair("request", "getPlayers"));
parameters.add(new BasicNameValuePair("clubid", Integer
.toString(userID)));
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(PlayersListActivity.URL);
httpPost.setEntity(new UrlEncodedFormEntity(parameters,
("ISO-8859-1")));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// if this is null the web service returned an empty page
if (httpEntity == null) // response is empty so exit out
return null;
String jsonString = EntityUtils.toString(httpEntity);
// again some simple validation around the returned string
if (jsonString != null && jsonString.length() != 0) // checking
// string
// returned
// from
// service
// to grab
// id
{
JSONArray jsonArray = new JSONArray(jsonString);
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, Object> map = new HashMap<String, Object>();
JSONObject jsonObject = (JSONObject) jsonArray.get(i);
int id = jsonObject.getInt("id");
String name = jsonObject.getString("name");
String base64 = jsonObject.getString("image");
map.put("id", id);
map.put("name", name);
if (name == null || name.trim().length() == 0) {
name = "Player unknown";
} else {
map.put("image", (R.drawable.baboon));
}
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.walcott);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Bitmap bmp1 = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
ImageView image = (ImageView) findViewById(R.id.image);
image.setImageBitmap(bmp1);
//ByteArrayOutputStream stream = new ByteArrayOutputStream();
//byte[] decodedString = Base64.decode(
// base64.getBytes("UTF-8"), Base64.NO_PADDING);
/*
* InputStream is = new
* ByteArrayInputStream(decodedString); Bitmap bitmap =
* BitmapFactory.decodeStream(is);
* bitmap.compress(Bitmap.CompressFormat.PNG, 100,
* stream);
*
* if(bitmap != null){ //Drawable drawableImg = new
* BitmapDrawable(getResources(), bitmap); ImageView
* imgView = (ImageView) findViewById(R.id.image);
* imgView.setImageBitmap(bitmap); map.put("image",
* bitmap); }
*/
//String images = new String(decodedString);
//Bitmap decodedByte = BitmapFactory.decodeByteArray(
// decodedString, 0, decodedString.length);
//decodedByte.compress(Bitmap.CompressFormat.PNG, 100,
// stream);
//Log.d("DECODEDBYTE IS: ", decodedByte.toString());
//LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//View view = inflater.inflate(R.layout.activity_players_list, null);
//setContentView(view);
//ImageView imgView = (ImageView) findViewById(R.id.image);
//imgView.setImageBitmap(decodedByte);
playersList.add(map);
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
Log.e("ERROR SOMEWHERE!!!! ", e.toString());
}
return null;
}
protected void onPostExecute(String file_url) {
if (playersList.size() == 0) {
Toast.makeText(PlayersListActivity.this,
"No players in a list", Toast.LENGTH_SHORT).show();
} else {
playerView.setAdapter(new PlayerListAdapter(
PlayersListActivity.this, playersList,
R.layout.activity_players_list, new String[] { "id",
"image", "name" }, new int[] {
R.id.player_list_id, R.id.image, R.id.name, }));
}
pDialog.dismiss();
}
}
}

Categories

Resources