Read Dynamically images from web/api (.net) in android - android

how to read dynamically image from web in android, i have a method which takes String type url and return drawable, i want to get an image from remote location and set it in my imageview and through remote location change to image occur and these change automatically reflect in my android application.
i have this code, any help will be appreciable, and thanks in advance
public static Drawable LoadImageFromWeb(String url){
try{
InputStream is = (InputStream) new URL(url).getContent();
Drawable drw = Drawable.createFromPath(url2);
//Drawable draw = Drawable.createFromStream(is, url2);
return drw;
}catch(Exception ex){
ex.printStackTrace();
return null;
}
thanks.

You could use an external library like Picasso or Universal-Image-Loader. URLS:
http://square.github.io/picasso/
https://github.com/nostra13/Android-Universal-Image-Loader

Use the bellow http network connection in Asynctask or a thrad.
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 20000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 30000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpclient = new DefaultHttpClient(httpParameters);
HttpPost httppost = new HttpPost(url);
//Adding the parameter values (if required input to remote service)
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair(Constants.URL_PARAM_PROVIDERID,Utilities.getProviderID(PageCurlGraph.this)));
nameValuePairs.add(new BasicNameValuePair("requestedDate",params[i]));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
//Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity httpEntity = response.getEntity();
InputStream instream = httpEntity.getContent();
Bitmap bitmap = BitmapFactory.decodeStream(instream);
gm = new GraphModel();
gm.setBitmap(bitmap);

your code is a bad way to showing an remote image from url. it can caused your apps not responsive.
i recommend you to using some 'image loader library' which it is take the advantages of android asynchronous task and keep your apps responsive.
for example, you can use this library:
https://github.com/androidquery/androidquery/releases/tag/0.26.8
all you need to do is import the library into your project, then load your image in just a view code:
ImageView imgView = (ImageView) findViewById(R.id.imageview);
AQuery aq = new AQuery(this); // assume you are doing this inside activity
String someImageURL = "http://someurl.com/someimage.jpg";
aq.id(imgView).image(someImageURL, true, true); // see documentation for detail

if u don't want to use tool or image loader library and your application not interacting to internet continuously, Then
you can take XML from server at ones, that containing image url's list, parse the XML, and download them one by one on sd card and show them offline by using ImageView.setImageResource(...) this process will make your app more faster and you can set time interval to check update from server.
If u have large no of images then u have to use image loader library because above process may cause memory space issue on device .

Related

How to show picture in Android app that can be changed every week? Like flyer for specials that changes every week

