1

I want to share image in android. I examine a lot of code to do that but all codes make application stopped .the logcat error is as below:

05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime: FATAL EXCEPTION: main
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime: java.lang.RuntimeException: Parcel: unable to marshal value ir.whc.news.model.ImageItem@41884b00
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Parcel.writeValue(Parcel.java:1235)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Parcel.writeList(Parcel.java:622)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Parcel.writeValue(Parcel.java:1195)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Parcel.writeMapInternal(Parcel.java:591)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Bundle.writeToParcel(Bundle.java:1619)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Parcel.writeBundle(Parcel.java:605)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.support.v4.app.FragmentState.writeToParcel(Fragment.java:137)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Parcel.writeTypedArray(Parcel.java:1102)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.support.v4.app.FragmentManagerState.writeToParcel(FragmentManager.java:385)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Parcel.writeParcelable(Parcel.java:1254)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Parcel.writeValue(Parcel.java:1173)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Parcel.writeMapInternal(Parcel.java:591)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Bundle.writeToParcel(Bundle.java:1619)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Parcel.writeBundle(Parcel.java:605)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.app.ActivityManagerProxy.activityStopped(ActivityManagerNative.java:2238)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.app.ActivityThread$StopInfo.run(ActivityThread.java:3393)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Handler.handleCallback(Handler.java:615)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:92)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:155)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5520)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
05-08 22:17:33.656 25125-25125/ir.whc.news E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)

and this is my code:

    package ir.whc.news.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import ir.whc.news.R;
import ir.whc.news.classes.CapturePhotoUtils;
import ir.whc.news.classes.Utility;
import ir.whc.news.model.ImageItem;

/**
 * Created by marzieh on 4/27/2016.
 */
public class SlideshowDialogFragment extends DialogFragment implements View.OnClickListener {
    private String TAG = SlideshowDialogFragment.class.getSimpleName();
    private ArrayList<ImageItem> images;
    private ViewPager viewPager;
    private MyViewPagerAdapter myViewPagerAdapter;
    private TextView lblCount, lblTitle;
    private int selectedPosition = 0;
    private int scwidth;
    RelativeLayout buttom_toolbar;
    ImageView btnsave;
    ImageView btnshare;
    ImageView imageViewPreview;
    ImageItem image;

    static SlideshowDialogFragment newInstance() {
        SlideshowDialogFragment f = new SlideshowDialogFragment();
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_image_slider, container, false);
        viewPager = (ViewPager) v.findViewById(R.id.viewpager);
        lblCount = (TextView) v.findViewById(R.id.lbl_count);
        lblTitle = (TextView) v.findViewById(R.id.title);
        buttom_toolbar = (RelativeLayout) v.findViewById(R.id.bottom_toolbar);
        buttom_toolbar.setVisibility(View.INVISIBLE);
        btnsave = (ImageView) v.findViewById(R.id.btnsave);
        btnshare = (ImageView) v.findViewById(R.id.btnshare);
        btnshare.setOnClickListener(this);
        btnsave.setOnClickListener(this);

        images = (ArrayList<ImageItem>) getArguments().getSerializable("images");
        selectedPosition = getArguments().getInt("position");
        scwidth = getArguments().getInt("scwidth");

        Log.e(TAG, "position: " + selectedPosition);
        Log.e(TAG, "images size: " + images.size());

        myViewPagerAdapter = new MyViewPagerAdapter();
        viewPager.setAdapter(myViewPagerAdapter);
        viewPager.addOnPageChangeListener(viewPagerPageChangeListener);

        setCurrentItem(selectedPosition);

