E / AndroidRuntime:致命异常:主要(单击按钮应用程序崩溃时)

时间:2018-12-02 07:35:01

标签: java android android-studio crash steganography


大家好,我的论文专案小组目前在使用Android Studio运行我们的android应用程序时遇到问题,概念是隐写术,我们正在使用https://github.com/guardianproject/PixelKnot/tree/version_2/PixelKnot/src/main/java/info/guardianproject/pixelknot的F5库


Here is our user interface and whenever clicking embed button, the app closes automatically

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.angel.filepicker, PID: 2972
java.lang.NullPointerException: Attempt to invoke virtual method 'void info.guardianproject.f5android.stego.StegoProcessor.addThread(info.guardianproject.f5android.stego.StegoProcessThread, boolean)' on a null object reference
    at com.example.angel.filepicker.EmbedFragment$3.onClick(EmbedFragment.java:162)
    at android.view.View.performClick(View.java:5637)
    at android.view.View$PerformClick.run(View.java:22429)
    at android.os.Handler.handleCallback(Handler.java:751)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:6119)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)


EmbedFragment.java代码

package com.example.angel.filepicker;
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import info.guardianproject.f5android.plugins.f5.Embed;
import info.guardianproject.f5android.stego.*;
import info.guardianproject.f5android.plugins.PluginNotificationListener;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import static android.app.Activity.RESULT_OK;
public class EmbedFragment extends Fragment {
    private static final String TAG = "EMbed";

    public EmbedFragment() {

    }

    private Activity a;

    public File finalFile;
    public File msgFile;

    public byte[] seed = new String("This is hopefully Temporary").getBytes();
    public String baseimage;
    public String secret_file;
    public Intent fileIntent;

    public static Activity act;
    public static Context cntx;

    public StegoProcessor stego_processor;
    //FOR FILE BUTTON

    public static final int FILE_PICKER_REQUEST_CODE = 1;
    Intent intent;

    Button btn_choose_image;
    ImageView image;
    TextView text;

    //FOR IMAGE BUTTON
    File photoFile = null;
    static final int CAPTURE_IMAGE_REQUEST = 2;
    static final int SELECT_FILE = 3;

    String mCurrentPhotoPath;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.embed_fragment, container, false);

        cntx = getActivity().getBaseContext();
        act = getActivity();


        //initialize and set intent type

        fileIntent = new Intent();

        fileIntent.setType("*/*");

        fileIntent.setAction(Intent.ACTION_GET_CONTENT);


        text = view.findViewById(R.id.textView2);

        //FOR FILE BUTTON
        Button pickButton = view.findViewById(R.id.pick_from_activity);
        pickButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                checkPermissionsAndOpenFilePicker();
                startActivityForResult(Intent.createChooser(fileIntent, "Select File"), FILE_PICKER_REQUEST_CODE);


            }
        });

        //FOR IMAGE BUTTON
        btn_choose_image = view.findViewById(R.id.btn_choose_image);
        image = view.findViewById(R.id.imageView2);

        btn_choose_image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                captureImage();
            }
        });


        final Button embedButton = (Button) view.findViewById(R.id.embedButton);
        embedButton.setOnClickListener(embedButtonListener);

        return view;


    }

    View.OnClickListener embedButtonListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

      if(baseimage !=null)

        {
            if ( secret_file != null) {

                //ImageSteganography Object instantiation
                Embed embed = new Embed(a,baseimage , secret_file, seed) {
                    @Override
                    public void run() {

                        super.run();
                    }
                };
                stego_processor.addThread(embed, true);
            }
        }
    }

    };



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        Log.e("onActivityResult", "requestCode " + requestCode + ", resultCode " + resultCode);


        if (requestCode == FILE_PICKER_REQUEST_CODE && resultCode==RESULT_OK && data != null && data.getData() != null) {


            Uri uri=data.getData();
            try{
                msgFile=new File(uri.getPath());//get the file
                secret_file = uri.getPath();
                //secretFile = getPathFromUri(getActivity(),uri);
                Toast.makeText(act.getBaseContext(), "Picked file: " + msgFile, Toast.LENGTH_LONG).show();
                //text.setText(textx);
            }catch(Exception e){}
            if(msgFile.length()==0){
                try{
                    msgFile=new File(getPathFromUri(getActivity(),uri));//get the file
//                    secretFile = getPathFromUri(getActivity(),uri);
                    Toast.makeText(act.getBaseContext(), "Picked file: " + msgFile, Toast.LENGTH_LONG).show();
                }catch(Exception e){
                    Log.e("Main","Unable to get file!");
                    e.printStackTrace();
                }
            }
        }

        if (requestCode == CAPTURE_IMAGE_REQUEST && resultCode == RESULT_OK) {
//            baseImage = photoFile.getAbsoluteFile();

            Bitmap myBitmap = BitmapFactory.decodeFile(photoFile.getAbsolutePath());

            image.setImageBitmap(myBitmap);

        }

        //PROBLEMA NITO IS YUNG PAG DISPLAY NG PIC YUNG SIZE NG PIC .
        // MAY METHOD NA RESIZIND PERO TSAKA NA CGURO PAG NALAGAY NA UI
        if (requestCode == SELECT_FILE && data != null && data.getData() != null) {
           // baseImage = getRealPathFromURI(getActivity(), data.getData());
            Uri uri=data.getData();

            try {
                // mengambil gambar dari Gallery

                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), data.getData());
                baseimage = uri.getPath();
                image.setImageBitmap(bitmap);
                text.setText(baseimage);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


    }