I'm working/learning on an app for my store. The whole purpose of this app is to a customer can check recent flyer in the app.
How can I replace that image every week? how does update on app (like image change) works? Does customer need to update the app in order to see new image? or is there any way where my app will fetch photo from "XYZ" location online, and all I have to do is upload that image online to "XYZ" location.
I suggest showing your weekly image from a URL like this
ImageView img = (ImageView) findViewById(R.id.imageView1);
try {
URL url = new URL("http://web.yourcompany.com/weekly.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) {
}
or using the WebView to load the image from URL.
WebView web = (WebView) findViewById(R.id.webView1);
web.loadUrl("Your/Url.jpg");
Ideally, you want to call this code from a separate thread.

Android - send data to server with HttpURLConnection

I was following this tutorial to upload images with android: here
After the line conn.setRequestProperty("uploaded_file", fileName); in function uploadFile(String sourceFileUri) I added further lines with conn.setRequestProperty("title", "example"); conn.setRequestProperty("name", "simple_image"); but in the php file I am not receiving these strings with $_POST or $_GET only the image is uploaded.
Is this tutorial here only for uploading images?
I would like to send with the image some other data too. How could I do this?
Thank you
Yes that tutorial is for uploading a single file only.If you want to send some other data(may be some strings) along with your image, then you can use MultipartEntityBuilder.However to use this you need to download the jars from the Apache HttpComponents site and add them to project and path(just add the httpclient jar to your libs folder).
Now for uploading an image along with some string data you can use (may be inside doInBackground of your AsynTask)
File file = new File("yourImagePath");
String urlString = "http://yoursite.com";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(urlString);
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
/* setting a HttpMultipartMode */
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
/* adding an image part */
FileBody bin1 = new FileBody(file);
builder.addPart("uploadedfile1", bin1);
builder.addPart("user", new StringBody("Some String",ContentType.TEXT_PLAIN));//adding a string
HttpEntity reqEntity = builder.build();
post.setEntity(reqEntity);
HttpEntity resultEntity = httpResponse.getEntity();
String result = EntityUtils.toString(resultEntity);
P.S : I assumed you are using AsyncTask for uploading process and that's the reason i said to use this code inside doInBackground of your AsyncTask.
You can use MultipartEntity too.Follow this tutorial which describes how to upload multiple images along with some other string data using MultipartEntity.However there's not much difference in the implementation of MultipartEntity and MultipartEntityBuilder.Try yourself to learn both.Hope these info help you.

Sending JSON From Android to PHP

I've been struggling a bit on sending JSON objects from an application on android to a php file (hosted locally). The php bit is irrelevant to my issue as wireshark isn't recording any activity from my application (emulation in eclipse/ADK) and it's almost certainly to do with my method of sending:
try {
JSONObject json = new JSONObject();
json.put("id", "5");
json.put("time", "3:00");
json.put("date", "03.04.12");
HttpParams httpParams = new BasicHttpParams();
HttpClient client = new DefaultHttpClient(httpParams);
//
//String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
// "json={\"UserName\":1,\"FullName\":2}";
String url = "http://localhost/datarecieve.php";
HttpPost request = new HttpPost(url);
request.setEntity(new ByteArrayEntity(json.toString().getBytes(
"UTF8")));
request.setHeader("json", json.toString());
HttpResponse response = client.execute(request);
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
if (entity != null) {
InputStream instream = entity.getContent();
}
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
I've modified this from an example I found, so I'm sure I've taken some perfectly good code and mangled it. I understand the requirement for multi-threading so my application doesn't hang and die, but am unsure about the implementation of it. Would using Asynctask fix this issue, or have I missed something else important?
Thankyou for any help you can provide.
Assuming that you are using emulator to test the code, localhost refers to the emulated environment. If you need to access the php hosted on your computer, you need to use the IP 10.0.2.2 or the LAN IP such as 192.168.1.3. Check Referring to localhost from the emulated environment
You can refer to Keeping Your App Responsive to learn about running your long running operations in an AsyncTask
you should use asynctask or thread, because in higher versions of android it doesn't allow long running task like network operations from ui thread.
here is the link for more description

Get image by REST call and display on android

Here is the link where I place a REST GET call.
http://adtouch.cloudfoundry.com/rest/ad/barcode/529a927973654526a309a77986062566/image
On opening it in browser, it redirects to other link and I get an image displayed.
I want to display this image on android. I am unable to determine what is the content I get by this call and how to convert it to an image to be displayed on android device.
This is the rest call I make:
HttpClient httpclient = new DefaultHttpClient();
String temp = "http://adtouch.cloudfoundry.com/rest/ad/barcode/529a927973654526a309a77986062566/image";
HttpGet request = new HttpGet(temp);
HttpResponse response = httpclient.execute(request);
ResponseHandler<String> handler = new BasicResponseHandler();
String result = httpclient.execute(request, handler);
System.out.println(result);
The result of this is numerous sequence of characters like:
(^( ?( ;QE??QE??ÊMÔâ1MT ??²¤i­#íù¨ùhÙQ¶ê??m7Í¡?mFÏ#3|µu]¿Þ§+Uò?\°Ñ³Qçý?o?MiUWt?*¯÷?ª9Jæ·û´Ý¿59_åùi¬Õq$jE¨)ÿ??Á#D°?©ËÒªÆß7Þ«?õ q?/ÉR+Tr%F?¨(·LÙQ­9]¨Ê´í?½;}??5???¨ßE??º?ôúc÷ ?·éGÍíFæZ??M­K·ûÔè÷?Þ©<¥Û#Æ?ýÚ±üÕEJ7l O?Z³YêÄÒï¨ÕhK{}ë¹¾íZ?>U¨c}?RG#QGðüÍM2®>\·û´??í?l¨ÿ??xß«NUþón }Ênÿ??î­9UR???nÖ?Å·ýÚo?¿Ä»¿Þ©(
I know how to set an image to the ImageView but the question is how to get an image from this call.
Look at the Javadoc for BitmapFactory. You must decode the stream in the HTTP response's entity:
InputStream in = client.execute(request).getEntity().getContent();
Bitmap bmp = BitmapFactory.decode(in);
in.close();
Note that network operations should not happen in the main thread. From your code it's not clear if you use an AsyncTask or not, however you should. Update the image in the onPostExecute() hook.

Do POST request with Android DefaultHTTPClient cause freeze on execute()

I need post data to server.
I use this code:
HttpClient client = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(serverUrl);
StringEntity se = new StringEntity(data);
httppost.setEntity(se);
httppost.setHeader("Accept", "application/json");
httppost.setHeader("Content-type", "application/json");
// Execute HTTP Post Request
HttpResponse response = client.execute(httppost);
int statusCode = response.getStatusLine().getStatusCode();
Log.i(TVProgram.TAG, "ErrorHandler post status code: " + statusCode);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (client != null) {
client.getConnectionManager().shutdown();
}
}
But problem is that Android freeze on execute() method, application is blocked out and after some time Android tell me that application doesn't respond.
I tried to debug into SDK classes and it freeze in AbstractSessionInputBuffer class on the line 103 which is
l = this.instream.read(this.buffer, off, len);
I also tried it run the request in separated thread, but the same problem.
I tested it on Android 2.1 (emulator) and Android 2.2 real mobile device.
I also tried to set HTTP proxy and use Fiddler to check HTTP communication data are received by server and server also send correct answer and HTTP code 200. All seems to be ok.
What is wrong please?
UPDATE: When I use AndroidHttpClient which is part of Android 2.2 SDK it works great. But it is not in earlier version of Android. So I include it's source code in my app for now. But AndroidHttpClient use DefaultHTTPClient internally, so problem will be in configuration of DefaultHttpClient.
I am using a POST HTTP request successfully. Here is my code. I removed pieces using handler to display messages etc. and the handler itself.
The POST string is like "&NAME=value#NAME2=value2"...
protected class ConnectingThread implements Runnable
{
Message msg;
private Handler mExtHandler;
private String mData;
private String mUrl;
/**
* #param h (Handler) - a handler for messages from this thread
* #param data (String) - data to be send in HTTP request's POST
* #param url (String) - URL to which to connect
*/
ConnectingThread(Handler h, String data, String url) {
mExtHandler = h;
mData = data;
mUrl = url;
}
public void run() {
try {
// TODO use the handler to display txt info about connection
URL url = new URL(mUrl);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(CONN_TIMEOUT_MILLIS);
conn.setDoOutput(true);
BufferedOutputStream wr = new BufferedOutputStream(conn.getOutputStream());
wr.write(mData.getBytes());
wr.flush();
wr.close();
String sReturn = null;
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
int length = conn.getContentLength();
char[] buffer = new char[length];
int read = rd.read(buffer);
if(read == length)
sReturn = new String(buffer);
rd.close();
buffer = null;
// TODO use the handler to use the response
} catch (Exception e) {
//....
}
// TODO use the handler to display txt info about connection ERROR
}
}
Isn't client.execute(httppost); synchronous ?
You probably need to put this in a thread, else it will freeze the UI.
Yes it is being freezed just becoz you haven't implemented this as Asynchronous process. Because while it makes web request, your UI will wait for the response and then it will be updated once the response is received.
So this should be implemented as Asynchronous process, and user should be notified (with progress bar or progress dialog) that there is something happening.
Now, Instead of implementing Runnable class, in android its preferrable and recommended to use AsyncTask, its also known as Painless Threading.
Do you background tasks inside the doInBackground() method.
Do your display type of operations inside onPostExecute() method, like updating listview with fetched data, display values inside TextViews....etc.
Display ProgressBar or ProgressDialog inside the onPreExecute() method.
Use AndroidHttpClient helped me in this situation.
But now complete AndroidHttpClient and DefaultHttpClient are obsolete in current version of Android so it is not important now.

Categories

Resources