Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 当加载多张图片时,“活动”崩溃_Android_Android Activity_Android Imageview - Fatal编程技术网

Android 当加载多张图片时,“活动”崩溃

Android 当加载多张图片时,“活动”崩溃,android,android-activity,android-imageview,Android,Android Activity,Android Imageview,我已经开发了一个代码,它将动态创建一个ImageView并将其放置在屏幕上。但当我在模拟器上测试它时,会创建许多imageview,但在手机上测试时,只会创建一个imageview,第二次应用程序崩溃。这是密码。当我创建一个ImageView时,在我的手机上进行usb调试,然后单击按钮将其他图像添加到图像视图中。此时打开“图库”以选择其他图像,但当选择其他图像时,最后一个图像视图将被删除。我想当画廊打开时,活动又开始了。谁能告诉我哪里出了问题 package info.androidhive.s

我已经开发了一个代码,它将动态创建一个ImageView并将其放置在屏幕上。但当我在模拟器上测试它时,会创建许多imageview,但在手机上测试时,只会创建一个imageview,第二次应用程序崩溃。这是密码。当我创建一个ImageView时,在我的手机上进行usb调试,然后单击按钮将其他图像添加到图像视图中。此时打开“图库”以选择其他图像,但当选择其他图像时,最后一个图像视图将被删除。我想当画廊打开时,活动又开始了。谁能告诉我哪里出了问题

package info.androidhive.slidingmenu;

public class DragActivity extends Activity {