        return v;
    }

    private void setCurrentItem(int position) {
        viewPager.setCurrentItem(position, false);
        displayMetaInfo(selectedPosition);
    }

    //  page change listener
    ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {

        @Override
        public void onPageSelected(int position) {
            displayMetaInfo(position);
        }

        @Override
        public void onPageScrolled(int arg0, float arg1, int arg2) {

        }

        @Override
        public void onPageScrollStateChanged(int arg0) {

        }
    };

    private void displayMetaInfo(int position) {
        lblCount.setText((position + 1) + " of " + images.size());

        ImageItem image = images.get(position);
        lblTitle.setText(image.get_description() != "null" ? image.get_description() : "");

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnsave:
                ProgressDialog pdilog=new ProgressDialog(getActivity());
                pdilog.setMessage(getString(R.string.loading));
                pdilog.show();

                savepic();
             pdilog.hide();
                Toast.makeText(getActivity(), getString(R.string.pictureissaved), Toast.LENGTH_SHORT).show();

                break;
            case R.id.btnshare:
                sharePic();

                break;
        }
    }
    private void sharePic()
    {


        Bitmap bitmap;
        OutputStream output;
        if (imageViewPreview.getDrawable() instanceof BitmapDrawable) {
            bitmap = ((BitmapDrawable) imageViewPreview.getDrawable()).getBitmap();
        } else {
            Drawable d = imageViewPreview.getDrawable();
            bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            d.draw(canvas);
        }
        // Find the SD Card path
        File filepath = Environment.getExternalStorageDirectory();

        // Create a new folder AndroidBegin in SD Card
        File dir = new File(filepath.getAbsolutePath() + "/Share Image Tutorial/");
        dir.mkdirs();

        // Create a name for the saved image
        File file = new File(dir, "sample_wallpaper.png");

        try {

            // Share Intent
            Intent share = new Intent(Intent.ACTION_SEND);

            // Type of file to share
            share.setType("image/jpeg");

            output = new FileOutputStream(file);

            // Compress into png format image from 0% - 100%
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, output);
            output.flush();
            output.close();

            // Locate the image to Share
            Uri uri = Uri.fromFile(file);

            // Pass the image into an Intnet
            share.putExtra(Intent.EXTRA_STREAM, uri);

            // Show the social share chooser list
            startActivity(Intent.createChooser(share, "Share Image Tutorial"));

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

    }

    private void savepic() {

        Bitmap bitmap;
        if (imageViewPreview.getDrawable() instanceof BitmapDrawable) {
            bitmap = ((BitmapDrawable) imageViewPreview.getDrawable()).getBitmap();
        } else {
            Drawable d = imageViewPreview.getDrawable();
            bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
            Canvas canvas = new Canvas(bitmap);
            d.draw(canvas);
        }
        CapturePhotoUtils.insertImage(getActivity().getContentResolver(), bitmap, image.get_id() + "", image.get_description());


    }

    //  adapter
    public class MyViewPagerAdapter extends PagerAdapter {

        private LayoutInflater layoutInflater;

        public MyViewPagerAdapter() {
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {

            layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = layoutInflater.inflate(R.layout.image_fullscreen_preview, container, false);

            imageViewPreview = (ImageView) view.findViewById(R.id.image_preview);

            image = images.get(position);

            Glide.with(getActivity()).load(image.get_largimage_path() + "/" + scwidth)

                    .thumbnail(0.5f)
                    .crossFade()
                    .diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(imageViewPreview);

            container.addView(view);


            imageViewPreview.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //  buttom_toolbar.setVisibility(buttom_toolbar.getVisibility()==View.VISIBLE?View.INVISIBLE:View.VISIBLE);

                    if (buttom_toolbar.getVisibility() == View.INVISIBLE) {
                        buttom_toolbar.setVisibility(View.VISIBLE);
                        new Handler().postDelayed(new Runnable() {
                            public void run() {
                                buttom_toolbar.setVisibility(View.INVISIBLE);
                            }
                        }, 3000);

                    } else {
                      //  buttom_toolbar.setVisibility(View.INVISIBLE);

                    }




                  /*  AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                    builder.setMessage(getString(R.string.savePicMessage))
                            .setCancelable(false)
                            .setPositiveButton(getString(R.string.Ok), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
*//*

                                    Bitmap bitmap;
                                    if (imageViewPreview.getDrawable() instanceof BitmapDrawable) {
                                        bitmap = ((BitmapDrawable) imageViewPreview.getDrawable()).getBitmap();
                                    } else {
                                        Drawable d = imageViewPreview.getDrawable();
                                        bitmap = Bitmap.createBitmap(d.getIntrinsicWidth(), d.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
                                        Canvas canvas = new Canvas(bitmap);
                                        d.draw(canvas);
                                    }
                                    CapturePhotoUtils.insertImage(getActivity().getContentResolver(), bitmap, image.get_id() + "", image.get_description());
*//*

                                }
                            })
                            .setNegativeButton(getString(R.string.Cancle), new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            });
                    AlertDialog alert = builder.create();
                    alert.show();*/
                }
            });


            return view;
        }

        @Override
        public int getCount() {
            return images.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object obj) {
            return view == ((View) obj);
        }


        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }
    }




}

what's wrong with my code?

EDITE: imageItem class

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by marzieh on 4/9/2016.
 */
public class ImageItem {

    private int _id;
    private String _description;
    private String _thumb_path;
    private String _largimage_path;

    public ImageItem()
    {

    }

    public ImageItem(int _id,String _description,String _thumb_path,String _largimage_path)
    {
        this._id=_id;
        this._description=_description;
        this._largimage_path=_largimage_path;
        this._thumb_path=_thumb_path;

    }
    public String get_description() {
        return _description;
    }

    public void set_description(String _description) {
        this._description = _description;
    }

    public void set_id(int _id) {
        this._id = _id;
    }

    public int get_id() {
        return _id;
    }

