How to save image from ViewPager? - java

I have an activity with ViewPager. I'm using it to swipe images. I also have a save button, and I need to save the current image to SD card. But I get an error. Here's my XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/rl_view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:focusableInTouchMode="true" >
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<Button
android:id="#+id/bSave"
android:layout_width="80dp"
android:layout_height="40dp"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="15dp"
android:text="Save"
android:layout_alignParentLeft="true"
android:textSize="24sp"
android:padding="0dp"
android:background="#drawable/buttons" />
</RelativeLayout>
And here's my class:
public class Photo_gallery extends Activity implements OnClickListener{
Button save;
final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Images/");
boolean success = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_gallery);
save = (Button) findViewById(R.id.bSave);
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
save.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
final Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
final String fname = "StyleMe-" + n + ".png";
myDir.mkdirs();
File image = new File(myDir, fname);
BitmapDrawable drawable = (BitmapDrawable) viewPager.getBackground();
Bitmap bitmap = drawable.getBitmap();
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(), "Image saved with success at /sdcard/Pictures/SexyImages",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"Error during image saving", Toast.LENGTH_LONG).show();
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse
("file://"
+ Environment.getExternalStorageDirectory())));
}
});
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.p1,
R.drawable.p2,
R.drawable.p3,
.
.
.
.
R.drawable.p108
};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Photo_gallery.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
I get error on this line (java.lang.NullPointerException):
Bitmap bitmap = drawable.getBitmap();

why didn't you do like that :
on button Save Clicklistener :
int currentItem =viewPager.getCurrentItem();
Drawable drawable = getResource.getDrawable(mImages[currentItem]);
Bitmap bm =((BitmapDrawable) drawable).getBitmap();

Related

Android: I'm not able to display phone's images into my GridView