    RelativeLayout relativeLayout;
    ImageView imgView;
    private int nfontSize;
    Bitmap originalBitmap, image;
    int height1, width1;
    final int SELECT_IMAGE = 1;
    Uri selectedImage;
    Bitmap yourSelectedImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_drag);
        Intent intent = getIntent();
        int nImageId = intent.getIntExtra("drawableId", 0);
        imgView = (ImageView) findViewById(R.id.imageViewEdit);
        imgView.setBackgroundResource(nImageId);

        relativeLayout = (RelativeLayout) findViewById(R.id.drag_activity_layout);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        // Dimension x,y of device to create a scaled bitmap having similar
        // dimnstinos to screen size
        height1 = displayMetrics.heightPixels;
        width1 = displayMetrics.widthPixels;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case SELECT_IMAGE:
            if (resultCode == RESULT_OK) {
                selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filepath = cursor.getString(columnIndex);
                cursor.close();
                yourSelectedImage = BitmapFactory.decodeFile(filepath);
                if (yourSelectedImage != null) {
                    final DragImageView dynamicImgView = new DragImageView(
                            getApplicationContext(), yourSelectedImage);
                    final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.WRAP_CONTENT,
                            RelativeLayout.LayoutParams.WRAP_CONTENT);
                    dynamicImgView.setLayoutParams(params);
                    relativeLayout.addView(dynamicImgView);
                }
            }
            break;

        default:
            break;
        }
    }
    void saveImage(Bitmap bmpImg) {
        String RootDir = Environment.getExternalStorageDirectory() + File.separator + AppConstant.SavedFolderName;
        File myDir = new File(RootDir);
        myDir.mkdirs();
        Random generator = new Random();
        int n = 10000;
        n = generator.nextInt(n);
        String fname = "Invite-"+ n + ".jpg";
        File file = new File(myDir,fname);
        if(file.exists())file.delete();
        try{
            FileOutputStream out = new FileOutputStream(file);
            Toast.makeText(DragActivity.this,
                    "Image saved to folder", Toast.LENGTH_LONG)
                    .show();
            bmpImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
        }catch(Exception e){
            e.printStackTrace();
        }

    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // TODO Auto-generated method stub
        switch (item.getItemId()) {
        case R.id.action_addText:
            final Dialog alertDialog = new Dialog(this);
            alertDialog.setContentView(R.layout.custom_alert_dialog);
            alertDialog.setTitle("Add Text");

            String[] colors = { "RED", "GREEN", "BLUE", "BLACK", "WHITE",
                    "YELLOW", "CYAN" };
            String[] fonts = { "Wedding", "Birthday", "Events", "Business" };
            // set custom dialog components
            final EditText etUserTxt = (EditText) alertDialog
                    .findViewById(R.id.editText_userTxt);
            final TextView tvFontSize = (TextView) alertDialog
                    .findViewById(R.id.textView_fontsize);
            final TextView tvErrorMsg = (TextView) alertDialog
                    .findViewById(R.id.textView_errorTxt);

            Button btnOk = (Button) alertDialog.findViewById(R.id.button_ok);
            Button btnCancel = (Button) alertDialog
                    .findViewById(R.id.button_cancel);
            final Spinner colorSpinner = (Spinner) alertDialog
                    .findViewById(R.id.spinnerColor);
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, colors);
            colorSpinner.setAdapter(adapter);
            final Spinner fontFaceSpinner = (Spinner) alertDialog
                    .findViewById(R.id.spinnerFontFace);
            ArrayAdapter<String> adapterFont = new ArrayAdapter<String>(this,
                    android.R.layout.simple_spinner_item, fonts);
            fontFaceSpinner.setAdapter(adapterFont);

            SeekBar seekBar_fontSize = (SeekBar) alertDialog
                    .findViewById(R.id.seekBar1);
            nfontSize = 20;

            fontFaceSpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                @Override
                public void onItemSelected(AdapterView<?> parent, View view,
                        int position, long id) {
                    // TODO Auto-generated method stub
                    Typeface tf;
                    switch (position) {
                    case 0:
                        tf = Typeface.createFromAsset(getAssets(), "fonts/AnkeCalligraph.TTF");
                        tvFontSize.setTypeface(tf);
                        break;
                    case 1:
                        tf = Typeface.createFromAsset(getAssets(), "fonts/LucidaBrightRegular.ttf");
                        tvFontSize.setTypeface(tf);
                        break;
                    case 2:
                        tf = Typeface.createFromAsset(getAssets(), "fonts/Subway.ttf");
                        tvFontSize.setTypeface(tf);
                        break;
                    case 3:
                        tf = Typeface.createFromAsset(getAssets(), "fonts/timesbi.ttf");
                        tvFontSize.setTypeface(tf);
                        break;
                    default:
                        tf = Typeface.createFromAsset(getAssets(), "fonts/LucidaBrightRegular.ttf");
                        tvFontSize.setTypeface(tf);
                        break;
                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> parent) {
                    // TODO Auto-generated method stub

                }
            });
            seekBar_fontSize
                    .setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

                        @Override
                        public void onStopTrackingTouch(SeekBar seekBar) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onStartTrackingTouch(SeekBar seekBar) {
                            // TODO Auto-generated method stub

                        }

                        @Override
                        public void onProgressChanged(SeekBar seekBar,
                                int progress, boolean fromUser) {
                            // TODO Auto-generated method stub

                            tvFontSize.setTextSize(progress);
                            nfontSize = progress;
                        }
                    });

            btnCancel.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    alertDialog.dismiss();
                }
            });

            btnOk.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    String userTxt = etUserTxt.getText().toString();
                    int colorId = colorSpinner.getSelectedItemPosition();
                    int fontId = fontFaceSpinner.getSelectedItemPosition();
                    final DragView textView = new DragView(
                            getApplicationContext());
                    textView.setText(userTxt);
                    textView.setTextSize(nfontSize);
                    switch (colorId) {
                    case 0:
                        textView.setTextColor(Color.RED);
                        break;
                    case 1:
                        textView.setTextColor(Color.GREEN);
                        break;
                    case 2:
                        textView.setTextColor(Color.BLUE);
                        break;
                    case 3:
                        textView.setTextColor(Color.BLACK);
                        break;
                    case 4:
                        textView.setTextColor(Color.WHITE);
                        break;
                    case 5:
                        textView.setTextColor(Color.YELLOW);
                        break;
                    case 6:
                        textView.setTextColor(Color.CYAN);
                        break;
                    default:
                        break;
                    }
                    Typeface tf;
                    switch (fontId) {
                    case 0:
                        tf = Typeface.createFromAsset(getAssets(), "fonts/AnkeCalligraph.TTF");
                        textView.setTypeface(tf);
                        break;
                    case 1:
                        tf = Typeface.createFromAsset(getAssets(), "fonts/LucidaBrightRegular.ttf");
                        textView.setTypeface(tf);
                        break;
                    case 2:
                        tf = Typeface.createFromAsset(getAssets(), "fonts/Subway.ttf");
                        textView.setTypeface(tf);
                        break;
                    case 3:
                        tf = Typeface.createFromAsset(getAssets(), "fonts/timesbi.ttf");
                        textView.setTypeface(tf);
                        break;
                    default:
                        tf = Typeface.createFromAsset(getAssets(), "fonts/LucidaBrightRegular.ttf");
                        textView.setTypeface(tf);
                        break;
                    }
                    final RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
                            RelativeLayout.LayoutParams.WRAP_CONTENT,
                            RelativeLayout.LayoutParams.WRAP_CONTENT);

                    textView.setLayoutParams(params);
                    relativeLayout.addView(textView, params);
                    if (userTxt.isEmpty()) {
                        tvErrorMsg.setText("Please enter the text");
                        tvErrorMsg.setTextColor(Color.RED);
                        tvErrorMsg.setTextSize(20);
                    } else {
                        alertDialog.dismiss();
                    }
                }

            });

            alertDialog.show();
            return true;
        case R.id.action_savePicture:

            View v = findViewById(R.id.drag_activity_layout);
            v.setDrawingCacheEnabled(true);
            Bitmap b = v.getDrawingCache();

            saveImage(b);

            return true;
        case R.id.action_addImage:
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(
                    Intent.createChooser(intent, "Select Picture"),
                    SELECT_IMAGE);

            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    public static int getFilesCount(File file) {

        int count = 0;
        if(file != null){
            Log.d("File Check","File is not empty");
        File[] files = file.listFiles();

        for (File f : files)
            if (f.isDirectory())
                count += getFilesCount(f);
            else
                count++;
        }
        else{
            Log.d("File Check","File is not empty");
            return 0;}
        return count;
    }

}
package info.androidhive.slidingmenu;
公共类DragActivity扩展了活动{
相对的相对的;
ImageView-imgView;
私人信息量;
位图原图,图像;
内部高度1,宽度1;
最终整数选择_图像=1;
Uri选择图像;
位图您选择的图像;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
//TODO自动生成的方法存根
super.onCreate(savedInstanceState);
setContentView(R.layout.activity\u拖动);
Intent=getIntent();
int-nImageId=intent.getIntExtra(“drawableId”,0);
imgView=(ImageView)findViewById(R.id.imageViewEdit);
imgView.setBackgroundResource(nImageId);
relativeLayout=(relativeLayout)findViewById(R.id.drag\u活动\u布局);
DisplayMetrics DisplayMetrics=新的DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
//设备的尺寸x,y,用于创建具有类似尺寸的缩放位图
//与屏幕大小的关系
height1=displayMetrics.heightPixels;
宽度1=displayMetrics.widthPixels;
}
@凌驾
受保护的void onActivityResult(int请求代码、int结果代码、意图数据){
//TODO自动生成的方法存根
super.onActivityResult(请求代码、结果代码、数据);
开关(请求代码){
案例选择图片:
if(resultCode==RESULT\u OK){
选择edimage=data.getData();
字符串[]filePathColumn={MediaStore.Images.Media.DATA};
Cursor Cursor=getContentResolver().query(selectedImage,
filePathColumn,null,null,null);
cursor.moveToFirst();
int columnIndex=cursor.getColumnIndex(filePathColumn[0]);
String filepath=cursor.getString(columnIndex);
cursor.close();
您选择的edimage=BitmapFactory.decodeFile(文件路径);
如果(您选择的图像!=null){
最终DragImageView dynamicmgview=新的DragImageView(
getApplicationContext(),您选择的是图像);
最终RelativeLayout.LayoutParams参数=新的RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_内容,
RelativeLayout.LayoutParams.WRAP_内容);
dynamicImgView.setLayoutParams(参数);
relativeLayout.addView(dynamicImgView);
}
}
打破
违约:
打破
}
}
无效保存图像(位图bmpImg){
字符串RootDir=Environment.getExternalStorageDirectory()+File.separator+AppConstant.SavedFolderName;
File myDir=新文件(RootDir);
myDir.mkdirs();
随机生成器=新随机();
int n=10000;
n=发电机。下一个(n);
String fname=“Invite-”+n+“.jpg”;
File File=新文件(myDir,fname);
如果(file.exists())file.delete();
试一试{
FileOutputStream out=新的FileOutputStream(文件);
Toast.makeText(DragActivity.this,
“图像保存到文件夹”,Toast.LENGTH\u LONG)
.show();
bmpImg.compress(位图.CompressFormat.JPEG,90,out);
out.flush();
out.close();
}捕获(例外e){
e、 printStackTrace();
}
}
@凌驾
公共布尔值onOptionsItemSelected(菜单项项){
//TODO自动生成的方法存根
开关(item.getItemId()){
案例R.id.action_addText:
最终对话框alertDialog=新对话框(本);
alertDialog.setContentView(R.layout.custom\u alert\u对话框);
alertDialog.setTitle(“添加文本”);
字符串[]颜色={“红色”、“绿色”、“蓝色”、“黑色”、“白色”,
“黄色”、“青色”};
字符串[]字体={“婚礼”、“生日”、“活动”、“业务”};
//设置自定义对话框组件
最终EditText etUserTxt=(EditText)警报对话框
.findViewById(R.id.editText\u userTxt);
最终文本视图tvFontSize=(文本视图)警报对话框
.findViewById(R.id.textView\u fontsize);
最终文本视图tvErrorMsg=(文本视图)警报对话框
.findViewById(R.id.textView\u errorTxt);
按钮btnOk=(按钮)alertDialog.findViewById(R.id.Button\u ok);
按钮btnCancel=(按钮)警报对话框
.findViewById(R.id.按钮\取消);
最终微调器颜色微调器=(微调器)警报对话框
.findviewbyd(R.id.spinnerColor);
ArrayAdapter=新的ArrayAdapter(此,
android.R.layout.simple\u微调器(项目、颜色);
colorSpinner.setAdapter(适配器);
最终微调器fontFaceSpinner=(微调器)alertDialog
.findViewById(R.id.喷丝头正面);
ArrayAdapter adapterFont=新的ArrayAdapter(此,
android.R.layout.simple\u微调器(项目、字体);
fontFaceSpinner.setAdapter(adapterFont);
SeekBar SeekBar_fontSize=(SeekBar)警报对话框
final DragImageView dynamicImgView = new DragImageView(
                        getApplicationContext(), yourSelectedImage);
relativeLayout.addView(dynamicImgView);