Why Image is not loading in my android application from remote server? - android

I have used two method to load image from remote server. It is working good in version 2.1(Samsung) and 2.3.4(Sony Ericsson Xperia Neo V). But the method is returning null in a samsung mobile V-2.2. The code is given below.
private Drawable ImageOperations(String url, String saveFilename) {
try {
String realImageUrl = url + "?email=" + Constants.email
+ "&proc_date=" + Constants.proc_date + "&access_key="
+ Constants.ACCESS_KEY + "&version=1.00";
String a = realImageUrl.replace("https", "http");
InputStream is = (InputStream) this.fetch(a);
Log.e("https,SubString http: ", realImageUrl + "," + a);
Drawable d = Drawable.createFromStream(is, "saveFilename");
return d;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
public Object fetch(String address) throws MalformedURLException,
IOException {
try {
URL url = new URL(address);
URI uri = new URI(url.getProtocol(), url.getUserInfo(),
url.getHost(), url.getPort(), url.getPath(),
url.getQuery(), url.getRef());
url = uri.toURL();
Log.i("Url:", url + "");
Object content = url.getContent();
return content;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}

Related

Can't read a pdf file on Android downloaded from my back Spring

I can't read with Acrobat Reader a created file.pdf on my Android Studio (pdf is an exemple, I also need .jpg or .txt) because there is an error.
private void uriGetDocumentGedFindById(Integer id, String extension) throws Throwable {
String url = PreferencesFragment.DEFAULT_SERVER_URL_DOCUMENTGEDFINDBYID + id;
MyHttpClient client = new MyHttpClient(url);
URL url2 = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) url2.openConnection();
responsUriGetDocumentGedFindById = client.getResponseHttpURLConnection(urlConnection);
String name = id.toString() + "." + extension;
saveFile(responsUriGetDocumentGedFindById, name, PreferencesFragment.DOCUMENTS_FOLDER);
}
public void saveFile(String json, String name, String path) throws IOException {
try {
FileWriter writer = new FileWriter(
new File(mContext.getFilesDir().toString() + path, name));
writer.write(json);
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public String getResponseHttpURLConnection(HttpURLConnection urlConnection) {
StringBuffer response = null;
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConnection.getInputStream()));
String inputLine;
response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
return response.toString();
}
I receive this from my back : via Postman on the left (this is functional, I can read the pdf), in my file.pdf (on Android Studio) on the right (there is an error with Acrobat Reader)
So first I can't read my file.pdf and second the file.pdf is bigger than the original whitout any additional information (original 200Ko and my file.pdf 400Ko) this is perhaps a clue...
My back :
#Override
public ResponseEntity<Resource> findByIdDocumentGed(Integer id) throws FileNotFoundException {
DocumentGed documentGed = documentGedService.findByIdDocumentGed(id);
InputStreamResource resource = null;
try {
Integer idFile = documentGed.getFichierCourant().getId();
String extensionFile = documentGed.getFichierCourant().getTypeFichier().getExtension();
File file = new File(nasIris + "/ged/import/" + idFile + "." + extensionFile);
resource = new InputStreamResource(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (resource == null) {
return new ResponseEntity<>(resource, new HttpHeaders(), HttpStatus.NOT_FOUND);
}
return new ResponseEntity<>(resource, new HttpHeaders(), HttpStatus.OK);
}
Have you tried to use FileOutputStream instead FileWriter ?

how to download web buffers in android?

I'm developping in galaxy note 10.1
the download action start java spring action.
this download action is well proceed in PC, browser in mobile device
the problem is galaxy note 10.1 built-in browser
this browser's userAgent is
"Mozilla/5.0 (Linux; U; Android 4.0.4; ko-kr; SHW-M480W Build/IMM76D) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30"
and android's download method is
mWebView.setDownloadListener(new DownloadListener(){
public void onDownloadStart(String url, String sUserAgent, String contentDisposition, String mimetype, long contentLength) {
URL urls = null;
String fileUrl = "";
String mPath = "";
Log.v("sUserAgent", sUserAgent);
String condition[] = contentDisposition.split("=");
String x = condition[1];
Log.d("test",x);
try {
fileUrl = URLDecoder.decode(x, "UTF-8");
} catch(Exception e) {
e.printStackTrace();
}
try {
urls = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
String fileName[] = url.split("/");
Log.d("test", url);
try {
HttpURLConnection conn= (HttpURLConnection)urls.openConnection();
conn.setDoOutput(true);
conn.connect();
mPath = Environment.getExternalStorageDirectory()+"/Download/";
String chkPath = Environment.getExternalStorageDirectory()+"/Download/"+fileUrl;
File chkFile = new File(chkPath);
if(chkFile.exists() == true){}
else {
File f = new File(mPath);
f.mkdirs();
File OutputFile = new File(f, fileUrl);
FileOutputStream fos = new FileOutputStream(OutputFile);
InputStream is = conn.getInputStream();
byte[]buffer = new byte[24576];
int len1 = 0;
while((len1 = is.read(buffer)) != -1) {
fos.write(buffer, 0, len1);
}
fos.close();
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), "DOWNLOAD COMPLETED", 0).show();
File files = new File(mPath+fileUrl);
Log.e("msg",mPath+fileUrl+"");
Intent intent = new Intent(Intent.ACTION_VIEW);
String mimes = fileUrl.substring(fileUrl.length()-3, fileUrl.length());
if(mimes.equals("hwp")) {
intent.setDataAndType(Uri.fromFile(files), "application/x-hwp");
} else {
intent.setDataAndType(Uri.fromFile(files), "application/"+mimes);
}
startActivity(intent);
}
});
the spring download action is
String mimetype = "application/x-msdownload";
response.setContentType(mimetype);
response.setHeader("fileName", fvo.getFileStreCours()+fvo.getStreFileNm());
setDisposition(fvo.getOrignlFileNm(), request, response);
response.setContentLength(fSize);
BufferedInputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new FileInputStream(uFile));
out = new BufferedOutputStream(response.getOutputStream());
FileCopyUtils.copy(in, out);
out.flush();
response.flushBuffer();
} catch (Exception ex) {
// Connection reset by peer: socket write error
log.debug("IGNORED: " + ex.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ignore) {
log.debug("IGNORED: " + ignore.getMessage());
}
}
if (out != null) {
try {
out.close();
} catch (Exception ignore) {
log.debug("IGNORED: " + ignore.getMessage());
}
}
}
this file is downloading from NAS
but android was not access web's response buffer
in android, maked 0 byte file.
how to access buffer and download file in web's response buffer?
ps. web service not allow open url, so I can't use redirect

Why image is not loading from url of android application?

I have created an android application where image is loading from given url.When I am passing url directly, the image is loading. But image is not loading when I am taking the url inside a string variable and passing that variable . My code is given below .
private Drawable ImageOperations(String url, String saveFilename) {
try {
String realImageUrl=url+"? email="+Constants.email+"&proc_date="+Constants.proc_date+"&access_key="
+Constants.ACCESS_KEY+"&version=1.00";
String newUrl=realImageUrl.replace("https", "http");
InputStream is = (InputStream) this.fetch(newUrl);
Log.e("https,SubString http: ",realImageUrl+","+ a);
Drawable d = Drawable.createFromStream(is, "src");
return d;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
public Object fetch(String address) throws MalformedURLException,
IOException {
URL url = new URL(address);
Object content = url.getContent();
return content;
}
This code is not working. my new url is newUrl. when I am printing newUrl in my log and giving that url directly instead of newUrl the image is loading.
I have found the solution. I have updated the fetch(String address) method.
public Object fetch(String address) throws MalformedURLException,
IOException {
try{
URL url = new URL(address);
URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(), url.getQuery(), url.getRef());
url = uri.toURL();
Log.i("Url:", url+"");
Object content = url.getContent();
return content;
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}

WebView download listener is giving Target host must not be null, or set in parameters error

In my WebView am trying to download some files from some web sites but on execution of http response it is giving an error saying "Target host must not be null,".
My piece of code is...
// TODO: Download Listener
webview.setDownloadListener(new DownloadListener() {
#Override
public void onDownloadStart(String url, String sUserAgent,
String contentDisposition, String mimetype,
long contentLength) {
if (sUserAgent == null) {
Log.e(TAG + " - Conexion", "Error on useragent");
}
String PATH = Environment.getExternalStorageDirectory()
+ "/download/";
Log.v("", "PATH: " + PATH);
File file = new File(PATH);
if (file.mkdirs()) {
System.out.println("Directry-->" + PATH + " is created");
}
try {
mUrl = new URL(url);
} catch (MalformedURLException e2) {
e2.printStackTrace();
}
String fileName = getFileName(mUrl);
File outputFile = new File(file, fileName);
try {
fos = new FileOutputStream(outputFile);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
client = new DefaultHttpClient();
try {
HttpPost request = new HttpPost(URLEncoder.encode(url, "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
request.setHeader("User-Agent", sUserAgent);
try {
response = client.execute(request);
StatusLine status = response.getStatusLine();
if (status.getStatusCode() != HTTP_STATUS_OK) {
Toast.makeText(myApp, "Error On Download",Toast.LENGTH_SHORT).show();
} else {
InputStream in = response.getEntity().getContent();
byte[] read = new byte[1024];
int numReadBytes = 0, singleByte;
boolean endFlow = false;
do {
singleByte = in.read();
endFlow = singleByte == -1;
if (!endFlow) {
read[numReadBytes] = (byte) singleByte;
numReadBytes++;
}
} while (!endFlow);
if (numReadBytes > 0) {
fos.write(read, 0, numReadBytes);
}
}
} catch (IOException e) {
Log.e(TAG + " - Conexion", e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
Log.e(TAG + " - Conexion", e.getMessage());
}
}
});
Try to use:
Add "http://" to "api.i-v-o.ch"
So it should be: "http://api.i-v-o.ch"
mostly it will help you...

Android Zooming For Graphs

I need to implement zoom functionality for graphs which are retrieving from web. These graphs are from php web-server so how to implement zooming functionality to these graphs. Any one can help me to come out from this issue. This is my java class code for retriving graphs from web.
localPalladium1YButton.setOnClickListener( new View.OnClickListener() {
public void onClick(View view)
{
localPalladium1DButton.setBackgroundResource(R.drawable.onedicon);
localPalladium5DButton.setBackgroundResource(R.drawable.fived);
localPalladium1MButton.setBackgroundResource(R.drawable.whitem);
localPalladium1YButton.setBackgroundResource(R.drawable.yover);
android.view.View.OnClickListener getImgListener = null;
localPalladium1YButton.setOnClickListener(getImgListener);
Bitmap palladiumBitmap3=fetchImage( PalladiumImageUrl4.trim() );
localPalladiumImageView.setImageBitmap( palladiumBitmap3 );
mSoundManager.playSound(1);
}
});
..................................
..................................
..................................
Bitmap bmImg;
void downloadFile(String fileUrl){
URL myFileUrl =null;
try {
myFileUrl= new URL(fileUrl);
}
catch (MalformedURLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String url1 = "my url";
URL url = new URL(url1);
URLConnection conn = url.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
BitmapFactory.Options bf = new BitmapFactory.Options();
Bitmap bm = BitmapFactory.decodeStream(bis);
ImageView localGoldImageView = null;
localGoldImageView.setImageBitmap(bm);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Bitmap fetchImage( String urlstr )
{
try
{
URL url;
url = new URL( urlstr );
HttpURLConnection c = ( HttpURLConnection ) url.openConnection();
c.setDoInput( true );
c.connect();
InputStream is = c.getInputStream();
Bitmap img;
img = BitmapFactory.decodeStream( is );
return img;
}
catch ( MalformedURLException e )
{
Log.d( "RemoteImageHandler", "fetchImage passed invalid URL: " + urlstr );
e.printStackTrace();
}
catch ( IOException e )
{
Log.d( "RemoteImageHandler", "fetchImage IO exception: " + e );
e.printStackTrace();
}
return null;
}
Thanks,
Murali.
Take a look at http://code.google.com/p/android-pinch/: it has code to implement zooming using pinch.

Categories

Resources