I have implemented Gridview, but the images from the phone gallery is not appearing in the particular GridView.
The scroll seems to be big enough as the scrollbar appearing on the right side scrolls along to the bottom. Then why I couldn't see the images.
GalleryGridAdapter.java
package com.test.Adapter;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v4.widget.CursorAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import android.widget.ImageView;
import com.test.R;
public class GalleryGridAdapter extends CursorAdapter
{
private Context mContext;
private Cursor mCursor;
private int mColumnIndex;
private ImageView imageView;
#SuppressWarnings("deprecation")
public GalleryGridAdapter(Context context, Cursor c, int ci) {
super(context, c);
mContext = context;
mCursor = c;
mColumnIndex = ci;
}
#Override
public void bindView(View view, Context context, Cursor curs)
{
ImageView imageView = (ImageView) view;
int id = curs.getInt(mColumnIndex);
imageView.setImageURI( Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
String.valueOf(id)));
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
}
#Override
public View newView(Context context, Cursor curs, ViewGroup parent)
{
return new ImageView(context);
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public int mygetItemId(int position) {
return 0;
}
}
MyActivity.java
String[] projection = {MediaStore.Images.Thumbnails._ID, MediaStore.Images.Thumbnails.DATA};
final Cursor cursor = context.getContentResolver().query(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, projection, null, null,
MediaStore.Images.Thumbnails.IMAGE_ID);
int columnIndex = 0;
if (cursor != null) {
columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
GridView gridview = (GridView) findViewById(R.id.gridViewGallery);
gridview.setAdapter(new GalleryGridAdapter(getApplicationContext(), cursor, columnIndex));
gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.e("selected Image",cursor.getColumnName(i)+"");
}
});
}
use xml code like :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#drawable/bg_child">
<FrameLayout android:id="#+id/FrameLayout01"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<FrameLayout android:id="#+id/LinearLayout01"
android:layout_gravity="top" android:layout_height="50dp" android:layout_width="fill_parent">
<TextView android:id="#+id/TextView01"
android:layout_width="wrap_content" android:layout_height="wrap_content" android:textStyle="bold" android:layout_gravity="center_vertical" android:layout_marginLeft="30dp" android:gravity="center_vertical" android:drawableLeft="#drawable/photo_frame" android:textColor="#color/grey" android:text="#string/photogallery_txt"></TextView>
<Button android:layout_gravity="right" android:id="#+id/btnMoreInfo" android:layout_marginRight="5dp" android:layout_marginTop="5dp" android:textStyle="bold" android:background="#drawable/my_child_button" android:layout_width="100dp" android:layout_height="40dp" android:text="#string/moreinfo_txt"></Button>
</FrameLayout>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:columnWidth="90dp"
android:numColumns="auto_fit" android:verticalSpacing="10dp"
android:horizontalSpacing="10dp" android:stretchMode="columnWidth"
android:gravity="center" android:layout_gravity="bottom"
android:layout_marginTop="50dp"/>
</FrameLayout>
use code like :
public class GalleryPage extends Activity {
private static Uri[] mUrls = null;
private static String[] strUrls = null;
private String[] mNames = null;
private GridView gridview = null;
private Cursor cc = null;
private Button btnMoreInfo = null;
private ProgressDialog myProgressDialog = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
btnMoreInfo = (Button) findViewById(R.id.btnMoreInfo);
// It have to be matched with the directory in SDCard
cc = this.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, null, null, null,
null);
if (cc != null) {
myProgressDialog = new ProgressDialog(GalleryPage.this);
myProgressDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
myProgressDialog.setMessage(getResources().getString(R.string.pls_wait_txt));
myProgressDialog.show();
new Thread() {
public void run() {
try {
cc.moveToFirst();
mUrls = new Uri[cc.getCount()];
strUrls = new String[cc.getCount()];
mNames = new String[cc.getCount()];
for (int i = 0; i < cc.getCount(); i++) {
cc.moveToPosition(i);
mUrls[i] = Uri.parse(cc.getString(1));
strUrls[i] = cc.getString(1);
mNames[i] = cc.getString(3);
//Log.e("mNames[i]",mNames[i]+":"+cc.getColumnCount()+ " : " +cc.getString(3));
}
} catch (Exception e) {
}
myProgressDialog.dismiss();
}
}.start();
gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Intent i = new Intent(GalleryPage.this, BigImage.class);
Log.e("intent : ", ""+position);
i.putExtra("imgUrls", strUrls);
i.putExtra("position", position);
startActivity(i);
}
});
}
btnMoreInfo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(GalleryPage.this, ChildLogin.class);
startActivity(i);
}
});
}
/**
* This class loads the image gallery in grid view.
*
*/
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return cc.getCount();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.galchild, null);
try {
ImageView imageView = (ImageView) v.findViewById(R.id.ImageView01);
//imageView.setScaleType(ImageView.ScaleType.FIT_XY);
// imageView.setPadding(8, 8, 8, 8);
Bitmap bmp = decodeURI(mUrls[position].getPath());
//BitmapFactory.decodeFile(mUrls[position].getPath());
imageView.setImageBitmap(bmp);
//bmp.
TextView txtName = (TextView) v.findViewById(R.id.TextView01);
txtName.setText(mNames[position]);
} catch (Exception e) {
}
return v;
}
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
FlurryAgent.onStartSession(this, "***");
}
/**
* This method is to scale down the image
*/
public Bitmap decodeURI(String filePath){
Options options = new Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, options);
// Only scale if we need to
// (16384 buffer for img processing)
Boolean scaleByHeight = Math.abs(options.outHeight - 100) >= Math.abs(options.outWidth - 100);
if(options.outHeight * options.outWidth * 2 >= 16384){
// Load, scaling to smallest power of 2 that'll get it <= desired dimensions
double sampleSize = scaleByHeight
? options.outHeight / 100
: options.outWidth / 100;
options.inSampleSize =
(int)Math.pow(2d, Math.floor(
Math.log(sampleSize)/Math.log(2d)));
}
// Do the actual decoding
options.inJustDecodeBounds = false;
options.inTempStorage = new byte[512];
Bitmap output = BitmapFactory.decodeFile(filePath, options);
return output;
}
}

