Progress bar dialog is not working with FTP uploading in android - android-asynctask

In Asynctask,either the progress bar is working or file is uploading successfully.
COMMENT2 line upload file properly when we write before the COMMENT1 line but progress bar is not working.
But if we write COMMENT2 after COMMENT1 then we face ERROR code 500(Syntax error) and uploading failed but progress bar
works properly.
private class AsyncCaller extends AsyncTask<String, Integer, String> {
int bytesRead, bytesAvailable, bufferSize = 1024,progress;
byte[] buffer;
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage("Uploading file..");
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setIndeterminate(false);
mProgressDialog.setCancelable(false);
mProgressDialog.setProgress(0);
mProgressDialog.setMax(100);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
// connection();
FTPClient con = null;
try
{
con = new FTPClient();
con.connect(FTP_HOST);
if (con.login(FTP_USER, FTP_PASS))
{
con.enterLocalActiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
con.changeWorkingDirectory("/uploads/school-staging/files/");
String data = FilePath;
final DataOutputStream out = new DataOutputStream(con.getOutputStream());
BufferedInputStream in = new BufferedInputStream(new FileInputStream(data));
int bufferSize=1024;
byte[] buffer = new byte[bufferSize];
// Read file
bytesRead = in.read(buffer, 0, bufferSize);//COMMENT 1
progress=0;
System.out.println("BYTE READ="+bytesRead);
while (bytesRead > 0)
{
progress+=bytesRead;
System.out.println("PROGRESS="+progress);
out.write(buffer, 0, bytesRead);
bytesAvailable = in.available();
publishProgress((int)((progress*100)/(file.length())));
bufferSize = Math.min(bytesAvailable, bufferSize);
bytesRead = in.read(buffer, 0, bufferSize);
}
boolean result = con.storeFile(FileName, in);//COMMENT 2
int code= con.getReplyCode();
System.out.println("CODE="+code);
in.close();
publishProgress(100);
if (result) Log.v("upload result", "succeeded");
System.out.println("RESULT="+result);
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return "ok";
}
#Override
public void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
mProgressDialog.setProgress(values[0]);
}//end of onProgressUpdate
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
connection();
mProgressDialog.dismiss();
}

I've faced similar problem. The reason for this seems to be that the ui code in onPreExecute() doesnt get to render by android system, and code in doInBackground() occupies the cpu. You can dismiss the dialog in onPostExecute() though...
You'd have to show the progress dialog before creating AsyncCaller, pass the progress dialog to AsyncCaller and you can dismiss it in onPostExecute().
ProgressDialog pd = new ProgressDialog(getActivity());
pd.setTitle("title string");
pd.setIndeterminate(true);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.show();
new AsyncCaller(getActivity(), pd).execute(params);
in onPostExecute():
if (pd != null && pd.isShowing())
pd.dismiss();

Related

Insert Image into PDF Document

