print pdf/ image file with Thermal printer android [closed] - android

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to print the image with a thermal printer which is stored in phone local storage. But it is printing a very small image. can anyone suggest me how to print the image via a thermal printer( Ethernet)
code:
MainActivity.java:
public class MainActivity extends Activity {
Socket socket = null;
RelativeLayout relativeLayout;
String htmlDocument;
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myWebView =(WebView)findViewById(R.id.myWebView);
relativeLayout = (RelativeLayout) findViewById(R.id.print);
htmlDocument = "<html><body><h2>Basic HTML Table</h2><table style=\"width:30%\"><tr><th>Firstname</th><th>Lastname</th><th>Age</th></tr><tr><td>Jill</td><td>Smith</td><td>50</td></tr><tr><td>Eve</td><td>Jackson</td><td>94</td></tr><tr><td>John</td><td>Doe</td><td>80</td></tr></table></body></html>";
myWebView.loadData(htmlDocument, "text/HTML", "UTF-8");
new Timer().schedule(new TimerTask() {
#RequiresApi(api = Build.VERSION_CODES.KITKAT)
#Override
public void run() {
laytooimag();
// this code will be executed after 2 seconds
}
}, 5000);
}
public void laytooimag() {
relativeLayout.setDrawingCacheEnabled(true);
relativeLayout.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
relativeLayout.layout(0, 0, relativeLayout.getMeasuredWidth(), relativeLayout.getMeasuredHeight());
relativeLayout.buildDrawingCache();
Bitmap bm = Bitmap.createBitmap(relativeLayout.getDrawingCache());
relativeLayout.setDrawingCacheEnabled(false);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/jpeg");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
Log.v("Tag_file",""+f);
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
new EthernetPrint()
.execute(resultdata);
}
private class EthernetPrint extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
try {
resultdata = params[0];
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// socket = new Socket(r.printerDetails.ipAddress, r.printerDetails.port);
socket = new Socket("192.168.1.23", 9100);
DataOutputStream DOS = new DataOutputStream(socket.getOutputStream());
byte[] printformat = new byte[]{0x1B, 0x21, 0x03};
DOS.write(printformat);
Printerinterface bb = new Printerinterface(getApplicationContext(), "Ethernet", null, DOS);
Log.v("Tag_d",""+"ethdoin");
printKot_invoice(bb);
resultdata = "Executed";
DOS.flush();
DOS.close();
socket.close();
} catch (IOException e) {
resultdata = "";
e.printStackTrace();
}
return resultdata;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
//printKot_invoice();
}
public void printKot_invoice(Printerinterface bb) {
bb.printPhoto(R.drawable.testimg);
}
}
Printerinterface.java:
public class Printerinterface {
public void printPhoto(int img) {
try {
File image = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
Bitmap bitmap = decodeFile(image,100,100);
if(bitmap!=null){
byte[] command = Utils.decodeBitmap(bitmap);
_outputstream().write(PrinterCommands.ESC_ALIGN_CENTER);
printText(command);
}else{
Log.e("Print Photo error", "the file isn't exists");
}
} catch (Exception e) {
e.printStackTrace();
Log.e("PrintTools", "the file isn't exists");
}
}
public static Bitmap decodeFile(File f,int WIDTH,int HIGHT){
try {
//Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f),null,o);
//The new size we want to scale to000
final int REQUIRED_WIDTH=WIDTH;
final int REQUIRED_HIGHT=HIGHT;
//Find the correct scale value. It should be the power of 2.
int scale=1;
while(o.outWidth/scale/2>=REQUIRED_WIDTH && o.outHeight/scale/2>=REQUIRED_HIGHT)
scale*=2;
//Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize=scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
}
catch (FileNotFoundException e) {}
return null;
}
}
If I did not decode the image, it is showing the error like image width and heights are large.

Related

How to take picture and send to wamp server

