0

I am developing an application in android and my ProgressDialog is not shown in the activity when I tap on button.

I have embedded ProgressDialog in ASYNC Class because I have to send the data to server.

SO thats why I have to show the Progress Dialog

Here is the XML code of the Activity

Plz Help me out and Thank You in advance.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
android:background="@drawable/background"
tools:context="com.example.ali.cottondiseasedetection.TakeImage">
<TextView android:text="Please Choose an image From the Gallery or Capture a Photo."
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="5dp"
    android:textColor="#ff0d5122"
    android:layout_centerHorizontal="true"
    android:textSize="20dp"
    android:textStyle="bold"
    />
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_marginTop="60dp"
    android:orientation="vertical" >
    <ImageButton
        android:id="@+id/button1"
        android:layout_width="140dp"
        android:layout_height="120dp"
        android:text="From Gallery"
        android:background="@drawable/imagegallery"
        />
</LinearLayout>
<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="45dp"
    android:layout_alignParentRight="true"
    android:orientation="vertical" >
    <ImageButton
        android:id="@+id/button"
        android:layout_width="140dp"
        android:layout_height="140dp"
        android:text="From Camera"
        android:layout_centerHorizontal="false"
        android:background="@drawable/vintagecamera"
    />
</LinearLayout>
<TableLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerInParent="true"

    >
    <TableRow android:layout_marginTop="150dp">
        <ImageView
            android:id="@id/setImage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
        />
    </TableRow>
</TableLayout>
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true">
    <Button
        android:id="@+id/process"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:text="Process Image"
    />
</LinearLayout>

Here is the Class file of the Activity

package com.example.ali.cottondiseasedetection;