Is it possible to add an image to the PDF document? My layout has one (Button) and one (ImageView), I would like that when I click (Button), it will open the Gallery to select the image, show it in (ImageView) and add it to the PDF document, as if it were a generator curriculum, thank you in advance.
*Using com.itextpdf:itextg:5.5.10
here is the complete code of what you wanted. Try this and let me know.
In the onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_to_pdf);
imageView = findViewById(R.id.imageView);
galleryBtn = findViewById(R.id.gallery);
convertBtn = findViewById(R.id.convert);
galleryBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
String imageFileName = "PDF_" + timeStamp + "_";
File storageDir = getAlbumDir();
try {
pdfPath = File.createTempFile(
imageFileName, /* prefix */
".pdf", /* suffix */
storageDir /* directory */
);
} catch (IOException e) {
e.printStackTrace();
}
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(photoPickerIntent, GALLERY_INTENT);
}
});
convertBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (bitmap == null) {
Toast.makeText(ImageToPDF.this, "Please select the image from gallery", Toast.LENGTH_LONG).show();
} else {
convertToPDF(pdfPath);
}
}
});
}
Create a directory for PDF file:
private File getAlbumDir() {
File storageDir = null;
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
storageDir = new File(Environment.getExternalStorageDirectory()
+ "/dcim/"
+ "Image to pdf");
if (!storageDir.mkdirs()) {
if (!storageDir.exists()) {
Log.d("CameraSample", "failed to create directory");
return null;
}
}
} else {
Log.v(getString(R.string.app_name), "External storage is not mounted READ/WRITE.");
}
return storageDir;
}
On camera activity intent result:
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == GALLERY_INTENT) {
if (resultCode == Activity.RESULT_OK && data != null) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
if (selectedImage != null) {
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String imagePath = cursor.getString(columnIndex);
bitmap = BitmapFactory.decodeFile(imagePath);
imageView.setImageBitmap(bitmap);
cursor.close();
}
}
} else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("Canceled", "Image not selected");
}
}
}
Now code to convert image to PDF and save to the directory:
private void convertToPDF(File pdfPath) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
PdfDocument pdfDocument = new PdfDocument();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(width, height, 1).create();
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.parseColor("#ffffff"));
canvas.drawPaint(paint);
bitmap = Bitmap.createScaledBitmap(bitmap, width, height, true);
paint.setColor(Color.BLUE);
canvas.drawBitmap(bitmap, 0, 0, null);
pdfDocument.finishPage(page);
try {
pdfDocument.writeTo(new FileOutputStream(pdfPath));
Toast.makeText(ImageToPDF.this, "Image is successfully converted to PDF", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
pdfDocument.close();
}

JOGL: Black panel on windows

I have a class that extends a GLJPanel and has a GLEventListener with
#Override
public void display( GLAutoDrawable glautodrawable ) {
System.out.println("Painting");
if(image!=null){
GL2 gl2 = glautodrawable.getGL().getGL2();
int format = GL.GL_LUMINANCE;
int type = GL.GL_UNSIGNED_SHORT;
DataBufferUShort db = (DataBufferUShort) image.getRaster().getDataBuffer();
short[] shorts = db.getData(0);
Buffer buffer = ShortBuffer.wrap(shorts);
gl2.glDrawPixels(image.getWidth(), image.getHeight(), format , type, buffer );
}
}
On Linux the image is displayed as I expect and the display method is called. On Windows the same code displays a black screen and it doesn't look like it calls the display method. The gears demo runs no problem on the Windows system.
EDIT:
I have narrowed it down to issues with GridBagLayout. Setting the gbc.anchor equal to LINE_START, LINE_END and CENTER is causing the image to appear or not
int bitdepth = 10;
GLProfile.initSingleton();
GLProfile glProfile = GLProfile.getDefault();
GLCapabilities glCapabilities = new GLCapabilities( glProfile );
glCapabilities.setBlueBits(bitdepth);
glCapabilities.setGreenBits(bitdepth);
glCapabilities.setRedBits(bitdepth);
glCapabilities.setAlphaBits(2);
glCapabilities.setDoubleBuffered(true);
glCapabilities.setHardwareAccelerated(true);
glCapabilities.setNumSamples(4);
glCapabilities.setBackgroundOpaque(false);
glCapabilities.setSampleBuffers(true);
GraphicsConfiguration gc = DeviceController.getConfOfRightMostMonitorAndLargest();
JFrame jf = new JFrame(gc);
jf.setExtendedState(JFrame.MAXIMIZED_BOTH);
GLCanvas canvas = new GLCanvas(glCapabilities);
canvas.addGLEventListener(new GLEventListener() {
#Override
public void reshape(GLAutoDrawable arg0, int arg1, int arg2, int arg3,
int arg4) {
// TODO Auto-generated method stub
}
#Override
public void init(GLAutoDrawable arg0) {
// TODO Auto-generated method stub
}
#Override
public void dispose(GLAutoDrawable arg0) {
// TODO Auto-generated method stub
}
#Override
public void display(GLAutoDrawable drawable) {
System.out.println("Painting");
BufferedImage image = null;
try {
image = ImageIO.read(new File("img.tiff"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(image!=null){
GL2 gl2 = drawable.getGL().getGL2();
//gl2.glClear(GL.GL_COLOR_BUFFER_BIT);
int format = GL.GL_LUMINANCE;
int type = GL.GL_UNSIGNED_SHORT;
DataBufferUShort db = (DataBufferUShort) image.getRaster().getDataBuffer();
short[] shorts = db.getData(0);
Buffer buffer = ShortBuffer.wrap(shorts);
//gl2.glViewport(0, 0, image.getWidth(), image.getHeight());
gl2.glDrawPixels(image.getWidth(), image.getHeight(), format , type, buffer );
}
}
});
JPanel jp = new JPanel();
jp.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.BOTH;
gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=1;
gbc.gridheight=1;
gbc.weightx=1;
gbc.weighty=1;
gbc.anchor= GridBagConstraints.CENTER;
jp.add(canvas,gbc);
JScrollPane jsp = new JScrollPane();
jsp.getViewport().add(jp);
JLayeredPane jlp = new JLayeredPane();
jlp.setLayout(new GridBagLayout());
jlp.add(jsp, gbc);
//jsp.getViewport().add(dsc);
gbc = new GridBagConstraints();
gbc.gridx=0;
gbc.gridy=0;
gbc.gridwidth=1;
gbc.gridheight=1;
gbc.weightx=1;
gbc.weighty=1;
gbc.fill=GridBagConstraints.NONE;
gbc.anchor= GridBagConstraints.CENTER;
jf.getContentPane().setLayout(new GridBagLayout());
jf.getContentPane().add(jlp,gbc);
jf.setVisible(true);

Making an android image editor and i have an issue with handling my Bitmaps into variables

This is a part of my onActivity Result code. What i want to do is make a bitmap variable that i can modify everytime i press a button instead of modifying the ImageView(imagen) and not saving the changes that happen to the image.
When i try to change the btp_tmp variable inside the onClick code of the button it throws an error about btp_tmp being in an inner class and must be made final.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap btp_img = null;
InputStream in_stream;
Bitmap btp_tmp = null;
if (resultCode == Activity.RESULT_OK && requestCode == RCode)
{
//ARXIKO IMAGE
try {
if (btp_img != null) {
btp_img.recycle();
}
in_stream = getContentResolver().openInputStream(
data.getData());
btp_img = BitmapFactory.decodeStream(in_stream);
in_stream.close();
btp_tmp = btp_img;
imagen.setImageBitmap(btp_img);
//btn_seleccion.setText(getResources().getString(R.string.modifa));
} catch (IOException e) {
e.printStackTrace();
}
//NEGATIVE
//final boolean test = false;
final Bitmap finalBtp_img1 = btp_tmp;
//if (test == false){}
btp_tmp = btp_img;
Neg_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//imagen.setImageBitmap(invert(finalBtp_img));
Negative neg = new Negative();
imagen.setImageBitmap(neg.invert(finalBtp_img1));
btp_tmp = neg.invert(finalBtp_img1);
}
});
//UNDO
final Bitmap finalBtp_imgUndo = btp_img;
eraser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
imagen.setImageBitmap(finalBtp_imgUndo);
}
});
I found the solution. The mistake i was doing is that i didn't declare the temporary variable in the Main Activity Class, so i got an error everytime i used the variable in the OnActivity part of the code.
Rookie mistake for sure.

