i need to send three images at once to server, currently i can send one image by following code(PictureId). If i need to send three images say Picture1Id, Picture2Id, Picture3Id how can set in (protected Void doInBackground(Void... params) {})
// IMAGE UPLOAD ///////////
final ProgressDialog progress = new ProgressDialog(NBCompetitorTracking_Activity.this);
progress.setMessage("Uploading image, please wait...");
// If auto upload true upload picture:
if (new SessionManager(NBCompetitorTracking_Activity.this).isAutoUpload()) {
// upload image
new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
progress.show();
}
#Override
protected Void doInBackground(Void... params) {
UploadImage.uploadImage(NB_CompetitorTracking.**PictureId**);
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
progress.dismiss();
}
};
}
// END: IMAGE UPLOAD ///////////
Start multiple Thread instances of the 'upload thread' with separate files to be uploaded.Purely upon java concept, You can write a Thread class that uploads a file. And initiate many instances(as much as the files) and start them all together.
Related
I have an asynchronous task in Android Studio, to send and receive data from a server as follows.
private class myTask extends AsyncTask<Void, Void, Integer> {
Exception excepccion;
protected void onPreExecute() {
super.onPreExecute();
Mensaje.mensajeConectandoseSicoy(actMetodoPago,getString(R.string.msg_conexion_sicoy));
}
#Override
protected Integer doInBackground(Void... params) {
try {
return new Servidor().guardarObtnerInfoServidorSicoy(ACCION_PAGAR_PEDIDO);
} catch (Exception e2) {
excepccion = e2;
return -1;
}
}
#Override
protected void onPostExecute(Integer respuesta) {
Mensaje.detenerMensajeConectandoseSicoy();
...
}
Where:
public static void mensajeConectandoseSicoy(Context context, String mensaje){
pd = new ProgressDialog(context);
pd.setMessage(mensaje);
pd.setCancelable(false);
Handler pdCanceller = new Handler();
pd.show();
}
public static void detenerMensajeConectandoseSicoy(){
if (pd.isShowing()){
pd.dismiss();
}
}
This process works very well until a user reported problems and discovered that their internet is of very poor quality.
When the task is running onPostExecute, that is, when the server has already responded, it is again executed onPreExecute, and this triggers a series of errors.
I solved it by putting a Boolean type flag variable, to avoid the problem.
My question is:
Is there a way to do that control in a better way?
I want to load four images in four imageview in android
I try this code and it is run vary good
but it is load one image>>>>>>>>
How can I do to load 4 images>> I think I need to use array but how??
public void onClick(View arg0) {
// TODO Auto-generated method stub
new LoadImage().execute("https://pbs.twimg.com/profile_images/630285593268752384/iD1MkFQ0.png");
}
});
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Loading Image ....");
pDialog.show();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream)new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if(image != null){
img.setImageBitmap(image);
b1.setImageBitmap(image);
pDialog.dismiss();
}else{
pDialog.dismiss();
Toast.makeText(MainActivity.this, "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}
Use one of the ready made libraries... they have async loading, resizing, loading into target to get bitmap... no need to reinvent the wheel (unless it's for study purposes). You can use Picasso, Glide, Fresco... you choose. There is plenty documentation available. Loading is done asynchronously. So you can send multiple requests with multiple urls.
Hi everyone i am facing problem in showing loading box on pressing send button using send_Schedule() function. I have the following code.
#Override
public void onClick(View arg0) {
pdialog.setCancelable(true);
pdialog.setMessage("Loading ....");
pdialog.show();
send_Schedule();
}
In send_Schedule() function i am putting delay of 3 secs like this in the following code. but dialog box always shows up after completion of loop.
send_Schedule(){
for(int i=0;i<100;i++){
Log.d("TAG",""+i)
try {
Thread.sleep(3000);
Log.e("----------------", "-----------------");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
pdialog.dismiss();
}
I want to show dialog box while sending data...
Try this..
private class YourTaskLoader extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(YourActivity.this);
progressDialog.setCancelable(false);
progressDialog.setMessage("Importing Messages...!");
progressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Write you back ground logic here
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDialog.dismiss();
super.onPostExecute(result);
}
}
Invoke like in your Activity
new YourTaskLoader().execute();
Check this more info AsyncTask
I've developed an application that takes content from the internet and shows it accordingly on the device's screen . The program works just fine , a little bit slow . It takes about 3-4 seconds to load and display the content . I would like to put my code that does all the work ( grabbing web content and displaying it) in a background thread . Also , I'd like to show a progress dialog .
public class Activity1 extends Activity
{
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new AsyncTask<Integer, Integer, Boolean>()
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
/*
* This is executed on UI thread before doInBackground(). It is
* the perfect place to show the progress dialog.
*/
progressDialog = ProgressDialog.show(Activity1.this, "",
"Loading...");
}
#Override
protected Boolean doInBackground(Integer... params)
{
if (params == null)
{
return false;
}
try
{
/*
* This is run on a background thread, so we can sleep here
* or do whatever we want without blocking UI thread. A more
* advanced use would download chunks of fixed size and call
* publishProgress();
*/
Thread.sleep(params[0]);
// HERE I'VE PUT ALL THE FUNCTIONS THAT WORK FOR ME
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
/*
* The task failed
*/
return false;
}
/*
* The task succeeded
*/
return true;
}
#Override
protected void onPostExecute(Boolean result)
{
progressDialog.dismiss();
/*
* Update here your view objects with content from download. It
* is save to dismiss dialogs, update views, etc., since we are
* working on UI thread.
*/
AlertDialog.Builder b = new AlertDialog.Builder(Activity1.this);
b.setTitle(android.R.string.dialog_alert_title);
if (result)
{
b.setMessage("Download succeeded");
}
else
{
b.setMessage("Download failed");
}
b.setPositiveButton(getString(android.R.string.ok),
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dlg, int arg1)
{
dlg.dismiss();
}
});
b.create().show();
}
}.execute(2000);
/* new Thread()
{
#Override
public void run()
{
// dismiss the progressdialog
progressDialog.dismiss();
}
}.start();
}*/
}
If I run the application with this code , I get this : download failed . On the other hand , if I keep the final thread , the app crashes , NullPointerException . I really don't know what to do anymore .
I would really appreaciate if you could give me an alternative to this code , not just some hints because I'm new to android and I really don't know much . Thanks.
UPDATE :
I don't want to display the progress of the download , I want to display the progress dialog until the app is ready to display the full content.
The best approach to do this is by using the AsyncTask class, as it will allow you to execute some background process and update the UI at the same time (in your case, it's a progress bar).
This is an example code:
ProgressDialog mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
DownloadFile downloadFile = new DownloadFile();
downloadFile.execute("the url to the file you want to download");
The AsyncTask will look like this:
private class DownloadFile extends AsyncTask<String, Integer, String>{
#Override
protected String doInBackground(String... url) {
int count;
try {
URL url = new URL(url[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
// this will be useful so that you can show a tipical 0-100% progress bar
int lenghtOfFile = conexion.getContentLength();
// downlod the file
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream("/sdcard/somewhere/nameofthefile.ext");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
The method above (doInBackground) runs always on a background thread. You shouldn't do any UI tasks there. On the other hand, the onProgressUpdate runs on the UI thread, so there you will change the progress bar:
#Override
public void onProgressUpdate(String... args){
// here you will have to update the progressbar
// with something like
mProgressDialog.setProgress(args[0]);
}
}
You will also want to override the onPostExecute method if you want to execute some code once the file has been downloaded completely.
You should create an inner class for AsyncTask like this :
private class YourTask extends AsyncTask<Context, Void, Void>
{
ProgressDialog dialog = new ProgressDialog(mContext);
protected void onPreExecute()
{
dialog.setMessage("loading..");
dialog.show();
}
protected Void doInBackground(Context... params)
{
// ...
return null;
}
protected void onPostExecute(final Void unused)
{
dialog.dismiss();
}
}
and in onCreate() put :
new YourTask().execute();
and for more detail you should check this once:
http://developer.android.com/reference/android/os/AsyncTask.html
When you use the new thread, your app crashes because the progress dialog is not initialized there
Inside your new thread use:
`progressDialog = ProgressDialog.show(Activity1.this, "","Loading...");
and about that alert dialog: Basically either params is null or the logic is throwing some exception. It's not returning true
so check the ddms logs and post them here.
`
I am working with Android 3.0 and 3.1.
I use the class AndroidHttpClient in my application and for the execute I use execute(HttpUriRequest).
I have a progress bar in the UI that I want to be updated while sending data.
Is there any way to get notifications from the AndroidHttpClient about the progress of the data sending (I guess it doesn't send the whole buffer in one shot)?
Thanks
To track the progress of data as it is sent to the server you have to wrap the underlying HTTP entity that is being sent. If you subclass HttpEntityWrapper and override writeTo() you can wrapper the OutputStream with a FilterOutputStream that is the stream being written to the server.
i think you need AsyncTask example , may be it will help you ::
private class xyz extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(tranning.this);
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please Wait...");
this.dialog.show();
// put your code which preload with processDialog
}
#Override
protected Void doInBackground(Void... arg0) {
// put you code here
return null;
}
#Override
protected void onPostExecute(final Void unused) {
//if (this.dialog.isShowing()) {
// this.dialog.dismiss();
//}
}
}
and use it in your main class ::
new xyz().execute();