如何使用非活动类在警报对话框中显示图像

时间:2019-03-16 09:04:02

标签: android android-recyclerview android-alertdialog recycler-adapter onactivityresult

因此,在我的应用程序中,我有一个RecyclerView,并且每张卡上都有一个编辑按钮,并且该编辑按钮调用一个自定义警报对话框,该对话框具有三个editTexts和一个edit image按钮以及一个图像视图以显示所选图像,并且编辑按钮由非活动类 RecyclerViewAdapter 控制 这是 RecyclerViewAdapter 类:

   package com.hitham.miscarros.UI;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.hitham.miscarros.Activities.DetailsActivity;
import com.hitham.miscarros.Activities.IntentHelper;
import com.hitham.miscarros.Activities.IntentHelperActivity;
import com.hitham.miscarros.Activities.ListActivity;
import com.hitham.miscarros.Activities.MainActivity;
import com.hitham.miscarros.Data.DatabaseHandler;
import com.hitham.miscarros.Model.Cars;
import com.hitham.miscarros.R;

import java.net.URI;
import java.util.List;

import static android.app.Activity.RESULT_OK;
import static android.support.v4.app.ActivityCompat.startActivityForResult;
import static android.support.v4.content.ContextCompat.startActivity;

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
    private Context context;
    private List<Cars> misCarros;
    private AlertDialog dialog;
    private AlertDialog.Builder alertBuilder;
    private static final int REQUEST_IMAGE_CAPTURE=1;
    public boolean clicked = false;
    public RecyclerViewAdapter(Context context, List<Cars> misCarros) {
        this.context = context;
        this.misCarros = misCarros;
    }
    @NonNull
    @Override
    public RecyclerViewAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_row,parent,false);
        return new ViewHolder(view,context);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerViewAdapter.ViewHolder holder, int position) {
        Cars carro = misCarros.get(position);
        Bitmap pic;
        if(carro.getCarImage() != null) {
            pic = BitmapFactory.decodeFile(carro.getCarImage());
            holder.ImagenaDelCarro.setImageBitmap(pic); }
        holder.ManufacturarDelCarro.setText(carro.getCarManuf());
        holder.NombreDelCarro.setText(carro.getCarName());
        holder.ModelDelCarro.setText(carro.getCarModel());
    }

    @Override
    public int getItemCount() {
        return misCarros.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        public TextView ManufacturarDelCarro;
        public TextView NombreDelCarro;
        public TextView ModelDelCarro;
        public ImageView ImagenaDelCarro;
        public Button editarElCarro;
        public Button deletarElCarro;
        public int id;
        public ViewHolder(View view, final Context ctx) {
            super(view);
            context = ctx;
            ManufacturarDelCarro = view.findViewById(R.id.carManuf);
            NombreDelCarro = view.findViewById(R.id.carName);
            ModelDelCarro = view.findViewById(R.id.carDOB);
            ImagenaDelCarro = view.findViewById(R.id.carImage);
            editarElCarro = view.findViewById(R.id.editCarID);
            deletarElCarro = view.findViewById(R.id.deleteCarID);
            editarElCarro.setOnClickListener(this);
            deletarElCarro.setOnClickListener(this);
            view.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //todo: go to next screen
                    int position = getAdapterPosition();
                    Cars car = misCarros.get(position);

                    Intent miIntento = new Intent(ctx, DetailsActivity.class);
                    miIntento.putExtra("name", car.getCarName());
                    miIntento.putExtra("model", car.getCarModel());
                    miIntento.putExtra("manuf", car.getCarManuf());
                    miIntento.putExtra("id", car.getCarID());
                    miIntento.putExtra("imagePath",car.getCarImage());
                    ctx.startActivity(miIntento);

                }
            });

        }
        @Override
        public void onClick(View v) {
            switch (v.getId())
            {
                case R.id.editCarID:
                    Cars unCarro = misCarros.get(getAdapterPosition());
                    editCar(unCarro);
                    break;
                case R.id.deleteCarID:
                    int position = getAdapterPosition();
                    unCarro = misCarros.get(position);
                    deleteCar(unCarro.getCarID());
                    break;
            }

        }
        public void deleteCar (final int id)
        {
            final DatabaseHandler db = new DatabaseHandler(context);
            alertBuilder = new AlertDialog.Builder(context);
            alertBuilder.setTitle(R.string.confTitle);
           // alertBuilder.setIcon(android.R.drawable.alert_dark_frame);
            alertBuilder.setMessage(R.string.confMsg);
            alertBuilder.setNegativeButton(R.string.noBu, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            alertBuilder.setPositiveButton(R.string.yesBu, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    db.deleteCars(id);
                    misCarros.remove(getAdapterPosition());
                    notifyItemRemoved(getAdapterPosition());
                    dialog.dismiss();
                    if (db.getCarsCount() <= 0)
                    {
                        context.startActivity(new Intent(context,MainActivity.class));
                        ((Activity)context).finish();
                    }
                }
            });
            dialog = alertBuilder.create();
            dialog.show();

        }
        public void editCar(final Cars car)
        {
            alertBuilder = new AlertDialog.Builder(context);
            LayoutInflater inflater = LayoutInflater.from(context);
            final View view = inflater.inflate(R.layout.new_car_popup,null);
            final EditText carName = view.findViewById(R.id.nCarName);
            final EditText carManuf = view.findViewById(R.id.nCarManuf);
            final EditText DOB = view.findViewById(R.id.nCarDOB);
            TextView editCarText = view.findViewById(R.id.textView);
            Button editImage = view.findViewById(R.id.addImageID);
            final ImageView carImage = view.findViewById(R.id.laImagenaPuta);
            final Button editCarButton = view.findViewById(R.id.addCarID);
            editImage.setText(R.string.editImageText);
            editCarButton.setText(R.string.editCarBu);
            editCarText.setText(R.string.editCarText);
            carManuf.setHint(R.string.manufHint);
            carName.setHint(R.string.nameHint);
            DOB.setHint(R.string.DOBHint);
            final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
            alertBuilder.setView(view);
            dialog = alertBuilder.create();
            dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            dialog.show();
            SharedPreferences.Editor editor = sharedPreferences.edit();
            if(!clicked)
                editor.putString("imagePath",null);
            editor.apply();
            long time = SystemClock.currentThreadTimeMillis();
            editImage.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    try{
                        if (ActivityCompat.checkSelfPermission(context,Manifest.permission.READ_EXTERNAL_STORAGE)
                                != PackageManager.PERMISSION_GRANTED){
                            ActivityCompat.requestPermissions((Activity)context, new String[]{
                                            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
                                    REQUEST_IMAGE_CAPTURE);
                        }else {
                            clicked = true;
                            Intent helperIntent = new Intent(context,IntentHelperActivity.class);
                            startActivity(context,helperIntent,null);
                            new Handler().postDelayed(new Runnable() {

                                @Override
                                public void run() {
                                    Bitmap image = BitmapFactory.decodeFile(sharedPreferences.getString("imagePath", null));
                                    carImage.setImageBitmap(image);
                                }
                            }, 1690);
                        }
                    }catch (Exception e)
                    {
                        e.printStackTrace();
                    }
                }
            });
                    //  alertBuilder.setIcon(android.R.drawable.alert_dark_frame);
            //String imagePath ;
            //editCarButton.setText(imagePath);
            editCarButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    final String imagePath = sharedPreferences.getString("imagePath", null);
                    DatabaseHandler db = new DatabaseHandler(context);
                    if(!carManuf.getText().toString().isEmpty())
                        car.setCarManuf(carManuf.getText().toString());