How to convert image to base64 string in Windows Phone?

I am developing a windows phone application in which I have to convert image to base64 string and I have to pass that string through Web Service. So I tried many Ways, but I cant able to send it as everytime I am getting error as "Target Invocation error". With this code I can choose the image from library but I cant send through web service.
I used the following code to covert the image:
private void photoChooserTask_Completed(object sender, PhotoResult e)
{
BitmapImage image = new BitmapImage();
image.SetSource(e.ChosenPhoto);
this.imageTribute.Source = image;
byte[] bytearray = null;
using (MemoryStream ms = new MemoryStream())
{
if (imageTribute.Source == null)
{
}
else
{
WriteableBitmap wbitmp = new WriteableBitmap((BitmapImage)imageTribute.Source);
wbitmp.SaveJpeg(ms, 40, 40, 0, 82);
bytearray = ms.ToArray();
}
}
strimage = Convert.ToBase64String(bytearray);
}
So please if anyone knows about that, help me out. Thanx in advance.
EDIT
void uploadphoto()
{
WebClient webClient1 = new WebClient();
webClient1.DownloadStringCompleted += new DownloadStringCompletedEventHandler(webClient1_DownloadStringCompleted);
webClient1.DownloadStringAsync(new Uri("Web Service"));
}
void webClient1_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
var rootobject1 = JsonConvert.DeserializeObject<RootObject1>(e.Result);
int error = rootobject1.response.errorFlag;
string message = rootobject1.response.msg;
if (error == 0)
{
MessageBox.Show(message);
}
else
{
MessageBox.Show(message);
}
}
public class Response1
{
public int errorFlag { get; set; }
public string msg { get; set; }
public List<string> uploadedImageNames { get; set; }
}
public class RootObject1
{
public Response1 response { get; set; }
}
private void ImageUpload(object sender, RoutedEventArgs e)
{
//MessageBoxResult mb = MessageBox.Show("Select the mode of uploading the picture", "", MessageBoxButton.OKCancel);
Popup popup = new Popup();
photoSelection photo = new photoSelection();
popup.Child = photo;
popup.IsOpen = true;
photo.camera.Click += (s, args) =>
{
photoCameraCapture.Show();
popup.IsOpen = false;
};
photo.library.Click += (s, args) =>
{
photoChooserTask.Show();
popup.IsOpen = false;
};
}
EDIT
Here I uploaded the stack trace of my error. So please check and reply me.
A Target Invocation Exception error tells you that the application crashed while invoking a method which could be many things. The real error is in the InnerException.
Look at the InnerException property of the TargetInvocationException object. This will show you the stack trace and the actual error thrown.
Get your file into stream either from resource or from isolatedStorage
//getting file from resource
var resource = Application.GetResourceStream(new Uri("image.jpg", UriKind.Relative));
//get Stream Data
StreamReader streamReader = new StreamReader(resource.Stream);
//initializing bytearray to stream length
byte[] imageData = new byte[streamReader.Length];
//wriing from stream to imagdata
streamReader.Read(imageData, 0, imageData.Length);
streamReader.Close();
Use isolatedStorageFile to read from isolated storage
now you have your image data in imageData and to convert it into base64 use:
var baseString = Convert.ToBase64String(imageData);