Why are my "posts" loading in different sizes in android recyclerview?

Okay, this is how my recyclerview is showing my "posts". Can anyone tell me why? I will post source code as well. I have tried changing some of the code with no success. Also, when I scroll through my RecyclerView, some of them resize to smaller or larger sizes. Any and all help is appreciated!
fragment_home.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff" />
</LinearLayout>
list_item.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/listItemLayout">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<ImageButton
android:id="#+id/yesButton"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="#00FF00" />
<ImageButton
android:id="#+id/noButton"
android:layout_width="0dp"
android:layout_height="40dp"
android:layout_weight="1"
android:background="#FF0000" />
</LinearLayout>
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/image_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="#drawable/placeholder" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:background="#509f9f9f"
android:orientation="horizontal">
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="8"
android:orientation="horizontal">
<com.android.volley.toolbox.NetworkImageView
android:id="#+id/thumbnail"
android:layout_width="40dp"
android:layout_height="40dp"
android:scaleType="fitXY"
android:src="#drawable/placeholder" />
<TextView
android:id="#+id/pUsername"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:gravity="center_vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:text="username" />
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="horizontal">
<ImageButton
android:id="#+id/postMenu"
android:layout_width="match_parent"
android:layout_height="40dp"
android:background="#000"/>
</LinearLayout>
</LinearLayout>
</LinearLayout>
LruBitmapCache.java:
public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageCache {
public LruBitmapCache(int maxSize) {
super(maxSize);
}
public LruBitmapCache(Context context) {
this(getCacheSize(context));
}
#Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
#Override
public Bitmap getBitmap(String url) {
return get(url);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
put(url, bitmap);
}
public static int getCacheSize(Context context) {
final DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
final int screenWidth = displayMetrics.widthPixels;
final int screenHeight = displayMetrics.heightPixels;
final int screenBytes = screenWidth * screenHeight * 4;
return screenBytes * 3;
}
}
MyRecyclerAdapter.java:
public class MyRecyclerAdapter extends RecyclerView.Adapter<ListRowViewHolder> {
private List<ListItems> listItemsList;
private Context mContext;
private ImageLoader mImageLoader;
private int focusedItem = 0;
public MyRecyclerAdapter(Context context, List<ListItems> listItemsList) {
this.mContext = context;
this.listItemsList = listItemsList;
}
#Override
public ListRowViewHolder onCreateViewHolder(final ViewGroup viewGroup, int position) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
ListRowViewHolder holder = new ListRowViewHolder(v);
return holder;
}
#Override
public void onBindViewHolder(final ListRowViewHolder listRowViewHolder, int position) {
ListItems listItems = listItemsList.get(position);
listRowViewHolder.itemView.setSelected(focusedItem == position);
listRowViewHolder.getLayoutPosition();
mImageLoader = MySingleton.getInstance(mContext).getImageLoader();
listRowViewHolder.thumbnail.setImageUrl(listItems.getProfilePicture(), mImageLoader);
listRowViewHolder.thumbnail.setDefaultImageResId(R.drawable.placeholder);
listRowViewHolder.image_1.setImageUrl(listItems.getImage_1(), mImageLoader);
listRowViewHolder.image_1.setDefaultImageResId(R.drawable.placeholder);
listRowViewHolder.username.setText(Html.fromHtml(listItems.getUsername()));
}
public void clearAdapter() {
listItemsList.clear();
notifyDataSetChanged();
}
#Override
public int getItemCount() {
return (null != listItemsList ? listItemsList.size() : 0);
}
}
MySingleton.java:
public class MySingleton {
private static MySingleton mInstance;
private RequestQueue mRequestQueue;
private ImageLoader mImageLoader;
private static Context mContext;
private MySingleton(Context context) {
mContext = context;
mRequestQueue = getRequestQueue();
mImageLoader = new ImageLoader(mRequestQueue, new LruBitmapCache(LruBitmapCache.getCacheSize(mContext)));
}
public static synchronized MySingleton getInstance(Context context) {
if (mInstance == null) {
mInstance = new MySingleton(context);
}
return mInstance;
}
public RequestQueue getRequestQueue() {
if (mRequestQueue == null) {
mRequestQueue = Volley.newRequestQueue(mContext.getApplicationContext());
}
return mRequestQueue;
}
public <T> void addToRequestQueue(Request<T> req) {
getRequestQueue().add(req);
}
public ImageLoader getImageLoader() {
return mImageLoader;
}
}
ListRowViewHolder.java:
public class ListRowViewHolder extends RecyclerView.ViewHolder {
protected NetworkImageView thumbnail;
protected NetworkImageView image_1;
protected ImageButton yes;
protected ImageButton no;
protected TextView username;
protected LinearLayout recLayout;
public ListRowViewHolder(View view) {
super(view);
this.thumbnail = (NetworkImageView) view.findViewById(R.id.thumbnail);
this.image_1 = (NetworkImageView) view.findViewById(R.id.image_1);
this.yes = (ImageButton) view.findViewById(R.id.yesButton);
this.no = (ImageButton) view.findViewById(R.id.noButton);
this.username = (TextView) view.findViewById(R.id.pUsername);
this.recLayout = (LinearLayout) view.findViewById(R.id.listItemLayout);
view.setClickable(true);
}
}
FragmentHome.java:
public class FragmentHome extends Fragment {
private final String postsUrl = "http://www.example.com/fetch_posts.php";
private ProgressDialog progressDialog;
private static final String TAG = "RecyclerViewExample";
private List<ListItems> listItemsList = new ArrayList<>();
private RecyclerView mRecyclerView;
private MyRecyclerAdapter adapter;
public FragmentHome() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (container == null) {
return null;
}
View view = inflater.inflate(R.layout.fragment_home, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
mRecyclerView.addItemDecoration(
new HorizontalDividerItemDecoration.Builder(getActivity())
.color(Color.BLACK)
.build());
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(linearLayoutManager);
updateFeed();
return view;
}
public void updateFeed() {
showPD();
adapter = new MyRecyclerAdapter(getActivity(), listItemsList);
mRecyclerView.setAdapter(adapter);
RequestQueue request = Volley.newRequestQueue(getActivity());
adapter.clearAdapter();
JsonArrayRequest req = new JsonArrayRequest(postsUrl, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
try {
for (int i = 0; i < response.length(); i++) {
JSONObject post = (JSONObject) response.get(i);
ListItems item = new ListItems();
item.setImage_1(post.getString("image_1"));
item.setUsername(post.getString("username"));
item.setProfilePicture(post.getString("image_1"));
listItemsList.add(item);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error: " + e.getMessage(), Toast.LENGTH_LONG).show();
}
adapter.notifyDataSetChanged();
hidePD();
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
hidePD();
Toast.makeText(getActivity(), "Volley Error: " + error.getMessage(), Toast.LENGTH_LONG).show();
}
});
request.add(req);
}
private void showPD() {
if (progressDialog == null) {
progressDialog = new ProgressDialog(getActivity());
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(false);
progressDialog.setCanceledOnTouchOutside(false);
progressDialog.show();
}
}
private void hidePD() {
if (progressDialog != null) {
progressDialog.dismiss();
progressDialog = null;
}
}
#Override
public void onDestroy() {
super.onDestroy();
hidePD();
}
}
Regarding the question "Also, when I scroll through my RecyclerView, some of them resize to smaller or larger sizes." :
As the name says 'Recycler', it reuses the ViewHolder objects. When you scroll down/up and when the view (holder) goes off the screen, the view object wont get destroyed but it will be used again (recycled) to hold/represent another data set that is becoming visible.
If data set at the new position that is becoming visible does not have data (may be null or empty etc) which in your case is profile_pic/thumbnail, the RecyclerView will use the the data of the recycled holder which is used to represent this position. That is why when you have many data sets than that screen can hold and when you scroll up/down, you see that everytime you scroll a view (make it visible and invisible), it will show different data depending on the (recycled)holder it uses at the moment. If your profile pics are different than just cat pic for every view, then you can witness this effect clearly.
What you've to do is that before you set the data (image, text etc) to a view, you can better reset it first. If it is image you can clear/reset as suggested here https://stackoverflow.com/a/8243184/3209739. Or you can have placeholder image or make it transparent whatever. Then this problem should not occur.
I think for same reason, it shows the different sized images (thumb and profile pic).
Try resetting the views before you set to your actual data. Always better to follow this when RecyclerView is used.
Why do you want to have your own caching code ? Why can not you use Picasso image loader, Universal Image Loader or something that suits your requirement. Take a look here to know the different image loaders Picasso v/s Imageloader v/s Fresco vs Glide.
You're not properly inflating your View in onCreateViewHolder() Instead of
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, null);
you should use
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.list_item, viewGroup, false);
See this answer for more details on the different LayoutInflater.inflate() methods.