//                    else{
//                        Cars miCarro = misCarros.get(getAdapterPosition());
//                        car.setCarManuf(miCarro.getCarName());
//                    }
                    if(!carName.getText().toString().isEmpty())
                        car.setCarName(carName.getText().toString());
//                    else{
//                        Cars miCarro = misCarros.get(getAdapterPosition());
//                        car.setCarName(miCarro.getCarName());
//                    }
                    if(!DOB.getText().toString().isEmpty())
                        car.setCarModel(DOB.getText().toString());
//                    else{
//                        Cars miCarro = misCarros.get(getAdapterPosition());
//                        car.setCarModel(miCarro.getCarName());
//                    }
                    if(imagePath != null)
                        car.setCarImage(imagePath);
//                    if (!carName.getText().toString().isEmpty() && !carManuf.getText().toString().isEmpty()
//                            && !DOB.getText().toString().isEmpty()) {
                   // if(imagePath != null )
                     //   car.setCarImage(imagePath);
                        db.updateCars(car);
                        notifyItemChanged(getAdapterPosition(), car);
                    //}
//                    else{
//                        Toast.makeText(context,R.string.enterSomething,Toast.LENGTH_LONG);
//                    }

                    dialog.dismiss();
                    Intent myIntent = new Intent(context,ListActivity.class);
                    context.startActivity(myIntent);
                    ((Activity)context).finish();
                    ((Activity) context).finish();

                }
            });

        }
    }
}

我已经尝试使用另一个活动 IntentHelperActivity 来帮助我调用startActivityForResult和onActivityResult方法来选择图像,这是类:

   package com.hitham.miscarros.Activities;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewParent;
import android.widget.ImageView;
import android.widget.Toast;

import com.hitham.miscarros.R;
import com.hitham.miscarros.UI.RecyclerViewAdapter;

public class IntentHelperActivity extends AppCompatActivity {
    private ImageView miImagen;
    private String imagePath = null;
    private Intent galleryIntent;
    private Bitmap image;

    public IntentHelperActivity() {
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_helper_activtiy);
        Bundle bundle = getIntent().getExtras();
        galleryIntent = new Intent(Intent.ACTION_PICK,MediaStore.Images
                .Media.EXTERNAL_CONTENT_URI);
        LayoutInflater inflater = LayoutInflater.from(this);
        View view = inflater.inflate(R.layout.new_car_popup,null);
        miImagen = view.findViewById(R.id.laImagenaPuta);
        startActivityForResult(galleryIntent,1);
    }

    @Override
    public void onBackPressed() {
        finish();
        super.onBackPressed();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode)
        {
            case 1:
                if (resultCode == RESULT_OK)
                {
                    Uri selectedImage = data.getData();
                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    Cursor miCursor = getContentResolver().query(selectedImage,filePathColumn,null,null,null);
                    miCursor.moveToFirst();
                    int columnIndex = miCursor.getColumnIndex(filePathColumn[0]);
                    String filePath = miCursor.getString(columnIndex);
                    miCursor.close();
                    imagePath = filePath;
                    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("imagePath",imagePath);
                    editor.apply();
                    finish();
                }
            break;
                default:
                finish();
        }
    }
}

IntentHelperActivity帮助我选择了图像并将其发送到上一类,但是导致了两个问题

  1. 选择图像时,我可以轻松地将其保存到数据库中,但无法在alertDialog的imageView中查看它
  2. 当我不选择图像时,只需按返回按钮,它将显示一个空白屏幕(intentHelperActivity) 所以有什么建议。

0 个答案:

没有答案