mDisplayList无效

时间:2014-07-22 10:59:54

标签: android fragment

我有问题...我不知道,导致问题的原因是什么...... LogCat给了我这样的错误:

from LogCat

我能说什么...
应用程序中的操作就是这样:

  
      
  1. 我正在创建Intent选择器,从packageManager.queryIntentActivities中选择选择器......这就是
  2.   
  3. 我从相机或其他应用中获取照片
  4.   
  5. 我正在返回应用,此时此刻我遇到了错误。
  6.   

我可以补充一点,获取照片是由活动中的两个片段中的一个诱发的。

我可以说的是,有时候我回到我的应用程序后,应用程序仍然无法加载。

如果您需要更多信息,请与我们联系 任何搜索提示都会非常有用(我在互联网上找不到任何内容)

编辑: 要求图像的片段:

public class AddAmbajFragment extends AbstractFragment implements View.OnClickListener {
    Button addImageButton;
    private Uri outputFileUri;

    public AddAmbajFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_add_ambaj, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        assignViews();
        setListeners();
    }

    public void assignViews(){
        addImageButton = (Button) getView().findViewById(R.id.add_ambaj_camera_button);
    }

    public void setListeners(){
        addImageButton.setOnClickListener(this);
    }

    @Override
    protected void changeView(FragmentPlaceEnum fragmentPlaceEnum, FragmentEnum fragmentEnum){
        if(changeFragmentEventListener!=null)
            changeFragmentEventListener.onFragmenChange(fragmentPlaceEnum, fragmentEnum);
    };

    @Override
    public void onClick(View view) {
        openImageIntent();
    }

    private void openImageIntent() {

        // Determine Uri of camera image to save.
        final File root = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM) + File.separator + "AmbajePhotos" + File.separator);
        root.mkdirs();
        final String fname = "img_"+ System.currentTimeMillis() + ".jpg";
        final File sdImageMainDirectory = new File(root, fname);
        outputFileUri = Uri.fromFile(sdImageMainDirectory);

        // Camera.
        final List<Intent> cameraIntents = new ArrayList<Intent>();
        final Intent captureIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        final PackageManager packageManager = getActivity().getPackageManager();
        final List<ResolveInfo> listCam = packageManager.queryIntentActivities(captureIntent, 0);
        for(ResolveInfo res : listCam) {
            final String packageName = res.activityInfo.packageName;
            final Intent intent = new Intent(captureIntent);
            intent.setComponent(new ComponentName(packageName, res.activityInfo.name));
            intent.setPackage(packageName);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            cameraIntents.add(intent);
        }

        // Filesystem.
        final Intent galleryIntent = new Intent();
        galleryIntent.setType("image/*");
        galleryIntent.setAction(Intent.ACTION_GET_CONTENT);

        // Chooser of filesystem options.
        final Intent chooserIntent = Intent.createChooser(galleryIntent, getResources().getString(R.string.add_ambaj_select_source));

        // Add the camera options.
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, cameraIntents.toArray(new Parcelable[]{}));

        startActivityForResult(chooserIntent, 1);

    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
    {
        try {
        if(resultCode == getActivity().RESULT_OK)
        {
            if(requestCode == 1)
            {
                final boolean isCamera;
                if(data == null)
                {
                    isCamera = true;
                }
                else
                {
                    final String action = data.getAction();
                    if(action == null)
                    {
                        isCamera = false;
                    }
                    else
                    {
                        isCamera = action.equals(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                    }
                }

                    Uri selectedImageUri;
                    if (isCamera) {
                        selectedImageUri = outputFileUri;
                        File imgFile = new File(selectedImageUri.getPath());
                        if (imgFile.exists()) {

                            Bitmap myBitmap = getScaledBitmap(imgFile.getAbsolutePath(), 800, 800);

                            ImageView myImage = (ImageView) getView().findViewById(R.id.add_ambaj_image_view);
                            myImage.setImageBitmap(myBitmap);

                        }
                    } else {
                        selectedImageUri = data == null ? null : data.getData();
                        File imgFile = new File(getRealPathFromURI(getActivity().getApplicationContext(), selectedImageUri));

                        if (imgFile.exists()) {

                            Bitmap myBitmap = getScaledBitmap(imgFile.getAbsolutePath(), 800, 800);

                            ImageView myImage = (ImageView) getView().findViewById(R.id.add_ambaj_image_view);
                            myImage.setImageBitmap(myBitmap);
                        }
                    }


            }
        }
        }
        catch(Exception e){
            Log.w("KKK", "Error: "+e.toString());
        }
    }


    public String getRealPathFromURI(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {

            if("content".equals(contentUri.getScheme())) {
                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);
            }
            else{
                return contentUri.getPath();
            }


        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    private Bitmap getScaledBitmap(String picturePath, int width, int height) {
        BitmapFactory.Options sizeOptions = new BitmapFactory.Options();
        sizeOptions.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(picturePath, sizeOptions);

        int inSampleSize = calculateInSampleSize(sizeOptions, width, height);

        sizeOptions.inJustDecodeBounds = false;
        sizeOptions.inSampleSize = inSampleSize;

        return BitmapFactory.decodeFile(picturePath, sizeOptions);
    }

    private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        // Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {

            // Calculate ratios of height and width to requested height and
            // width
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);

            // Choose the smallest ratio as inSampleSize value, this will
            // guarantee
            // a final image with both dimensions larger than or equal to the
            // requested height and width.
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }
}