public class TakeImage extends ActionBarActivity {
String message2;
private ProgressDialog pd;
Context context;
byte[] image;
private Bitmap bitmap;
private ImageButton camera;
private ImageButton gallery;
ImageView targetImage;
NotificationManager nm;
Uri fileUri = null;
private Button process;
private static int TAKE_PICTURE = 1;
private static int FROM_GALLERY = 2;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_take_image);
    context=this;
    //Notification Code
    nm=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    //
    camera=(ImageButton)findViewById(R.id.button);
    gallery=(ImageButton)findViewById(R.id.button1);
    targetImage=(ImageView)findViewById(R.id.setImage);
    process=(Button)findViewById(R.id.process);
    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
            File photo = new File(Environment.getExternalStorageDirectory(),  "Pic.jpg");
            intent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(photo));
            fileUri = Uri.fromFile(photo);
            startActivityForResult(intent, TAKE_PICTURE);
        }
    });
    gallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, FROM_GALLERY);
        }
    });
    process.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            boolean temp=true;
                bitmap = BitmapFactory.decodeResource(getResources(), R.id.setImage);
                BitmapDrawable bd = (BitmapDrawable) targetImage.getDrawable();
                bitmap = bd.getBitmap();
                ByteArrayOutputStream stream = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
                image = stream.toByteArray();
                int l = image.length;
                if (l == 0) {
                    //Toast.makeText(getApplicationContext(),"0",Toast.LENGTH_LONG).show();
                } else {

                }
                SendMessage sendMessageTask = new SendMessage();
                String re = null;
                try {
                    re = sendMessageTask.execute().get();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (ExecutionException e) {
                    e.printStackTrace();
                }
                //Toast.makeText(getApplicationContext(),"Processing",Toast.LENGTH_LONG).show();

                Intent i = new Intent(getApplicationContext(), Response.class);
                i.putExtra("result", re);
                i.putExtra("image", image);
                startActivity(i);

        }
    });
}
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // TODO Auto-generated method stub
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == TAKE_PICTURE && resultCode == Activity.RESULT_OK) {
        Uri selectedImage = fileUri;
        getContentResolver().notifyChange(selectedImage, null);
        ContentResolver cr = getContentResolver();
        try {
            bitmap = android.provider.MediaStore.Images.Media.getBitmap(cr, selectedImage);
            targetImage.setImageBitmap(bitmap);
            //Toast.makeText(this, selectedImage.toString(),Toast.LENGTH_LONG).show();
        } catch (Exception e) {
            //Toast.makeText(this, "Failed to load", Toast.LENGTH_SHORT)
                    //.show();
            Log.e("Camera", e.toString());
        }
    }
    else if (requestCode == FROM_GALLERY && resultCode == RESULT_OK) {
        Uri targetUri = data.getData();
        try {
            bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(targetUri));
            targetImage.setImageBitmap(bitmap);
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
private class SendMessage extends AsyncTask<String, String, String> {
    @Override
    protected void onPreExecute(){
        super.onPreExecute();
        pd = new ProgressDialog(TakeImage.this);
        pd.setMessage("Please wait.");
        pd.setIndeterminate(false);
        pd.setCancelable(true);
        pd.show();
    }
    protected String doInBackground(String... params) {
        Socket clientSocket = null;
        try {
            clientSocket = new Socket("192.168.1.8", 4001);
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert clientSocket != null;
        DataOutputStream outToServer = null;
        try {
            outToServer = new DataOutputStream(clientSocket.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }

        // sentence = "Mohammad";
        assert outToServer != null;
        try {
            outToServer.writeInt(image.length);
            outToServer.write(image,0,image.length);
        } catch (IOException e) {
            e.printStackTrace();
        }
        DataInputStream input=null;
        try {
            input=new DataInputStream(clientSocket.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        assert input != null;
        try {
            message2=input.readUTF();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            clientSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return message2;
    }
    @Override
    protected void onPostExecute(String s) {
        pd.dismiss();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_take_image, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

}

Aman Jham
  • 478
  • 6
  • 18
ALI Sajjad Rizvi
  • 185
  • 5
  • 20

4 Answers4

1

Don't call get() in

re = sendMessageTask.execute().get();

use

re = sendMessageTask.execute()

And get Result callback in postExecute.

@Override
protected void onPostExecute(String s) {
    pd.dismiss();
    Intent i = new Intent(getApplicationContext(), Response.class);
    i.putExtra("result", s);
    i.putExtra("image", image);
    startActivity(i);
}
Dharmaraj
  • 1,256
  • 13
  • 12
0

Whats the purpose of "get()" method appended to the sendMessage?

Create SendMessage Constructor and initialize ProgressDialog in it. Also, get the results return by server in onPostExecute

Remove that and pass the String values to the execute method of SendMessage class.

You can declare the String re at class level and call the re in onPostExecute e.g re =s. s is the onPostExecute parameter.

Want2bExpert
  • 527
  • 4
  • 11
0

I got it your isssue Use this code your progress dialog will work.

private class SendMessage extends AsyncTask<String, String, String> {

private ProgressDialog pd = new ProgressDialog(TakeImage.this);
@Override
protected void onPreExecute(){
    super.onPreExecute();

    pd.setMessage("Please wait.");
    pd.setIndeterminate(false);
    pd.setCancelable(true);
    pd.show();
}
protected String doInBackground(String... params) {
    Socket clientSocket = null;
    try {
        clientSocket = new Socket("192.168.1.8", 4001);
    } catch (IOException e) {
        e.printStackTrace();
    }
    assert clientSocket != null;
    DataOutputStream outToServer = null;
    try {
        outToServer = new DataOutputStream(clientSocket.getOutputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }

    // sentence = "Mohammad";
    assert outToServer != null;
    try {
        outToServer.writeInt(image.length);
        outToServer.write(image,0,image.length);
    } catch (IOException e) {
        e.printStackTrace();
    }
    DataInputStream input=null;
    try {
        input=new DataInputStream(clientSocket.getInputStream());
    } catch (IOException e) {
        e.printStackTrace();
    }
    assert input != null;
    try {
        message2=input.readUTF();
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        clientSocket.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return message2;
}
@Override
protected void onPostExecute(String s) {
        if(pd != null && pd.isShowing()){
            pd.dismiss();
            pd  = null;
        }
      Intent i = new Intent(getApplicationContext(), Response.class);
            i.putExtra("result", re);
            i.putExtra("image", image);
            startActivity(i);
}
}

And this is the correct way to calling the AsyncTask new SendMessage().execute()

  process.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        boolean temp=true;
            bitmap = BitmapFactory.decodeResource(getResources(), R.id.setImage);
            BitmapDrawable bd = (BitmapDrawable) targetImage.getDrawable();
            bitmap = bd.getBitmap();
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
            image = stream.toByteArray();
            int l = image.length;
            if (l == 0) {
                //Toast.makeText(getApplicationContext(),"0",Toast.LENGTH_LONG).show();
            } else {

            }
            try {
                new SendMessage().execute();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (ExecutionException e) {
                e.printStackTrace();
            }
            //Toast.makeText(getApplicationContext(),"Processing",Toast.LENGTH_LONG).show();



    }
});
Aman Jham
  • 478
  • 6
  • 18
0

When you are using get(), using Async Task doesn't make any sense. Because get() will block the UI Thread.

Don't use get() instead use AsyncTask with Call Back check this AsyncTask with callback interface

Answer credit goes to this post.

Hope this helps. :)

Community
  • 1
  • 1
Ye Min Htut
  • 2,904
  • 15
  • 28