VideoView unable to open content from internel storage

I have the following code:
try {
myVideoView.setMediaController(mediaControls);
File mydir = getDir("myDir", Context.MODE_PRIVATE);
myVideoView.setVideoPath(mydir.getPath()+"/fileName.3gp");
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
myVideoView.requestFocus();
myVideoView.setOnPreparedListener(new OnPreparedListener() {
// Close the progress bar and play the video
public void onPrepared(MediaPlayer mp) {
progressDialog.dismiss();
myVideoView.seekTo(position);
if (position == 0) {
myVideoView.start();
} else {
myVideoView.pause();
}
}
});
within onCreate() method. The problem is that it throws an IOException, and says that Unable to open the content. It works perfect if I use myVideoView.setVideoURI(path/to/server) instead of myVideoView.setVideoPath(path/to/local/storage). All permissions at Manifest.xml are fine, and it does not says that the file was not found or something. It says unable to open it. It is not a video format problem either, because is the same video when I play it from server. If this is a useful info, I have another activity in background (same app), and the VideoView activity is in foreground. Thank you!
Hi use it to play Internal Video
public class MainActivity extends Activity {
private Cursor videocursor;
private int video_column_index;
ListView videolist;
int count;
String[] thumbColumns = { MediaStore.Video.Thumbnails.DATA, MediaStore.Video.Thumbnails.VIDEO_ID };
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init_phone_video_grid();
}
#SuppressWarnings("deprecation")
private void init_phone_video_grid() {
System.gc();
String[] proj = { MediaStore.Video.Media._ID, MediaStore.Video.Media.DATA, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.SIZE };
videocursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
count = videocursor.getCount();
videolist = (ListView) findViewById(R.id.PhoneVideoList);
videolist.setAdapter(new VideoAdapter(getApplicationContext()));
videolist.setOnItemClickListener(videogridlistener);
}
private OnItemClickListener videogridlistener = new OnItemClickListener() {
public void onItemClick(AdapterView parent, View v, int position, long id) {
System.gc();
video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
videocursor.moveToPosition(position);
String filename = videocursor.getString(video_column_index);
Intent intent = new Intent(MainActivity.this, ViewVideo.class);
intent.putExtra("videofilename", filename);
startActivity(intent);
}
};
public class VideoAdapter extends BaseAdapter {
private Context vContext;
public VideoAdapter(Context c) {
vContext = c;
}
public int getCount() {
return count;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
System.gc();
ViewHolder holder;
String id = null;
convertView = null;
if (convertView == null) {
convertView = LayoutInflater.from(vContext).inflate(R.layout.listitem, parent, false);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView.findViewById(R.id.txtTitle);
holder.txtSize = (TextView) convertView.findViewById(R.id.txtSize);
holder.thumbImage = (ImageView) convertView.findViewById(R.id.imgIcon);
video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
videocursor.moveToPosition(position);
id = videocursor.getString(video_column_index);
video_column_index = videocursor.getColumnIndexOrThrow(MediaStore.Video.Media.SIZE);
videocursor.moveToPosition(position);
// id += " Size(KB):" +
// videocursor.getString(video_column_index);
holder.txtTitle.setText(id);
holder.txtSize.setText(" Size(KB):" + videocursor.getString(video_column_index));
String[] proj = { MediaStore.Video.Media._ID, MediaStore.Video.Media.DISPLAY_NAME, MediaStore.Video.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, proj, MediaStore.Video.Media.DISPLAY_NAME + "=?",
new String[] { id }, null);
cursor.moveToFirst();
long ids = cursor.getLong(cursor.getColumnIndex(MediaStore.Video.Media._ID));
ContentResolver crThumb = getContentResolver();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 1;
Bitmap curThumb = MediaStore.Video.Thumbnails.getThumbnail(crThumb, ids, MediaStore.Video.Thumbnails.MICRO_KIND, options);
holder.thumbImage.setImageBitmap(curThumb);
curThumb = null;
} /*
* else holder = (ViewHolder) convertView.getTag();
*/
return convertView;
}
}
static class ViewHolder {
TextView txtTitle;
TextView txtSize;
ImageView thumbImage;
}
}
and Video View Class is here
public class ViewVideo extends Activity {
private String filename;
VideoView vv;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.gc();
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("videofilename");
// vv = new VideoView(getApplicationContext());
setContentView(R.layout.activity_main);
vv = (VideoView) findViewById(R.id.videoView);
vv.setVideoPath(filename);
vv.setMediaController(new MediaController(this));
vv.requestFocus();
vv.start();
}
}
And Xml Part is Here
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:background="#242425"
android:gravity="center"
android:orientation="vertical" >
<VideoView
android:id="#+id/videoView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="0.5" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.5"
android:background="#android:color/white"
android:gravity="center"
android:orientation="vertical" >
<ListView
android:id="#+id/PhoneVideoList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#android:color/darker_gray"
android:cacheColorHint="#00000000"
android:dividerHeight="2dp"></ListView>
</LinearLayout>
</LinearLayout>
</LinearLayout>