//    private String getRealPathFromURI(Context context, Uri contentUri) {
//        Cursor cursor = null;
//        try {
//            String[] proj = { MediaStore.Images.Media.DATA };
//            cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
//            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
//            cursor.moveToFirst();
//            return cursor.getString(column_index);
//        } catch (Exception e) {
//            Log.e(TAG, "getRealPathFromURI Exception : " + e.toString());
//            return "";
//        } finally {
//            if (cursor != null) {
//                cursor.close();
//            }
//        }
//    }
    public static String getPathFromUri(final Context context, final Uri uri) {//get path name from a uri object(source: web)

        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                if ("primary".equalsIgnoreCase(type)) {
                    return Environment.getExternalStorageDirectory() + "/" + split[1];
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(
                        Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

                return getDataColumn(context, contentUri, null, null);
            }
            // MediaProvider
            else if (isMediaDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];

                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if ("video".equals(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if ("audio".equals(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }

                final String selection = "_id=?";
                final String[] selectionArgs = new String[] {
                        split[1]
                };

                return getDataColumn(context, contentUri, selection, selectionArgs);
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {

            // Return the remote address
            if (isGooglePhotosUri(uri))
                return uri.getLastPathSegment();

            return getDataColumn(context, uri, null, null);
        }
        // File
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            return uri.getPath();
        }

        return null;
    }

    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = {
                column
        };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }


    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

//...................................................................................................................................
    //FOR IMAGE BUTTON
    private void captureImage() {
        image.setImageResource(0);
        final CharSequence[] items = {"Take Photo", "Choose from Library",
                "Cancel"};
//ITO YUNG CHOICE KUNG TAKE PHOTO OR SELECT IMAGE . KAPAG TAKE PHOTO DAPAT
// NASASAVE SA GALLERY PERO WALA AKO NAKITA SA GALLERY KO HAHAH FEELING KO MAS OKAY PAG DI NLNG NASSASAVE

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Add Photo!");
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (items[item].equals("Take Photo")) {

                    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    if (takePictureIntent.resolveActivity(getContext().getPackageManager()) != null) {
                        // Create the File where the photo should go
                        try {

                            photoFile = createImageFile();
                            displayMessage(getActivity().getBaseContext(), photoFile.getAbsolutePath());
                            Log.i("Stegrapp", photoFile.getAbsolutePath());

                            // Continue only if the File was successfully created
                            if (photoFile != null) {
                                Uri photoURI = FileProvider.getUriForFile(getActivity(),
                                        "com.example.angel.filepicker.fileprovider",
                                        photoFile);
                                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                                startActivityForResult(takePictureIntent, CAPTURE_IMAGE_REQUEST);
                            }
                        } catch (Exception ex) {
                            // Error occurred while creating the File
                            displayMessage(getActivity().getBaseContext(), ex.getMessage().toString());
                        }


                    } else {
                        displayMessage(getActivity().getBaseContext(), "Nullll");
                    }

                    //PROBLEMA NITO IS YUNG PAG DISPLAY NG PIC YUNG SIZE NG PIC .
                    // MAY METHOD NA RESIZIND PERO TSAKA NA CGURO PAG NALAGAY NA UI
                } else if (items[item].equals("Choose from Library")) {
                    intent = new Intent();
                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);
                    startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_FILE);
                } else if (items[item].equals("Cancel")) {
                    dialog.dismiss();
                }


            }

        });
        builder.show();
    }

//........................................................................................................


    //ITO YUNG PAG CREATE NG FILE NUNG IMAGE GALING CAMERA
    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getContext().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );

        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void displayMessage(Context context, String message)
    {
        Toast.makeText(context,message,Toast.LENGTH_LONG).show();
    }






    public static void show(final String toast){
        act.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(EmbedFragment.cntx,toast,Toast.LENGTH_LONG).show();
            }
        });
    }

}


MainActivity.java代码

package com.example.angel.filepicker;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends AppCompatActivity {
    private static int SPLASH_TIME_OUT = 4000;

    ImageView imageView;
    Toolbar toolbar;
    ViewPager viewPager;
    TabLayout tabLayout;
    FloatingActionButton shareButton;
    Button btn_choose_image;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        toolbar = findViewById(R.id.toolbar_id);
        viewPager = findViewById(R.id.viewPager_id);
        tabLayout = findViewById(R.id.tabLayout_id);
        shareButton = findViewById(R.id.shareButton_id);




        //sharing
        shareButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent myIntent = new Intent(Intent.ACTION_SEND);
                // this should be the file
                // must create folder the carrier image
                // this is a sample that takes string

                //intent takes string should be file
                myIntent.setType("text/plain");
                //should be the carrier image
                String shareBody = "Your body here";
                // can be removed / optional
                String shareSub = "Your subject here";
                myIntent.putExtra(Intent.EXTRA_SUBJECT,shareSub);
                myIntent.putExtra(Intent.EXTRA_TEXT,shareBody);
                startActivity(Intent.createChooser(myIntent, "Share using"));
            }
        });

        // SETTING UP ViewPagerAdapter
        ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());

        viewPagerAdapter.addElements(new EmbedFragment(), "Embed");
        viewPagerAdapter.addElements(new ExtractFragment(), "Extract");

        viewPager.setAdapter(viewPagerAdapter);
        tabLayout.setupWithViewPager(viewPager);




    }

}

0 个答案:

没有答案