包含片段的主要活动

public class MainFragmentActivity extends Activity implements ChangeFragmentEventListener {
    AbstractFragment menuFragment;
    AbstractFragment contentFragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main_fragment);
        assignViews();
        setListeners();
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, 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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onFragmenChange(FragmentPlaceEnum fragmentPlaceEnum, FragmentEnum fragmentEnum) {

        AbstractFragment newFragment = null;
        if(fragmentEnum.equals(FragmentEnum.MAIN_WALL_FRAGMENT))
            newFragment = new MainWallFragment();
        else if(fragmentEnum.equals(FragmentEnum.GROUPS_FRAGMENT))
            newFragment = new GroupsFragment();
        else if(fragmentEnum.equals(FragmentEnum.NOTIFICATIONS_FRAGMENT))
            newFragment = new NotificationsFragment();
        else if (fragmentEnum.equals(FragmentEnum.ADD_AMBAJ_FRAGMENT))
            newFragment = new AddAmbajFragment();

        contentFragment = newFragment;

        FragmentTransaction transaction = getFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
        if(fragmentPlaceEnum.equals(FragmentPlaceEnum.MAIN_ACTIVITY_CONTENT))
            transaction.replace(R.id.main_content_fragment, newFragment);
        else if(fragmentPlaceEnum.equals(FragmentPlaceEnum.MAIN_ACTIVITY_MENU))
            transaction.replace(R.id.main_menu_fragment, newFragment);
        //transaction.addToBackStack(null);

// Commit the transaction
       transaction.commit();
    }

    private void assignViews(){

        menuFragment = (AbstractFragment) getFragmentManager().findFragmentById(R.id.main_menu_fragment);
        contentFragment = (AbstractFragment) getFragmentManager().findFragmentById(R.id.main_content_fragment);
    }

    private void setListeners(){
        menuFragment.setChangeFragmentEventListener(this);
        contentFragment.setChangeFragmentEventListener(this);
    }

}

1 个答案:

答案 0 :(得分:0)

听到它的声音,&#34;有时会崩溃&#34;我敢打赌你没有使用onSaveInstanceState()onRestoreInstanceState这只是预感。如果您发布代码和日志,将会很有帮助;要检查这是否是问题的一部分,请在您的设备上转到设置&gt;开发人员选项&gt;并检查&#34;不要保留活动..如果您的设备没有显示开发者选项:http://www.androidcentral.com/how-enable-developer-settings-android-42

@Override
    protected void onSaveInstanceState(Bundle outState) {

        super.onSaveInstanceState(outState);
        //save things

    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);

        //restore things

    }

用于图像调整大小的AsyncTask示例

import java.io.FileOutputStream;
import java.io.IOException;


import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;

import android.os.AsyncTask;
import android.util.Log;



public class ImageResizerTask extends AsyncTask<Integer, Void, Bitmap> {

    Bitmap mBitmap;
    String filePath;
    Context mContext;
    YourActivity mCallBack;
    //ProgressDialog pd;

    public ImageResizerTask(Context context, String path,
            YourActivity callBack) {

        mContext = context;
        filePath = path;
        mBitmap = BitmapFactory.decodeFile(filePath);
        mCallBack = callBack;
    }
    @Override
    protected void onPreExecute() {


    }

    @Override
    protected Bitmap doInBackground(Integer... params) {
        // TODO Auto-generated method stub
        resize(mBitmap);
        return mBitmap;
    }

    @Override
    protected void onPostExecute(Bitmap bitmap) {

        bitmap.recycle();
        mCallBack.onImageResized(filePath);

    }


    private void resize(Bitmap tmp) {

        final Bitmap bitmap = Bitmap.createBitmap(500, 500,
                Bitmap.Config.ARGB_8888);

        final Canvas canvas = new Canvas(bitmap);

        Log.v("TMPBMP",
                "temp bmp width:" + tmp.getWidth() + " height:"
                        + tmp.getHeight());

        if (tmp.getWidth() < tmp.getHeight()) {
            final int width = (int) (1f * tmp.getWidth() / tmp.getHeight() * 500);

            final int height = 500;
            final Bitmap scaled = Bitmap.createScaledBitmap(tmp, width, height,
                    false);
            final int leftOffset = (bitmap.getWidth() - scaled.getWidth()) / 2;
            final int topOffset = 0;
            canvas.drawBitmap(scaled, leftOffset, topOffset, null);
        } else {
            final int width = 500;
            final int height = (int) (1f * tmp.getHeight() / tmp.getWidth() * 500);
            ;
            final Bitmap scaled = Bitmap.createScaledBitmap(tmp, width, height,
                    false);
            final int leftOffset = 0;
            final int topOffset = (bitmap.getHeight() - scaled.getHeight()) / 2;
            canvas.drawBitmap(scaled, leftOffset, topOffset, null);
        }

        FileOutputStream outStream;

        try {
            outStream = new FileOutputStream(filePath);

            try {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                outStream.flush();
                outStream.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }


}