How to get the run time image id to set wallpaper

I am using view paper for image gallery, able to see all the images on swipe.
Here I want to set the image as wallpaper by clicking the "Set as wallpaper" button.
Below are the difficulties I am facing:
I am able to set the image as wallpaper successfully, but with constant image
Ex: R.drawable.picture3.But at run time when the images are loaded at each
turn different image will be displayed so cannot give this constant value
R.drawable.picture3.
How do I get the run time image id which is displayed?
Trying to achieve on click "Set as wallpaper" should set the current image
as wallpaper.
Note : v.getId()=R.drawable.picture1 not worked here both gave different value
Below is my code:
Context context;
Integer[] imageIDs = {
R.drawable.picture1,
R.drawable.picture2,
R.drawable.picture3,
R.drawable.picture4,
R.drawable.picture5,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery);
ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
ImageAdapter adapter = new ImageAdapter(this);
viewPager.setAdapter(adapter);
Button button=(Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
wallpaperManager.setResource(R.drawable.picture3);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),
"Image is clicked-"+v.getBackground(), Toast.LENGTH_SHORT).show();
}
});
}
public class ImageAdapter extends PagerAdapter{
Context context;
int currentPosition;
private int[] GalImages = new int[] {
R.drawable.picture1,
R.drawable.picture2,
R.drawable.picture3,
R.drawable.picture4,
R.drawable.picture5,
};
ImageAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.abc_action_bar_content_inset_material);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true">
</android.support.v4.view.ViewPager>
<Button
android:id="#+id/button1"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:background="#cccccc"
android:text="#string/set_as_wallpaper" />
</RelativeLayout>
I don't want to achieve this in instantiateItem method in image adapter.
It's simple.If I got it correct then you want to set the image as wallpaper after clicking the button.Then here is the logic
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
curruntPosition=arg0; //Here you can the position
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
And then
button.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
wallpaperManager.setResource(imageIDs[curruntPosition]);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(),
"Image is clicked-"+v.getBackground(), Toast.LENGTH_SHORT).show();
}
});
Edit:
If you want to get the current viewable image from the viewpager
Maintain a list of images that are added dynamically say imageList then
int currentItem =viewPager.getCurrentItem();
Drawable drawable = getResource.getDrawable(imageList[currentItem]);
Bitmap bm =((BitmapDrawable) drawable).getBitmap();