    public String get_largimage_path() {
        return _largimage_path;
    }

    public String get_thumb_path() {
        return _thumb_path;
    }

    public void set_largimage_path(String _largimage_path) {
        this._largimage_path = _largimage_path;
    }

    public void set_thumb_path(String _thumb_path) {
        this._thumb_path = _thumb_path;
    }

    public static ImageItem fromJson(JSONObject jsonObject)
    {
        ImageItem imageItem=new ImageItem();

        try {
            imageItem._id=Integer.parseInt(jsonObject.getString("id"));
            imageItem._largimage_path=jsonObject.getString("large_img");
            imageItem._thumb_path=jsonObject.getString("tb_img");
            imageItem._description=jsonObject.getString("description");


        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
        // Return new object
        return imageItem;
    }
    public static ArrayList<ImageItem> fromJson(JSONArray jsonArray) {
        JSONObject imageItemJson;
        ArrayList<ImageItem> imageItems = new ArrayList<ImageItem>(jsonArray.length());
        // Process each result in json array, decode and convert to subdomain object
        for (int i=0; i < jsonArray.length(); i++) {
            try {
                imageItemJson = jsonArray.getJSONObject(i);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }

            ImageItem imageItem = ImageItem.fromJson(imageItemJson);
            if (imageItem != null) {
                imageItems.add(imageItem);
            }
        }

        return imageItems;
    }

}
Cœur
  • 37,241
  • 25
  • 195
  • 267
MSepehr
  • 890
  • 2
  • 13
  • 36
  • 2
    Your problem lies with `ir.whc.news.model.ImageItem` and how it is being used. – CommonsWare May 08 '16 at 17:42
  • this code work without share , so there is nothing wrong with `ImageItem` – MSepehr May 08 '16 at 17:45
  • 2
    Yes, there is. The error is `java.lang.RuntimeException: Parcel: unable to marshal value ir.whc.news.model.ImageItem@41884b00`. Android is having difficulty attempting to work with your `ImageItem`, perhaps as it trying to pass it from one activity to another, or possibly as part of working with the saved instance state `Bundle`. If you choose not to pay attention to the error message, then nobody can help you. – CommonsWare May 08 '16 at 17:50
  • @CommonsWare share image do not use `imageitem`. so i do not know what's the reason of this error! :( – MSepehr May 10 '16 at 21:25
  • can you share code inside class ImageItem? – Ankit Aggarwal May 11 '16 at 05:38
  • @ankitaggarwal i did it as edite – MSepehr May 11 '16 at 07:47

3 Answers3

1

I do not think the issue is with sharing code. From stacktrace you can clearly see that framework complains about ImageItem class object:

java.lang.RuntimeException: Parcel: unable to marshal value ir.whc.news.model.ImageItem@41884b00.

not knowing how to parcel it. Apparently you are passing your ImageItem objects as arguments thru bundle to your DialogFragment (your question lacks this invocation code), and to make this happen object must implement Parcelable interface. Your ImageItem is does not have required code so you need to add it (see How can I make my custom objects be Parcelable? for info how to that or what tools to use to make required code generated). Alternatively you can use libraries like Parceler to do this for you.

Community
  • 1
  • 1
Marcin Orlowski
  • 72,056
  • 11
  • 123
  • 141
1

You are getting a crash because of this line

images = (ArrayList<ImageItem>) getArguments().getSerializable("images");

Actually your ImageItem is neither Serializable nor Parcelable and you are trying to send its objects in bundle as arguments. To avoid this, implement your ImageItem class with Parcelable interface.

public class ImageItem implements Parcelable{
    public static final Creator<ImageItem> CREATOR = new Creator<ImageItem>() {

        public ImageItem createFromParcel(Parcel in) {
            return new ImageItem(in);
        }

        public ImageItem[] newArray(int size) {
            return new ImageItem[size];
        }
    };

    public Contact(Parcel parcel) {
        _id = parcel.readInt();
        _description = parcel.readString();
        _thumb_path = parcel.readString();
        _largimage_path = parcel.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel parcel, int flags) {
        parcel.writeInt(_id);
        parcel.writeString(_description);
        parcel.writeString(_thumb_path);
        parcel.writeString(_largimage_path);
    }

    ...
    ...
}

Now to send the arraylist of your ImageItem objects, just put

bundle.putParcelableArrayListExtra("images", imageItemList);

and to retrieve this list, you have to do ,

images = (ArrayList<ImageItem>) getArguments().getParcelableArrayListExtra("images");
Ankit Aggarwal
  • 5,317
  • 2
  • 30
  • 53
1

You need to implements your ImageItem class as Serializable.

public class ImageItem implements Serializable{

// Other stuff

}

Hope this will help you.

Hiren Patel
  • 52,124
  • 21
  • 173
  • 151