I want to send the data(picture taken to wampserver). How does it work?
public class MainActivity extends Activity {
ImageView picture;
Button button;
static final int CAM_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button takePicture = (Button) findViewById(R.id.button);
ImageView picture = (ImageView) findViewById(R.id.imageView);
takePicture.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = getfile();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
//startActivityForResult(intent, 0);
startActivityForResult(intent, CAM_REQUEST);
}
});
}
private File getfile()
{
File folder = new File ("localhost:8080/sampleTest.php");
if (!folder.exists())
{
folder.mkdir();
}
File image_file = new File(folder, "cam_image.jpg");
return image_file;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
//super.onActivityResult(requestCode, resultCode, data);
//Bitmap bitmap = (Bitmap)data.getExtras().get("data");
//picture.setImageBitmap(bitmap);
String path = "localhost:8080/sampleTest.php/cam_image.jpg";
picture.setImageDrawable(Drawable.createFromPath(path));
}
}
I expect the output to take a picture. After taking a picture, send the picture to "localhost:8080/sampleTest.php". However, what i am getting is that i am only able to take a picture, I could not send the picture to wampserver.
Call camera app with intent:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
Get the thumbnail returned from the camera:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
mImageView.setImageBitmap(imageBitmap);
}}
If you want to get an image with better quality, you need to provide an image saving path to the camera app.
Therefore, add the permissions to AndroidManifest.xml
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Improve the intent:
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
Intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
startActivityForResult(intent, 0);
Decode the image file when the result is returned:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0 && resultCode == Activity.RESULT_OK) {
setPic();
}}
private void setPic() {
// Get the dimensions of the View
int targetW = mImageView.getWidth();
int targetH = mImageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
mImageView.setImageBitmap(bitmap);}
Image Transmission from Android Client to Server
Now, we can combine the two functionalities to enhance the Android application.
To access the Internet, add the following permission to AndroidManifest.xml:
<uses-permission android:name="android.permission.INTERNET" />
Refer to this blog, create a class MultipartEntity:
public class MultipartEntity implements HttpEntity {
private String boundary = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
boolean isSetLast = false;
boolean isSetFirst = false;
public MultipartEntity() {
this.boundary = System.currentTimeMillis() + "";
}
public void writeFirstBoundaryIfNeeds(){
if(!isSetFirst){
try {
out.write(("--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
isSetFirst = true;
}
public void writeLastBoundaryIfNeeds() {
if(isSetLast){
return ;
}
try {
out.write(("\r\n--" + boundary + "--\r\n").getBytes());
} catch (final IOException e) {
}
isSetLast = true;
}
public void addPart(final String key, final String value) {
writeFirstBoundaryIfNeeds();
try {
out.write(("Content-Disposition: form-data; name=\"" +key+"\"\r\n").getBytes());
out.write("Content-Type: text/plain; charset=UTF-8\r\n".getBytes());
out.write("Content-Transfer-Encoding: 8bit\r\n\r\n".getBytes());
out.write(value.getBytes());
out.write(("\r\n--" + boundary + "\r\n").getBytes());
} catch (final IOException e) {
}
}
public void addPart(final String key, final String fileName, final InputStream fin){
addPart(key, fileName, fin, "application/octet-stream");
}
public void addPart(final String key, final String fileName, final InputStream fin, String type){
writeFirstBoundaryIfNeeds();
try {
type = "Content-Type: "+type+"\r\n";
out.write(("Content-Disposition: form-data; name=\""+ key+"\"; filename=\"" + fileName + "\"\r\n").getBytes());
out.write(type.getBytes());
out.write("Content-Transfer-Encoding: binary\r\n\r\n".getBytes());
final byte[] tmp = new byte[4096];
int l = 0;
while ((l = fin.read(tmp)) != -1) {
out.write(tmp, 0, l);
}
out.flush();
} catch (final IOException e) {
} finally {
try {
fin.close();
} catch (final IOException e) {
}
}
}
public void addPart(final String key, final File value) {
try {
addPart(key, value.getName(), new FileInputStream(value));
} catch (final FileNotFoundException e) {
}
}
#Override
public long getContentLength() {
writeLastBoundaryIfNeeds();
return out.toByteArray().length;
}
#Override
public Header getContentType() {
return new BasicHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
}
#Override
public boolean isChunked() {
return false;
}
#Override
public boolean isRepeatable() {
return false;
}
#Override
public boolean isStreaming() {
return false;
}
#Override
public void writeTo(final OutputStream outstream) throws IOException {
outstream.write(out.toByteArray());
}
#Override
public Header getContentEncoding() {
return null;
}
#Override
public void consumeContent() throws IOException,
UnsupportedOperationException {
if (isStreaming()) {
throw new UnsupportedOperationException(
"Streaming entity does not implement #consumeContent()");
}
}
#Override
public InputStream getContent() throws IOException,
UnsupportedOperationException {
return new ByteArrayInputStream(out.toByteArray());
}}
Use AsyncTask to process the uploading work:
private class UploadTask extends AsyncTask<Bitmap, Void, Void> {
protected Void doInBackground(Bitmap... bitmaps) {
if (bitmaps[0] == null)
return null;
Bitmap bitmap = bitmaps[0];
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream); // convert Bitmap to ByteArrayOutputStream
InputStream in = new ByteArrayInputStream(stream.toByteArray()); // convert ByteArrayOutputStream to ByteArrayInputStream
DefaultHttpClient httpclient = new DefaultHttpClient();
try {
HttpPost httppost = new HttpPost(
"http://192.168.8.84:8003/savetofile.php"); // server
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("myFile",
System.currentTimeMillis() + ".jpg", in);
httppost.setEntity(reqEntity);
Log.i(TAG, "request " + httppost.getRequestLine());
HttpResponse response = null;
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
if (response != null)
Log.i(TAG, "response " + response.getStatusLine().toString());
} finally {
}
} finally {
}
if (in != null) {
try {
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
Toast.makeText(MainActivity.this, R.string.uploaded, Toast.LENGTH_LONG).show();
}
}

load image from URL and save on memory in android

How to load image from URL and save that on memory of device in android? Dont say me use Picasso or oser laibrary.
I need to:
If device get internet conection I load image to ImageView from url and save it on memory of device, else I need to load one of save image to imageView. Thank`s for helps
P.S. Sorry me, I can make some mistakes in question because I don`t very good know English.
This my class:
public class ImageManager {
String file_path;
Bitmap bitmap = null;
public Bitmap donwoaledImageFromSD() {
File image = new File(Environment.getExternalStorageDirectory().getPath(),file_path);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
return bitmap;
}
private void savebitmap() {
File file = new File("first");
file_path = file.getAbsolutePath();
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90,fileOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchImage(final String url, final ImageView iView) {
new AsyncTask<String, Void, Bitmap>() {
protected Bitmap doInBackground(String... iUrl) {
try {
InputStream in = new URL(url).openStream();
bitmap = BitmapFactory.decodeStream(in);
savebitmap();
} catch (Exception e) {
donwoaledImageFromSD();
}
return bitmap;
}
protected void onPostExecute(Bitmap result) {
super.onPostExecute(result);
if (iView != null) {
iView.setImageBitmap(result);
}
}
}.execute(url);
}
}
Try to use this code:
Method for loading image from imageUrl
public Bitmap getBitmapFromURL(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection)
url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream inputStream = connection.getInputStream();
Bitmap imageBitmap = BitmapFactory.decodeStream(inputStream);
return imageBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
And You should use it in a separate thread, like that:
new Thread(new Runnable() {
#Override
public void run() {
try {
Bitmap bitmap = getBitmapFromURL(<URL of your image>);
imageView.setImageBitmap(bitmap);
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
But using Picasso - indeed a better way.
Update:
For saving Bitmap to file on external storage (SD card) You can use method like this:
public static void writeBitmapToSD(String aFileName, Bitmap aBitmap) {
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
File sdPath = Environment.getExternalStorageDirectory();
File sdFile = new File(sdPath, aFileName);
if (sdFile.exists()) {
sdFile.delete ();
}
try {
FileOutputStream out = new FileOutputStream(sdFile);
aBitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
}
}
Remember that You need
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
for it.
And for loading `Bitmap` from file on external storage You can use method like that:
public static Bitmap loadImageFromSD(String aFileName) {
Bitmap result = null;
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
try {
FileInputStream fis = new FileInputStream(new File(Environment.getExternalStorageDirectory(), aFileName));
result = BitmapFactory.decodeStream(fis);
fis.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "loadImageFromSD: " + e.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
You need
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
to do this.
Update 2
Method getBitmapFromURL(), but ImageView should be updated from UI thread, so You should call getBitmapFromURL(), for example, this way:
new Thread(new Runnable() {
#Override
public void run() {
try {
final Bitmap bitmap = getBitmapFromURL("<your_image_URL>");
runOnUiThread(new Runnable() {
#Override
public void run() {
imageView.setImageBitmap(bitmap);
}
});
} catch (Exception e) {
e.printStackTrace();
e.getMessage();
}
}
}).start();
I had this same issue and I hope this helps. First, To download Image from URL into your app, use the code below:
private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public DownloadImageTask(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
In order for the image to be displayed inside the app, use the method below in your onCreate method:
new DownloadImageTask((ImageView) -your imageview id-)
.execute(-your URL-);
In order for the image to be saved INTERNALLY inside the app/phone, use the code below:
#SuppressLint("WrongThread")
protected void onPostExecute(Bitmap result) {
if (result != null) {
File dir = new File(peekAvailableContext().getFilesDir(), "MyImages");
if(!dir.exists()){
dir.mkdir();
}
File destination = new File(dir, "image.jpg");
try {
destination.createNewFile();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
result.compress(Bitmap.CompressFormat.PNG, 0, bos);
byte[] bitmapdata = bos.toByteArray();
FileOutputStream fos = new FileOutputStream(destination);
fos.write(bitmapdata);
fos.flush();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
bmImage.setImageBitmap(result);
}
}
To load the image from the internal storage, use the code below:
private void loadImageFromStorage(String path)
{
try {
File f=new File(path, "image.jpg");
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(f));
ImageView img=(ImageView)findViewById(R.id.businessCard_iv);
img.setImageBitmap(b);
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
Things to note: 1. path is the a string containing the path of the file. 2. "image.jpg" is the file name so ensure that matches with yours. 3. "MyImages" is a folder in your path which contains the actual saved image.

Error while setting bitmap image to ImageView

I am creating a to send image from java server to android client.
Here is my android code:
protected Void doInBackground(Void... arg0) {
try {
socket = new Socket("192.168.237.1", 6666);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
// dataOutputStream.writeUTF(textOut.getText().toString());
String base64Code = dataInputStream.readUTF();
Log.d("String", ":" + base64Code);
//
byte[] decodedString;
decodedString = Base64.decode(base64Code);
Log.d("Ds",""+decodedString);
Log.d("St--", ":" + decodedString.length);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inMutable=true;
bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
Drawable ob=new BitmapDrawable(getResources(),bitmap);
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setBackgroundDrawable(ob);
/*//imageView.setImageBitmap(bitmap);
ByteArrayInputStream input=new ByteArrayInputStream(decodedString);
bitmap=BitmapFactory.decodeStream(input);
imageView.setImageBitmap(bitmap);*/
Log.d("Bitmap",""+bitmap);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
Log.d("Error", "" + e);
}
}
I have encoded the byte array in java usung apache common codec and decoded in android program.
The error I am getting is it gives NullPointeException at imageView.setBackgroundDrawable (ob);.
What is the error in this code??
You need to do it like this:
private class MyAsyncTask extends AsyncTask<Void, Void, Bitmap> {
#Override
protected Bitmap doInBackground(Void... params) {
try {
socket = new Socket("192.168.237.1", 6666);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
// dataOutputStream.writeUTF(textOut.getText().toString());
String base64Code = dataInputStream.readUTF();
Log.d("String", ":" + base64Code);
//
byte[] decodedString;
decodedString = Base64.decode(base64Code);
Log.d("Ds",""+decodedString);
Log.d("St--", ":" + decodedString.length);
BitmapFactory.Options options=new BitmapFactory.Options();
options.inMutable=true;
bitmap = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
return bitmap;
/*//imageView.setImageBitmap(bitmap);
ByteArrayInputStream input=new ByteArrayInputStream(decodedString);
bitmap=BitmapFactory.decodeStream(input);
imageView.setImageBitmap(bitmap);*/
Log.d("Bitmap",""+bitmap);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
Log.d("Error", "" + e);
}
return null;
}
#Override
protected void onPostExecute(Bitmap bitmap) {
if (bitmap != null) {
Drawable ob =new BitmapDrawable(getResources(), bitmap);
imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setBackgroundDrawable(ob);
} else {
// error
}
}
}
You can,t perform UI operations from background thread. They need to be performed in the ui thread. So try and perform thi operationn in onPostExecute().

Android: Downloading images crashing app on API 8

I have a problem in API 8 with AsyncTask...
Here is my code...
try{
new loadPhotos().execute(""+USER._id,"date","DESC");
}catch(Exception e){
e.printStackTrace();
}
Before you ask... YES I am desperate, so I surrounded EVERYTHING with try{}catch
public class loadPhotos extends AsyncTask<String,Object,Void>{
ProgressBar pb;
ImageView img;
TableRow.LayoutParams paramsImage;
List<String> urlsOfImages;
TableLayout tl;
TableRow tr;
LayoutParams lp;
int numberOfPhotos=0;
#Override
protected void onPreExecute(){
urlsOfImages = new ArrayList<String>(); //There is stored urls of all images ( www.example.com/image1.jpg ... etc)
try {
allUserPhotoBitmaps.clear(); //allUserPhotoBitmaps is List<Bitmap>
pb = (ProgressBar) findViewById(R.id.profile_photos_progress_bar);
pb.setVisibility(View.VISIBLE);
tl = (TableLayout) findViewById(R.id.profile_photos_table_layout);
tl.removeAllViews();
tr = new TableRow(Profile.this);
lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
tr.setLayoutParams(lp);
}catch(Exception e){
Toast.makeText(Profile.this, "Error in onPreExecute", Toast.LENGTH_LONG).show();
}
}
#Override
protected Void doInBackground(String... arg) {
try{
// This function basicaly returns List<HashMap<String,String>> with informations about photos ( web_path, latitude, longitude, city, etc...)
allUserPhotoInformations = myDb.getUrlsOfUserImages(arg[0],arg[1],arg[2]);
}catch(Exception e){
Toast.makeText(Profile.this, "Error downloading images", Toast.LENGTH_SHORT).show();
}
if ( allUserPhotoInformations != null ) {
for (int i=0 ; i < allUserPhotoInformations.size() ; i++){
try{
Bitmap bm = getBitmapFromURL(allUserPhotoInformations.get(i).get("file_path"));
allUserPhotoBitmaps.add(bm);
publishProgress(bm,i);
}
catch(Exception e){
return null;
}
}
}
return null;
}
#Override
protected void onProgressUpdate(Object... arg){
img = new ImageView(getBaseContext());
paramsImage = new TableRow.LayoutParams( (((int)screenWidth)/2)-16 , (((((int)screenWidth)/2)-15)/16)*11 );
paramsImage.setMargins(10,10,0,0);
img.setLayoutParams(paramsImage);
img.setBackgroundColor(Color.parseColor("#FF000000"));
try{
img.setImageBitmap((Bitmap) arg[0]);
}catch(Exception e){
Toast.makeText(Profile.this,"Cannot put Bitmap into ImageView",Toast.LENGTH_LONG).show();
}
img.setVisibility(View.VISIBLE);
img.setOnClickListener(new ImageListener((Integer)arg[1])); //here I passing index to onClickListener
tr.addView(img);
if ( numberOfPhotos==1 ){
try{
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}catch(Exception e){
e.printStackTrace();
Toast.makeText(Profile.this,"Cannot inflate tableLayout",Toast.LENGTH_LONG).show();
}
tr = new TableRow(Profile.this);
tr.setLayoutParams(lp);
numberOfPhotos--;
}
else {
numberOfPhotos++;
}
}
#Override
protected void onPostExecute(Void arg){
pb.setVisibility(View.GONE);
userPhotos.setText("uploaded: "+allUserPhotoBitmaps.size()+" photos");
if ( numberOfPhotos==1 ){
try{
tl.addView(tr, new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}catch(Exception e){
e.printStackTrace();
Toast.makeText(Profile.this,"Cannot inflate tableLayout",Toast.LENGTH_LONG).show();
}
tr = new TableRow(Profile.this);
tr.setLayoutParams(lp);
}
}
In my device ( API > 15 ) everything works great, but in API 10 it crashes the app... I you want , I can provide also OnClickListener or some othere methods...
Yes, here ... How I download pictures :
public Bitmap getBitmapFromURL(String src) {
try {
java.net.URL url = new java.net.URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
double width;
double height;
width = (screenWidth)/myBitmap.getRowBytes();
if ( myBitmap.getWidth() > myBitmap.getHeight() ){
Log.w("size","landscape");
height = ((myBitmap.getRowBytes()*width)/16)*11;
width = (height/11)*16;
}
else {
Log.w("size","protrait");
height = ((myBitmap.getRowBytes()*width)/11)*16;
width = (height/16)*11;
}
Bitmap bitmap = Bitmap.createScaledBitmap(myBitmap, (int)width, (int)height, true);
return bitmap;
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(Profile.this, "Error parsing image to bitmap", Toast.LENGTH_LONG).show();
return null;
}
}
Any help ?
call new loadPhotos().execute(""+USER._id,"date","DESC"); in onCreate and Use Asynctask and try to avoid load in main thread. Your application crash one of the main reason may be if you are calling the methode in main thread.
Ex:
String zoomouturl = "your url";
new ImageDownload().execute(zoomouturl);
Try
public class ImageDownload extends AsyncTask<String, Void, String> {
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
loadBitmap(zoomouturl, bmOptions);
return zoomouturl;
}
protected void onPostExecute(String imageUrl) {
if (!imageUrl.equals("")) {
Constants._image.setImageBitmap(bm);
} else {
Toast.makeText(this,
"not found proper bitmap.. ", Toast.LENGTH_LONG)
.show();
}
}
}
and
public static Bitmap loadBitmap(String URL, BitmapFactory.Options options) {
InputStream in = null;
try {
in = OpenHttpConnection(URL);
bm = BitmapFactory.decodeStream(in, null, options);
in.close();
} catch (IOException e1) {
}
return bm;
}
private static InputStream OpenHttpConnection(String strURL)
throws IOException {
InputStream inputStream = null;
URL url = new URL(strURL);
URLConnection conn = url.openConnection();
try {
HttpURLConnection httpConn = (HttpURLConnection) conn;
httpConn.setRequestMethod("GET");
httpConn.connect();
if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) {
inputStream = httpConn.getInputStream();
}
} catch (Exception ex) {
}
return inputStream;
}

Downloaded image can not be displayed

I previously worked on fetching image from sd card displaying it in a list view, that worked using:
imgView.setImageURI(Uri.parse(ImagePath));
Now, I am trying to display image from URL, with the following lines but the image is not displayed in the list view, the following are the lines used:
imgView.setImageBitmap(getBitmapFromURL(ImagePath));
Where, getBitmapFromURL is:
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
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;
}
}
There is no exception displayed, the image just not get displayed.
Need of an urgent solution....
Thanks,
This is a synchronous loading.(Personally I would not use this cause if there are so many Image to be loaded, the apps is a bit laggy)..
URL url = new URL(//your URL);
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);//your imageview
If I were you I would study Async or the lazy adapter..
EDIT
I forgot where I got these code (well thank you for a wonderful code author)
Here it is
public Bitmap getBitmap(String bitmapUrl) {
try {
URL url = new URL(bitmapUrl);
return BitmapFactory.decodeStream(url.openConnection().getInputStream());
}
catch(Exception ex) {return null;}
}
public enum BitmapManager {
INSTANCE;
private final Map<String, SoftReference<Bitmap>> cache;
private final ExecutorService pool;
private Map<ImageView, String> imageViews = Collections
.synchronizedMap(new WeakHashMap<ImageView, String>());
private Bitmap placeholder;
BitmapManager() {
cache = new HashMap<String, SoftReference<Bitmap>>();
pool = Executors.newFixedThreadPool(5);
}
public void setPlaceholder(Bitmap bmp) {
placeholder = bmp;
}
public Bitmap getBitmapFromCache(String url) {
if (cache.containsKey(url)) {
return cache.get(url).get();
}
return null;
}
public void queueJob(final String url, final ImageView imageView,
final int width, final int height) {
/* Create handler in UI thread. */
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
String tag = imageViews.get(imageView);
if (tag != null && tag.equals(url)) {
if (msg.obj != null) {
imageView.setImageBitmap((Bitmap) msg.obj);
} else {
imageView.setImageBitmap(placeholder);
Log.d(null, "fail " + url);
}
}
}
};
pool.submit(new Runnable() {
public void run() {
final Bitmap bmp = downloadBitmap(url, width, height);
Message message = Message.obtain();
message.obj = bmp;
Log.d(null, "Item downloaded: " + url);
handler.sendMessage(message);
}
});
}
public void loadBitmap(final String url, final ImageView imageView,
final int width, final int height) {
imageViews.put(imageView, url);
Bitmap bitmap = getBitmapFromCache(url);
// check in UI thread, so no concurrency issues
if (bitmap != null) {
Log.i("inh","Item loaded from cache: " + url);
imageView.setImageBitmap(bitmap);
} else {
imageView.setImageBitmap(placeholder);
queueJob(url, imageView, width, height);
}
}
private Bitmap downloadBitmap(String url, int width, int height) {
try {
Bitmap bitmap = BitmapFactory.decodeStream((InputStream) new URL(
url).getContent());
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
Log.i("nandi2 ako", ""+bitmap);
cache.put(url, new SoftReference<Bitmap>(bitmap));
return bitmap;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Now to call it
String fbAvatarUrl = "//Your URL";
BitmapManager.INSTANCE.loadBitmap(fbAvatarUrl, //Your ImageView, 60,60);
//60 60 is my desired height and width
I encountered this kind problem before, you can refer to this thread, if no luck, try my code,
public static Bitmap loadImageFromUrl(String url) {
URL m;
InputStream i = null;
BufferedInputStream bis = null;
ByteArrayOutputStream out =null;
try {
m = new URL(url);
i = (InputStream) m.getContent();
bis = new BufferedInputStream(i,1024 * 8);
out = new ByteArrayOutputStream();
int len=0;
byte[] buffer = new byte[1024];
while((len = bis.read(buffer)) != -1){
out.write(buffer, 0, len);
}
out.close();
bis.close();
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = out.toByteArray();
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
return bitmap;
}

Categories

Resources