How to get path of checked picture using checkbox from grid view of photo Gallery in android

I am trying to get path of photo from gallery which in grid view. this gallery consists of each thumbnail with attached checkbox. Here is the whole code:
public class GridGallery extends Activity
{
ArrayList<String>list;
AlertDialog.Builder alert;
private Button send;
GridView gridView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_gallery);
DataModel dbModel = new DataModel(this);
list = dbModel.selectAll();
alert = new AlertDialog.Builder(GridGallery.this);
send = (Button)findViewById(R.id.send_message);
gridView = (GridView) findViewById(R.id.sdcard);
gridView.setAdapter(new ImageAdapter(this));
gridView.setClickable(true);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View view, int pos,
long id)
{
// TODO Auto-generated method stub
final int position = pos;
final String path = list.get(position).toString();
final String option[] = new String[]{"Send to","Watch"};
alert.setTitle("Pick options");
alert.setItems(option, new OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
// TODO Auto-generated method stub
if(option[which].equals("Watch"))
{
if(path.contains(".jpg"))
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(list.get(position))), "image/jpeg");
startActivity(intent);
}
else if(path.contains(".mp4"))
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(list.get(position))), "video/*");
startActivity(intent);
}
else
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(list.get(position))), "audio/*");
startActivity(intent);
}
}//
else
{
Intent sendMail = new Intent(GridGallery.this, SendMessage.class);
sendMail.putExtra("path", path);
startActivity(sendMail);
}
}
}).show();
}
});
send.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
// TODO Auto-generated method stub
String path = null;
Intent sendToMail = new Intent(GridGallery.this, SendMessage.class);
sendToMail.putExtra("path", path);
startActivity(sendToMail);
}
});
}
/**
* Adapter for our image files.
*/
private class ImageAdapter extends BaseAdapter
{
private final Context context;
Bitmap bitmap;
public ImageAdapter(Context localContext) {
context = localContext;
}
public int getCount()
{
return list.size();
}
public Object getItem(int position)
{
return position;
}
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView picturesView;
View myView = convertView;
if (convertView == null)
{
LayoutInflater layoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);//getLayoutInflater();
myView = layoutInflater.inflate(R.layout.image_selection, null);
picturesView = new ImageView(context);
picturesView = (ImageView)myView.findViewById(R.id.item_grid);
picturesView.setClickable(true);
if(list.get(position).contains(".jpg"))
{
bitmap = BitmapFactory.decodeFile(list.get(position));
}
else if(list.get(position).contains(".mp4"))
{
bitmap = ThumbnailUtils.createVideoThumbnail(list.get(position), 0);
}
else
{
}
picturesView.setImageBitmap(bitmap);
picturesView.setScaleType(ImageView.ScaleType.FIT_CENTER);
picturesView.setPadding(8, 8, 8, 8);
return myView;
}
else
{
myView = convertView;
return myView;
}
}
}
}
MY problem is I can not be able to click the image or video thumbnail. also how do I able to get the image when I checked the check box.
here is XML code for Image_selection:-
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:orientation="vertical" android:gravity="center_horizontal">
<ImageView android:id="#+id/item_grid" android:layout_width="100dip" android:layout_height="100dip"/>
<CheckBox android:id="#+id/check" android:layout_width="wrap_content" android:layout_height="wrap_content" />
and grid_gallery.xml:-
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical">
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/sdcard"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:columnWidth="90dp"
android:stretchMode="columnWidth"
android:gravity="center"
/>
</RelativeLayout>
please help me. Thanks in advance
it seems you store the image path in the ArrayList list. If so, then set an onItemClickListeber for the GridView. in the onItemClick method you get the position of the gridview which was clicked. try 'list.get(position)in theonItemClick` to get the path

Categories

Resources