I have been trying many of the codes that have been posted on stackoverflow itself. However, none have worked for me so far. I'm new to android and there's probably something I'm overlooking. Kindly help fix this code -
package com.alphageeks.pespitstop;
import java.io.InputStream;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
public class Vop extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_vop);
Button bnot = (Button) findViewById(R.id.bnot);
Button bcant = (Button) findViewById(R.id.bcant);
Button bcal = (Button) findViewById(R.id.bcal);
final ImageView img = (ImageView) findViewById(R.id.imageView1);
final Toast disp = null;
bnot.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
try {
URL url = new URL("https://drive.google.com/file/d/0B-bEff6i-vWoUHpWS3h1VUR4ZkE/edit?usp=sharing");
//try this url = "http://0.tqn.com/d/webclipart/1/0/5/l/4/floral-icon-5.jpg"
HttpGet httpRequest = null;
httpRequest = new HttpGet(url.toURI());
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity b_entity = new BufferedHttpEntity(entity);
InputStream input = b_entity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(input);
img.setImageBitmap(bitmap);
} catch (Exception ex) {
disp.makeText(Vop.this, "error",Toast.LENGTH_SHORT).show();
}
}
});
}
}
Two things:
1) The URL your want is actually:
https://lh3.googleusercontent.com/pgF2BkPGEdp5KuKD535q0DNL-SkXqiaPGmeQt-F0wA-GZ3GLIu2WaOGI72i0TzlxI-Uub4FoFtY
2) You'll need to download the image in a background Thread, like an AsyncTask, otherwise you'll throw a NetworkOnMainThreadException.
private class ImageWorker extends AsyncTask<String, Void, Bitmap> {
/**
* {#inheritDoc}
*/
#Override
protected Bitmap doInBackground(String... params) {
InputStream input = null;
try {
final URL url = new URL(YOUR_URL);
input = new BufferedInputStream(url.openStream());
return BitmapFactory.decodeStream(input);
} catch (final Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (final IOException ignored) {
// Nothing to do
}
}
}
return null;
}
/**
* {#inheritDoc}
*/
#Override
protected void onPostExecute(Bitmap result) {
if (result != null) {
// Set the image here
}
}
}
try this (this is in case if you don't get any exceptions, otherwise you probably do networking on UI thread and that results in error, then you may ignore my reply):
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
byte[] bytes = out.toByteArray();
Bitmap bmp=BitmapFactory.decodeByteArray(bytes,0,bytes.length);
img.setImageBitmap(bmp);
Maybe you can take a look in this tutorial.
I hope it can solve your problem.
https://sites.google.com/site/androidhowto/diplayinganimage
Or this website that have more detailed tutorial on how to display image from URL.
Don't forget to include permission in the manifest.
http://www.androidhive.info/2012/07/android-loading-image-from-url-http/
use picasso http://square.github.io/picasso/ is easy with less code example Picasso.with(context).load("http://i.imgur.com/DvpvklR.png").into(imageView);
Try this..it may be help you..
URL url = new URL("YourUrl");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);
Try this:
try {
URL url = new URL("https://drive.google.com/file/d/0B-bEff6i-vWoUHpWS3h1VUR4ZkE/edit?usp=sharing");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
Related
Is there an easy way to point the code below to a URL that has JSON data. Before I had the following with my Json file in the Assets folder:
InputStream is = context.getAssets().open("data.json");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
What is in that data.json file is now stored online. If I get the string of that URL as String URL = "http...whatever....data.json" how do I initialize the InputStream in the first line of code?
That code is specific to reading from files. You will need to setup an AsyncTask and pull the data in a background thread.
This page explains the issues and provides good examples.
http://developer.android.com/training/basics/network-ops/connecting.html
Update 1:
Here is code from a project that pulls the data and parses it and populates a java object:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import com.google.gson.Gson;
public class RestServices
{
public static String getServerAddress()
{
return "http://192.168.96.179:8090/";
}
public static String getRestURI()
{
return "api/";
}
public static <T> T getExternalData(Class<T> clazz, String uri) throws IOException
{
String responseString = "";
try
{
HttpClient httpclient = new DefaultHttpClient();
String address = getServerAddress() + getRestURI() + uri;
HttpResponse response = httpclient.execute(new HttpGet(address));
StatusLine statusLine = response.getStatusLine();
if(statusLine.getStatusCode() == HttpStatus.SC_OK){
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else{
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
}
catch (ClientProtocolException e)
{
}
Gson gson = new Gson();
T object = gson.fromJson(responseString, clazz);
return object;
}
}
And how I call it:
class SiteConfigTask extends AsyncTask<Void, SiteConfig, SiteConfig>
{
#Override
protected SiteConfig doInBackground(Void... none)
{
SiteConfig sc = null;
try
{
sc = RestServices.getExternalData(SiteConfig.class, "siteconfig");
} catch (IOException e)
{
Log.e(TAG,"Failed to fetch siteconfig", e);
}
return sc;
}
#Override
protected void onPostExecute(SiteConfig result)
{
super.onPostExecute(result);
if ( result == null )
{
EventBus.getDefault().post(new ConfigurationFetchErrorEvent());
}
else
{
// Adds an additional empty stream if there are
// and odd number of streams, the new stream will be disabled.
if ( result.getStreamList().size() % 2 != 0)
{
Stream s = new Stream();
s.setEnabled(false);
result.getStreamList().add(s);
}
updateSiteConfig(result);
}
}
}
You could request the resource via HttpURLConnection like the code snippet below.
HttpURLConnection connection = null;
InputStream inputStream = null;
try {
URL url = new URL("http://www.example.com/data.json");
connection = (HttpURLConnection) url.openConnection();
inputStream = connection.getInputStream();
int size = inputStream.available();
byte[] buffer = new byte[size];
inputStream.read(buffer);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please have a look at the following code
package com.example.jsontest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
private EditText editText;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.
ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edit_text);
//Call The JSon
try {
JSONObject jObject = new JSONObject(getJson());
int code = jObject.getInt("code");
editText.append("Code: "+code+"\n");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String getJson()
{
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("https://bigml.io/andromeda/source/5277b1bd035d074e940056e0?username=xxx;api_key=xxxxxxxxxxxxxxx");
// 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;
}
}
In here, what I need to do is, print the "entire" result I retrieved. I wish to print the entire thing, I don't need to get separate values. How can I do this? Here is the link to the BigML retrieve documentation.
Just use JSONObject.toString() ?
You should never connect to network on main thread. Best and the most simple option is to use AsyncTask<...>.
something like this:
private class DownloadProductsTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
try {
return new PublicDataDBManager().retriveJsonData(mCode, mUserMail);
} catch (Exception e) {
}
return null;
}
#Override
protected void onPostExecute(String result){
buildData(result);// here you update mathod in your main thread
}
}
Here is simple example: http://androide-examples.blogspot.com/2013/11/android-retrieve-json-data-from-url.html
So I ran your code, and it crashed. I also see that you are bypassing security and doing network operations in onCreate, in the main thread. This isn't a good idea in Android. Network operations should go in a background thread.
I refactored it very quickly to use a thread and it worked. Here is the code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText)findViewById(R.id.edit_text);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
new Thread(new Runnable() {
#Override
public void run() {
JSONObject jObject;
try {
jObject = new JSONObject(getJson());
// I am logging the raw value that was returned here
Log.i("JSON Body", jObject.toString());
int code = jObject.getInt("code");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}).start();
}
If you want to update the main thread (MainActivity) within the thread, create a Handler and pass a reference to that into the thread, and use that for updates.
guys. I have this code:
package com.example.httpprogress;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
public class MyPicGetTask extends AsyncTask<URL , Void, Bitmap>{
InputStream is = null;
BufferedInputStream bis = null;
Bitmap bmp = null;
#Override
protected Bitmap doInBackground(URL... urls) {
// TODO Auto-generated method stub
URL url = urls[0];
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
}
}
return bmp;
}
}
it fails, but if i use AsyncTask and describe this class as inner in my activity - it's ok . I can not say the reason because i can not debug, i can see that debug tab opens when it fails but it is not informative for me. Any ideas? Sorry for my noob question
that's my Activity:
package com.example.httpprogress;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
public class PicActivity extends Activity implements OnClickListener{
InputStream is = null;
BufferedInputStream bis = null;
Bitmap bmp = null;
private URL url;
//"http://192.168.0.30/03.jpg";
/*
private class getPicTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... s) {
// TODO Auto-generated method stub
try {
url = new URL("http://192.168.0.93/image.php");
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (MalformedURLException e) {
} catch (IOException e) {
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
}
}
return null;
}
};
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pic);
final ImageView image = (ImageView) findViewById(R.id.imageView1);
image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
///////////
try {
url = new URL("http://192.168.0.30/03.jpg");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
new MyPicGetTask().execute(url);
image.setImageBitmap(bmp);
}
});
////////////////
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.pic, menu);
////////////////
return true;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.d("httpProgress", "Onclick()");
}
}
Add Log.d() code to doInBackground(...) to print out all exceptions that occur. That should tell you what's going wrong, e.g.
try {
URLConnection conn = url .openConnection();
conn.connect();
is = conn.getInputStream();
bis = new BufferedInputStream( is );
bmp = BitmapFactory.decodeStream( bis );
} catch (Exception e) {
Log.d("Async","EXCEPTION",e);
} finally {
try {
is.close();
bis.close();
} catch (IOException e) {
Log.d("Close","EXCEPTION",e);
}
}
When the MyPicGetTask is an inner class it has access to the bmp field. When you pulled it out of your activity it lost access to the bmp class field.
I would suggest reading Google's documentation and following their examples for AsyncTasks.
The bitmap you return from doInBackground should then be used to update your UI in onPostExecute.
protected void onPostExecute(Bitmap bitmap) {
image.setImageBitmap(bitmap);
}
Your asyncTask subclass needs access to image in order to update the UI, so having it as a inner class is one way to make sure it can do this.
Your AsyncTask if you're using it as a public class outside the activity in which you are calling it needs to recieve the context of that activity. There are a number of posts here, here and here that explain how to set this up.
I have trouble with download image from server in my android app. If i try to download image from https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg
My Code -
bitmap = BitmapFactory.decodeStream((InputStream) new URL(url)
.getContent());
It return null means image not downloading on 4.0.3 but image downloading successfully on 2.2
I think there may be problem with os version.
Now i want anyone to help and guide me for the same.
Write below code into your activity.java file's onCreate method after setcontentview().
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Between 2.2 and 4.0.0 there were some changes regarding what you could do on the UI thread.
From your code snipit I can not tell what thread you are doing this on, but I would expect that this is the same problem.
Try loading your image using an AsyncTask, as you can not perform this http action on the UI thread.
Please confirm about Network on UI Thread Exception and make sure that you are using AsyncTask. Try the same code with AsyncTask, this will help you.
Try this code.
try
{
imageView.setImageDrawable(grabImageFromUrl(imageUrl));
}
catch (Exception e)
{
Log.i("CATCH", "ImageDrawable");
e.printStackTrace();
}
and method code is::
private Drawable grabImageFromUrl(String imageUrlInput) throws MalformedURLException, IOException, Exception
{
return Drawable.createFromStream((InputStream)new URL(imageUrlInput).getContent(), "src");
}
I have created this code for you, try it worked at my end...
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.ImageView;
public class image extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bitmap bitmap = DownloadImage("https://www.morroccomethod.com/components/com_virtuemart/shop_image/category/resized/Trial_Sizes_4e4ac3b0d3491_175x175.jpg");
ImageView img = (ImageView) findViewById(R.id.img);
img.setImageBitmap(bitmap);
}
private InputStream OpenHttpConnection(String urlString) throws IOException {
InputStream in = null;
int response = -1;
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
if (!(conn instanceof HttpURLConnection))
throw new IOException("Not an HTTP connection");
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setAllowUserInteraction(false);
httpConn.setInstanceFollowRedirects(true);
httpConn.setRequestMethod("GET");
httpConn.connect();
response = httpConn.getResponseCode();
if (response == HttpURLConnection.HTTP_OK) {
in = httpConn.getInputStream();
}
} catch (Exception ex) {
throw new IOException("Error connecting");
}
return in;
}
private Bitmap DownloadImage(String URL) {
Bitmap bitmap = null;
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bitmap = BitmapFactory.decodeStream(in);
in.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return bitmap;
}
}
i tried to upload the image to the server for two days but i could not post the image .the coding is compiled and run sucessfully but the imag is not write into the server.
this is my coding:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Toast;
public class sde extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
loadtoUrl("http://
");
}
private void loadtoUrl(String string) {
// TODO Auto-generated method stub
try {
String pathToOurFile = "/sdcard/tamil.PNG";
FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );
BufferedInputStream bis = new BufferedInputStream(fileInputStream,3000);
byte[] bt=new byte[bis.available()];
HttpURLConnection connection = (HttpURLConnection)new URL(string).openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.connect();
FileOutputStream input = (FileOutputStream) connection.getOutputStream();
input.write(bt);
} catch (MalformedURLException e) {
Context context = null;
int duration = 0;
Toast.makeText(context, "erro in writing", duration);
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
here is a nice article, http://blog.sptechnolab.com/2011/03/09/android/android-upload-image-to-server/. It contains an example that will upload an image and write it at server side. It works.
public boolean fileUpload(Map<String , String> params, ByteArrayOutputStream file, String link) throws Throwable{
Account user = Util.getAccount(getApplicationContext());
try{
HttpClient httpClient = new DefaultHttpClient();
HttpPost postRequest = new HttpPost(link);
MultipartEntity multipartContent = new MultipartEntity();
if (params != null && !params.isEmpty()) {
for (Map.Entry<String , String> entry : params.entrySet()) {
multipartContent.addPart(entry.getKey(),new StringBody(entry.getValue(),Charset.forName(HTTP.UTF_8)));
}
}
byte[] data = file.toByteArray();
ByteArrayBody img = new ByteArrayBody(data, "capture.jpg");
multipartContent.addPart("image",img);
postRequest.setEntity(multipartContent);
HttpResponse res = httpClient.execute(postRequest);
res.getEntity().getContent().close();
return true;
}catch(Throwable e){
throw e;
}
}