Android ImageSwitcher图像到另一个活动

时间:2016-03-24 12:01:37

标签: java android android-activity imageswitcher

我正在做ImageSwitcher,它正在完美地尝试将ImageSwitcher图像发送到另一个活动.. ImageSwitcher工作完美但是点击按钮进入下一个活动后,错误:Views.java中的(imageview)中的空指针异常

MainEvent.java

///<reference path="../../../../../typings/tsd.d.ts"/>

import {Component, OnInit} from 'angular2/core'
import {Router} from 'angular2/router';
import {NgClass} from 'angular2/common';

import {ImageInterface} from './image.interface'
import {ImageService} from './image.service'
import {ImageModel as Image} from './image.model'

import {ImageComponent} from './image.component'

@Component({
    selector: 'create-images-component',
    templateUrl: './angular2/app/images/image-form.component.html',
    providers: [
        ImageService
    ],
    directives: [
        ErrorsComponent,
        NgClass,
    ] })

export class CreateImageComponent implements OnInit {

    public image:ImageInterface = new Image(); 
    public validationErrors;

    constructor(public service:ImageService,
                private _router:Router) {
    }

    /**
     * File input change event
     * @param event
     */
    onFileChange(event) {
        let file = event.target.files[0];
        if (!file) {
            return;
        }
        if ( this.isValidExtension(file) == false ) {
            swal('Invalid file format!', 'Invalid file Format. Only ' + ImageComponent.ALLOWED_EXTENSIONS.join(', ') + ' are allowed.', 'error');
            return false;
        }
        if (this.isValidFileSize(file) == false) {
            swal('Invalid file size!', 'Invalid file size. Max allowed is : ' + ImageComponent.ALLOWED_SIZE + ', your file is : ' + this.getFileSize(file) + ' Mb' , 'error');
            return;
        }
        console.log(file);

        let reader = new FileReader();
        reader.onload = (e) => {
            this.image.base64 = e.target.result;
        };
        reader.readAsDataURL(file);
    }

    /**
     * Check if file has valid extension
     * @param file
     */
    private isValidExtension(file:File):boolean {
        let allowedExtensions = ImageComponent.ALLOWED_EXTENSIONS;
        let extension = file.name.split('.').pop();
        return allowedExtensions.indexOf(extension) !== -1
    }

    /**
     * Check file size
     * @param file
     * @returns {boolean}
     */
    private isValidFileSize(file) {
        let size = this.getFileSize(file);
        return size < ImageComponent.ALLOWED_SIZE;
    }

    /**
     * GEt file size in Mb
     * @param file
     * @returns {Number}
     */
    private getFileSize(file:File):Number {
        return file.size / 1024 / 1024;
    }

    /**
     * Clear selected image
     * @param ev
     */
    clearImage(ev) {
        ev.preventDefault();
        this.image.base64 = ''
    }

    /**
     * Return if image exists
     * @returns {boolean}
     */
    fileExists() {
        return this.image.base64 && (typeof this.image.base64 !== 'undefined')
    }

    /**
     * Create new image
     */
    onSubmit(form) {
        return this.service.httpPost(this.image)
            .subscribe(
            (res) => {
                if (res.data.errors) {
                    this.validationErrors = res.data.errors;
                }
                if (res.status == "success") {
                    this.successMessage = res.message;
                    swal("Good Job", res.message, "success");
                    this.validationErrors = [];
                } else {
                    this.errorMessage = res.message;
                }
            },
            (error) =>  this.errorMessage = <any>error);
    }

    onCancel() {
        return this._router.navigate(['Images']);
    }

    get diagnostic() {
        return JSON.stringify(this.image);
    }

}

Views.java

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.ViewSwitcher;

import java.io.ByteArrayOutputStream;

public class MainEvent extends Activity {

private ImageSwitcher imageSwitcher;
Button btnNext,back,select,refresh;
ImageView imageView;

// Array of Image IDs to Show In ImageSwitcher
int imageIds[]={R.drawable.frame3,R.drawable.frame7,
 R.drawable.curtain,R.drawable.potraitimage
        };
int messageCount=imageIds.length;
// to keep current Index of ImageID array
int currentIndex=0;
Animation in,out;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main_event);

    // get The references
    btnNext=(Button)findViewById(R.id.button2);
    back=(Button)findViewById(R.id.button);
    select=(Button)findViewById(R.id.select);
    refresh=(Button)findViewById(R.id.refresh);
    imageSwitcher = (ImageSwitcher) findViewById(R.id.imageSwitcher);

 // Set the ViewFactory of the ImageSwitcher that will create
 ImageView object   when asked
    imageSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
        public View makeView() {
            // TODO Auto-generated method stub
            // Create a new ImageView set it's properties
            imageView = new ImageView(getApplicationContext());
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            imageView.setImageResource(R.drawable.potraitimage);
            return imageView;
        }
    });

    // Declare the animations and initialize them
     in = AnimationUtils.loadAnimation(this,android.R.anim.slide_in_left);
   out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);

    // set the animation type to imageSwitcher
    imageSwitcher.setInAnimation(in);
    imageSwitcher.setOutAnimation(out);

    // ClickListener for NEXT button
    // When clicked on Button ImageSwitcher will switch between Images
   // The current Image will go OUT and next Image  will come 
  in with specified animation
    btnNext.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            // TODO Auto-generated method stub
            imageView.setImageResource(0);
            Log.d("index", String.valueOf(currentIndex));
            currentIndex++;
            Log.d("index", String.valueOf(currentIndex));
            // If index reaches maximum reset it
            if(currentIndex==messageCount)
                currentIndex=0;
            imageSwitcher.setImageResource(imageIds[currentIndex]);
        }
    });
    back.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // set the animation type to imageSwitcher

            // TODO Auto-generated method stub
            Log.d("index", String.valueOf(currentIndex));
            currentIndex--;
            Log.d("index", String.valueOf(currentIndex));
            // If index reaches maximum reset it
            if (currentIndex < 0)
                currentIndex = 2;
            imageSwitcher.setImageResource(imageIds[currentIndex]);
        }
    });
    select.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
        imageView.setImageResource(imageIds[currentIndex]);
    BitmapDrawable drawable = (BitmapDrawable) imageView.getDrawable();
            Bitmap bitmap = drawable.getBitmap();
            Intent in=new Intent(MainEvent.this,Camera.class);
          /*  in.putExtra("image",bitmap);*/
           ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();
            Bundle bu=new Bundle();
            bu.putByteArray("ImageByte",byteArray );
            in.putExtras(bu);
            startActivity(in);
        }
    });
    refresh.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onRestart();
        }
    });
}
@Override
protected void onRestart() {

    // TODO Auto-generated method stub
    super.onRestart();
    Intent i = new Intent(MainEvent.this, MainEvent.class);  //your class
    startActivity(i);
    finish();
}
}

我不知道如何将图像从imageswitcher传递到下一个活动..请帮助我们..

1 个答案:

答案 0 :(得分:1)

而不是传入图像的字节,你不能只传入它所在的索引(int)吗?

那会更有效率。

(以下链中的扩展答案) 在两个活动中共享数组。 关于静态属性的简单方法:

public class StaticModelManager {
     public static int imageIds[]; 
}

然后在应用程序的任何位置获取或设置它:

StaticModelManager.imageIds = {
     R.drawable.frame3,
     R.drawable.frame7,
     R.drawable.curtain,
     R.drawable.potraitimage
};

使用它们:

StaticModelManager.imageIds[currentIndex];

多个活动或片段可以轻松访问这一个实例。只需确保在不需要时将其清理干净或将其存放在内存中。