进度对话框在我的 Activity 中不起作用

Progress Dialog not working in my Activity

我正在 android 中开发一个应用程序,当我点击按钮时,我的 ProgressDialog 没有显示在 activity 中。

我在 ASYNC Class 中嵌入了 ProgressDialog 因为我必须将数据发送到服务器。

所以这就是为什么我必须显示 Progress Dialog

这里是XML代码Activity

请帮助我,提前谢谢你。

<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>

这是 Activity

的 Class 文件
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);
}

}

附加到 sendMessage 的 "get()" 方法的目的是什么?

创建 SendMessage 构造函数并在其中初始化 ProgressDialog。另外,通过服务器在 onPostExecute

中获取结果 return

删除它并将字符串值传递给 SendMessage class 的执行方法。

您可以在 class 级别声明字符串 re 并在 onPostExecute 中调用 re,例如 re =s。 s 是 onPostExecute 参数。

我明白了你的问题使用此代码你的进度对话框将起作用。

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);
}
}

这是调用 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();



    }
});

不要在

中调用 get()
re = sendMessageTask.execute().get();

使用

re = sendMessageTask.execute()

并在 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);
}

当您使用get() 时,使用Async Task 没有任何意义。因为 get() 会阻塞 UI 线程。

不要使用 get() 而是使用带有回调的 AsyncTask 检查这个 AsyncTask with callback interface

答案归功于此 post

希望这对您有所帮助。 :)