uploading photo to a webservice with mvvmcross and mono touch

What I want to do is simply to upload a photo to a webservice using mono touch/mono droid and mvvmcross, hopefully in a way so I only have to write the code once for both android and IOS :)
My initial idea is to let the user pick an image (in android using an intent) get the path for the image. Then use MvxResourceLoader resourceLoader to open an stream from the path and then use restsharp for creating a post request with the stream.
However I already hit a wall, when the user picks an image the path is e.g. "/external/images/media/13". this path results in a file not found exception when using the MvxResourceLoader resourceLoader.
Any ideas to why I get the exception or is there an better way to achieve my goal?
This is how I ended up doinging it - thank you stuart and to all the links :)
public class PhotoService :IPhotoService, IMvxServiceConsumer<IMvxPictureChooserTask>,IMvxServiceConsumer<IAppSettings>
{
private const int MaxPixelDimension = 300;
private const int DefaultJpegQuality = 64;
public void ChoosePhotoForEventItem(string EventGalleryId, string ItemId)
{
this.GetService<IMvxPictureChooserTask>().ChoosePictureFromLibrary(
MaxPixelDimension,
DefaultJpegQuality,
delegate(Stream stream) { UploadImage(stream,EventGalleryId,ItemId); },
() => { /* cancel is ignored */ });
}
private void UploadImage(Stream stream, string EventGalleryId, string ItemId)
{
var settings = this.GetService<IAppSettings>();
string url = string.Format("{0}/EventGallery/image/{1}/{2}", settings.ServiceUrl, EventGalleryId, ItemId);
var uploadImageController = new UploadImageController(url);
uploadImageController.OnPhotoAvailableFromWebservice +=PhotoAvailableFromWebservice;
uploadImageController.UploadImage(stream,ItemId);
}
}
public class PhotoStreamEventArgs : EventArgs
{
public Stream PictureStream { get; set; }
public Action<string> OnSucessGettingPhotoFileName { get; set; }
public string URL { get; set; }
}
public class UploadImageController : BaseController, IMvxServiceConsumer<IMvxResourceLoader>, IMvxServiceConsumer<IErrorReporter>, IMvxServiceConsumer<IMvxSimpleFileStoreService>
{
public UploadImageController(string uri)
: base(uri)
{
}
public event EventHandler<PhotoStreamEventArgs> OnPhotoAvailableFromWebservice;
public void UploadImage(Stream stream, string name)
{
UploadImageStream(stream, name);
}
private void UploadImageStream(Stream obj, string name)
{
var request = new RestRequest(base.Uri, Method.POST);
request.AddFile("photo", ReadToEnd(obj), name + ".jpg", "image/pjpeg");
//calling server with restClient
var restClient = new RestClient();
try
{
this.ReportError("Billedet overføres", ErrorEventType.Warning);
restClient.ExecuteAsync(request, (response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
//upload successfull
this.ReportError("Billedet blev overført", ErrorEventType.Warning);
if (OnPhotoAvailableFromWebservice != null)
{
this.OnPhotoAvailableFromWebservice(this, new PhotoStreamEventArgs() { URL = base.Uri });
}
}
else
{
//error ocured during upload
this.ReportError("Billedet kunne ikke overføres \n" + response.StatusDescription, ErrorEventType.Warning);
}
});
}
catch (Exception e)
{
this.ReportError("Upload completed succesfully...", ErrorEventType.Warning);
if (OnPhotoAvailableFromWebservice != null)
{
this.OnPhotoAvailableFromWebservice(this, new PhotoStreamEventArgs() { URL = url });
}
}
}
//method for converting stream to byte[]
public byte[] ReadToEnd(System.IO.Stream stream)
{
long originalPosition = stream.Position;
stream.Position = 0;
try
{
byte[] readBuffer = new byte[4096];
int totalBytesRead = 0;
int bytesRead;
while ((bytesRead = stream.Read(readBuffer, totalBytesRead, readBuffer.Length - totalBytesRead)) > 0)
{
totalBytesRead += bytesRead;
if (totalBytesRead == readBuffer.Length)
{
int nextByte = stream.ReadByte();
if (nextByte != -1)
{
byte[] temp = new byte[readBuffer.Length * 2];
Buffer.BlockCopy(readBuffer, 0, temp, 0, readBuffer.Length);
Buffer.SetByte(temp, totalBytesRead, (byte)nextByte);
readBuffer = temp;
totalBytesRead++;
}
}
}
byte[] buffer = readBuffer;
if (readBuffer.Length != totalBytesRead)
{
buffer = new byte[totalBytesRead];
Buffer.BlockCopy(readBuffer, 0, buffer, 0, totalBytesRead);
}
return buffer;
}
finally
{
stream.Position = originalPosition;
}
}
}
Try:
Issues taking images and showing them with MvvmCross on WP
Need an example of take a Picture with MonoDroid and MVVMCross
https://github.com/Redth/WshLst/ - uses Xam.Mobile for it's picture taking

Resources