How to share full screen image android? - java

I am displaying image in the view pager by fetching from the server.I am not displaying the full screen image.I have added the feature to share the image via email or many other options.
code to share image
imageView = (TouchImageView) viewpager.findViewWithTag(viewpager
.getCurrentItem());
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
String path = Images.Media.insertImage(getContentResolver(), bitmap,
"description", null);
uri = Uri.parse(path);
Intent send_report = new Intent(Intent.ACTION_SEND);
send_report.putExtra(Intent.EXTRA_EMAIL, new String[] { "" });
send_report.putExtra(Intent.EXTRA_SUBJECT, "Give Me That Picture");
send_report.putExtra(Intent.EXTRA_STREAM, uri);
send_report.putExtra(Intent.EXTRA_TEXT, "cool picture");
send_report.setType("text/plain");
send_report.setType("image/png");
startActivityForResult(
Intent.createChooser(send_report, "Choose an Email client"), 77);
But the image which is shared is not a full screen image.But i want to share the actual size image.Please help me out on this.
UPDATE
view pager adapter
public class ImagePagerAdapter extends PagerAdapter {
LayoutInflater inflater;
PhotoViewAttacher attacher;
PhotoViewAttacher pic;
private DisplayImageOptions options;
private List<Wallpaper> IMAGES_LIST = AppController.getInstance()
.getPrefManger().getAllImages();
public ImagePagerAdapter(Context context) {
inflater = LayoutInflater.from(context);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.resetViewBeforeLoading(true).cacheOnDisk(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true)
.displayer(new FadeInBitmapDisplayer(300)).build();
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
final View imageLayout = inflater.inflate(
R.layout.item_pager_image, container, false);
assert imageLayout != null;
pos = position;
imageView = (TouchImageView) imageLayout.findViewById(R.id.image);
// pic=new PhotoViewAttacher(imageView);
imageView.setTag(position);
imageView.setOnDoubleTapListener(new OnDoubleTapListener() {
#Override
public boolean onSingleTapConfirmed(MotionEvent e) {
// TODO Auto-generated method stub
Log.i("hello", "sinfle");
mHandler.removeCallbacks(r);
share.setVisibility(View.VISIBLE);
done.setVisibility(View.VISIBLE);
gimmy.setVisibility(View.VISIBLE);
comment.setVisibility(View.VISIBLE);
mHandler.postDelayed(r, 5 * 1000);
return false;
}
#Override
public boolean onDoubleTapEvent(MotionEvent e) {
// TODO Auto-generated method stub
Log.i("hello", "donl");
return false;
}
#Override
public boolean onDoubleTap(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
});
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showShareDialog();
}
});
final ProgressBar spinner = (ProgressBar) imageLayout
.findViewById(R.id.loading);
ImageLoader.getInstance().displayImage(
IMAGES_LIST.get(position).getUrl(), imageView, options,
new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
view.setVisibility(View.GONE);
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(view.getContext(), message,
Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
view.setVisibility(View.VISIBLE);
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES_LIST.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}

You've already set cacheOnDisk(true), so now you want to take an image from it by:
File cachedImage = imageLoader.getDiscCache().get(imageUrl);
if (cachedImage.exists()) {
/// get your image from file
}

If you take the cache of the current image in view pager then you will get the view which is being displayed on view pager with margins.You need to download the image from the server.Get the url of current displayed image in view pager & download the image from the server.This will solve your problem.

Related

How to implement view pager adapter in android?

I am building an android application like TechCrunch where user can swipe the articles.
I had used view pager adapter for doing this but my application some time crash.
The error I get in my logcat is :
java.lang.IllegalStateException: The application's PagerAdapter
changed the adapter's contents without calling
PagerAdapter#notifyDataSetChanged! Expected adapter item count: 40,
found: 50 Pager id: com.yslabs.yourstory:id/myviewpager Pager class:
class android.support.v4.view.ViewPager Problematic adapter: class
singlearticle.SingleArticle$MyPagerAdapter at
android.support.v4.view.ViewPager.populate(ViewPager.java:962) at
android.support.v4.view.ViewPager.populate(ViewPager.java:914) at
android.support.v4.view.ViewPager$3.run(ViewPager.java:244) at
android.view.Choreographer$CallbackRecord.run(Choreographer.java:747)
at android.view.Choreographer.doCallbacks(Choreographer.java:567) at
android.view.Choreographer.doFrame(Choreographer.java:535) at
android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:733)
at android.os.Handler.handleCallback(Handler.java:615) at
android.os.Handler.dispatchMessage(Handler.java:92) at
android.os.Looper.loop(Looper.java:153) at
android.app.ActivityThread.main(ActivityThread.java:5034) at
java.lang.reflect.Method.invokeNative(Native Method) at
java.lang.reflect.Method.invoke(Method.java:511) at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584) at
dalvik.system.NativeStart.main(Native Method)
Here is the class where I am using view page adapter
public class SingleArticleAfrica extends Activity {
ConnectionDetector checkConnection;
Boolean isInternetPresent = false;
ViewPager viewPage;
MyPagerAdapter mypageAdapter;
#SuppressWarnings("deprecation")
#SuppressLint({ "InflateParams", "SetJavaScriptEnabled", "HandlerLeak",
"NewApi" })
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.check);
viewPage = (ViewPager) findViewById(R.id.myviewpager);
mypageAdapter = new MyPagerAdapter(this, ArticleDataHolder.getData());
viewPage.setAdapter(mypageAdapter);
viewPage.setCurrentItem(ArticleDataHolder.getPosition());
viewPage.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
ArticleDataHolder.setPosition(position);
viewPage.setCurrentItem(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
}
});
getActionBar().setBackgroundDrawable(
new ColorDrawable(Color.parseColor("#f8f8f8")));
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
ActionBar mActionBar = getActionBar();
mActionBar.setDisplayShowHomeEnabled(true);
mActionBar.setDisplayShowTitleEnabled(false);
LayoutInflater mInflater = LayoutInflater.from(this);
View mCustomView = mInflater.inflate(R.layout.customactionbar, null);
TextView mTitleTextView = (TextView) mCustomView
.findViewById(R.id.title_text);
Typeface fontt = Typeface.createFromAsset(getAssets(),
"helvetica.ttf");
mTitleTextView.setTypeface(fontt);
mActionBar.setCustomView(mCustomView);
mActionBar.setDisplayShowCustomEnabled(true);
mActionBar.setLogo(R.drawable.africaicon);
// String htmldata =
// "<html><style = text/css> img{width:100%!important;height:auto!important;}iframe{max-
width:100%;max-height:100%;}a { color:#3366CC; text-decoration: none; }</style><body
style = line-
height:25px; >"
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main2, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_refresh:
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(
Intent.EXTRA_TEXT,
ArticleDataHolder.getData()
.get(ArticleDataHolder.getPosition()).getTitle()
+ "\n"
+ ArticleDataHolder.getData()
.get(ArticleDataHolder.getPosition())
.getPermalink());
sendIntent.setType("text/plain");
startActivity(sendIntent);
return true;
case android.R.id.home:
onBackPressed();
/*web1.loadUrl("");
web1.stopLoading();*/
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public class myWebClient extends WebViewClient
{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
// progressBar.setVisibility(View.GONE);
}
}
// To handle "Back" key press event for WebView to go back to previous
// screen.
#SuppressWarnings("static-access")
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == event.KEYCODE_BACK) {
/*web1.loadUrl("");
web1.stopLoading();*/
finish();
}
return super.onKeyDown(keyCode, event);
}
private class MyPagerAdapter extends PagerAdapter {
Context context;
List<Movie> list;
public MyPagerAdapter(Context context, List<Movie> list) {
this.context = context;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
public Object instantiateItem(ViewGroup container, int position) {
/* *Title* */
float titleSize = 25;
TextView titleView = new TextView(SingleArticleAfrica.this);
Typeface fontType = Typeface.createFromAsset(getAssets(),
"helvetica-neue-regular-1361522098.ttf");
titleView.setTypeface(fontType);
titleView.setTextSize(titleSize);
titleView.setBackgroundResource(R.color.list_background);
titleView.setTypeface(Typeface.DEFAULT_BOLD);
titleView.setText(list.get(position).getTitle());
/* * Date * */
TextView dateView = new TextView(SingleArticleAfrica.this);
dateView.setTextColor(Color.GRAY);
dateView.setBackgroundResource(R.color.list_background);
dateView.setTextSize(14);
dateView.setPadding(10, 0, 0, 0);
dateView.setTypeface(Typeface.DEFAULT_BOLD);
dateView.setText(list.get(position).getAuthor()
+ " "
+ list.get(position)
.getDate()
.substring(0,
list.get(position).getDate().length() - 3));
/* *Article Content* */
WebView web1 = new WebView(SingleArticleAfrica.this);
web1.setWebViewClient(new myWebClient());
web1.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
web1.getSettings().setJavaScriptEnabled(true);
web1.getSettings().setDefaultFontSize(18);
web1.setWebChromeClient(new WebChromeClient());
web1.getSettings().setPluginState(PluginState.ON_DEMAND);
String c = single.content;
c = c.replace("src=\"//", "src=\"https://");
final String ALLOWED_URI_CHARS = "##&=*+-_.,:!?()/~'%";
String htmldata = "<!DOCTYPE html><html><style = text/css>
img{width:100%!important;height:auto!important;} iframe{width:100sp;max-height:100sp;}a {
color:#3366CC; text-decoration: none; } </style> <body style = 'line-height:25px;'>"
+ list.get(position).getContent() + "</body></html>";
web1.loadData(htmldata, "text/html; charset=utf-8", null);
/* *Facebook Comment* */
WebView fbCommentview = new WebView(SingleArticleAfrica.this);
fbCommentview.setWebViewClient(new myWebClient());
fbCommentview.getSettings()
.setJavaScriptCanOpenWindowsAutomatically(true);
fbCommentview.getSettings().setJavaScriptEnabled(true);
fbCommentview.getSettings().setDefaultFontSize(18);
fbCommentview.setWebChromeClient(new WebChromeClient());
fbCommentview.getSettings().setPluginState(PluginState.ON_DEMAND);
checkConnection = new ConnectionDetector(getApplicationContext());
isInternetPresent = checkConnection.isConnectingToInternet();
if (isInternetPresent) {
// Toast.makeText(getApplicationContext(),"Internet Working",
// Toast.LENGTH_SHORT).show();
fbCommentview.setVisibility(View.VISIBLE);
} else {
// Toast.makeText(getApplicationContext(),"Internet Not Working",
// Toast.LENGTH_SHORT).show();
fbCommentview.setVisibility(View.GONE);
}
ScrollView scrollView = new ScrollView(SingleArticleAfrica.this);
LinearLayout layout = new LinearLayout(SingleArticleAfrica.this);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(titleView);
layout.addView(dateView);
layout.addView(web1);
layout.addView(fbCommentview);
scrollView.addView(layout);
container.addView(scrollView);
return scrollView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
//container.removeView((ScrollView) object);
}
}
}
Here is getPosition class code :
public class ArticleDataHolder {
static List<Movie> data = new ArrayList<Movie>();
static int position;
public static void setData(Movie movie){
data.add(movie);
}
public static List<Movie> getData(){
return data;
}
public static void setPosition(int pos){
position = pos;
}
public static int getPosition(){
return position;
}
}
Please help me!! to make me more understanding this problem an suggested the solution.
this error say your data(list) size changed but pagerAdapter.notifyDataChanged() not called.
when you setData and list changed in code you should call notifyDataChanged() after this change.
where you call ArticleDataHolder.setData()?

Android Listview with different layout for each row Java NullPointerException

Solved! Look at the edit below!
I am trying to create a list view to show different type of layouts but am getting this error
(I am getting this error when I scroll up, after scrolling down and seeing both types of layouts)
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
I can scroll to the bottom and see both types of layouts (couldn't see them both at once (error) when the else statement with the comment "//THIS ONE!" want there)
Code for my adapter is as follows - (edited as with #matiash's suggestions)
public class NewsAdapter extends ArrayAdapter<NewsXMLData> {
ImageLoader imageLoader;
DisplayImageOptions options;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private LayoutInflater mInflater;
public NewsAdapter(Context ctx, int textViewResourceId, List<NewsXMLData> sites) {
super(ctx, textViewResourceId, sites);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
#Override
public int getItemViewType(int position) {
if(getItem(position).getType().equals("image")) {
return TYPE_ITEM;
}
else{
return TYPE_SEPARATOR;
}
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
public static class ViewHolder {
public ImageView iconImg = null;
public TextView contentTxt = null;
public TextView imageTitleTxt = null ;
public ProgressBar imageIndicator = null ;
public TextView textTitleTxt = null ;
public ProgressBar textIndicator = null;
}
String flag;
//#Override
public View getView(int pos, View convertView, ViewGroup parent){
ViewHolder holder =null;
int type = getItemViewType(pos);
Log.i("APP", "getView " + pos + " " + convertView + " type = " + type);
View row = convertView;
mInflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
try {
if (null == row) {
//No recycled View, we have to inflate one.
holder = new ViewHolder();
switch (type){
case TYPE_ITEM:
row = (RelativeLayout) mInflater.inflate(R.layout.row_news, null);
holder.iconImg = (ImageView) row.findViewById(R.id.newsImageView);
holder.imageTitleTxt = (TextView) row.findViewById(R.id.newsTitleText);
holder.imageIndicator = (ProgressBar) row.findViewById(R.id.newsProgressBar);
holder.iconImg.setVisibility(View.INVISIBLE);
holder.imageIndicator.setVisibility(View.VISIBLE);
holder.imageTitleTxt.setVisibility(View.INVISIBLE);
//Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener() {
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
}
#Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
};
holder.iconImg.setVisibility(View.VISIBLE);
holder.imageIndicator.setVisibility(View.INVISIBLE);
holder.imageTitleTxt.setVisibility(View.VISIBLE);
//Load the image and use our options so caching is handled.
imageLoader.displayImage(getItem(pos).getImgUrl(), holder.iconImg, options, listener);
//Set the relavent text in our TextViews
holder.imageTitleTxt.setText(getItem(pos).getTitle());
break;
case TYPE_SEPARATOR:
row = (RelativeLayout) mInflater.inflate(R.layout.row_news_text, null);
holder.contentTxt = (TextView) row.findViewById(R.id.newsTextContentText);
holder.textTitleTxt = (TextView) row.findViewById(R.id.newsTextTitleText);
holder.textIndicator = (ProgressBar) row.findViewById(R.id.newsTextProgressBar);
/*holder.contentTxt.setVisibility(View.INVISIBLE);
holder.textIndicator.setVisibility(View.VISIBLE);
holder.textTitleTxt.setVisibility(View.INVISIBLE);*/
holder.contentTxt.setVisibility(View.VISIBLE);
holder.textIndicator.setVisibility(View.INVISIBLE);
holder.textTitleTxt.setVisibility(View.VISIBLE);
holder.textTitleTxt.setText(getItem(pos).getTitle());
holder.contentTxt.setText(getItem(pos).getContent());
break;
}
convertView.setTag(holder);
}
else{
holder = (ViewHolder)convertView.getTag();
}
}catch (Exception e){
e.printStackTrace();
}
return row;
}
}
Any suggestions?
Also, is there a better way to do it other than parsing XML and showing the content as a list view?
Edit: The code now works thanks to #Jens and #matiash
Code:
public class NewsAdapter extends ArrayAdapter<NewsXMLData> {
ImageLoader imageLoader;
DisplayImageOptions options;
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
private LayoutInflater mInflater;
public NewsAdapter(Context ctx, int textViewResourceId, List<NewsXMLData> sites) {
super(ctx, textViewResourceId, sites);
//Setup the ImageLoader, we'll use this to display our images
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(ctx).build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
//Setup options for ImageLoader so it will handle caching for us.
options = new DisplayImageOptions.Builder()
.cacheInMemory()
.cacheOnDisc()
.build();
}
#Override
public int getItemViewType(int position) {
if(getItem(position).getType().equals("image")) {
return TYPE_ITEM;
}
else{
return TYPE_SEPARATOR;
}
}
#Override
public int getViewTypeCount() {
return TYPE_MAX_COUNT;
}
public static class ViewHolder {
public ImageView iconImg = null;
public TextView contentTxt = null;
public TextView imageTitleTxt = null ;
public ProgressBar imageIndicator = null ;
public TextView textTitleTxt = null ;
public ProgressBar textIndicator = null;
}
String flag;
//#Override
public View getView(int pos, View convertView, ViewGroup parent){
ViewHolder holder =null;
int type = getItemViewType(pos);
//Log.i("APP", "getView " + pos + " " + convertView + " type = " + type);
View row = convertView;
mInflater = (LayoutInflater) parent.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
try {
if (null == row) {
//No recycled View, we have to inflate one.
holder = new ViewHolder();
switch (type) {
case TYPE_ITEM:
row = (RelativeLayout) mInflater.inflate(R.layout.row_news, null);
break;
case TYPE_SEPARATOR:
row = (RelativeLayout) mInflater.inflate(R.layout.row_news_text, null);
break;
}
//Log.i("APP","holder" + holder);
}
if(type==TYPE_ITEM){
holder = new ViewHolder();
holder.iconImg = (ImageView) row.findViewById(R.id.newsImageView);
holder.imageTitleTxt = (TextView) row.findViewById(R.id.newsTitleText);
holder.imageIndicator = (ProgressBar) row.findViewById(R.id.newsProgressBar);
holder.iconImg.setVisibility(View.INVISIBLE);
holder.imageIndicator.setVisibility(View.VISIBLE);
holder.imageTitleTxt.setVisibility(View.INVISIBLE);
//Setup a listener we can use to swtich from the loading indicator to the Image once it's ready
ImageLoadingListener listener = new ImageLoadingListener() {
#Override
public void onLoadingStarted(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingCancelled(String arg0, View arg1) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String arg0, View arg1, Bitmap arg2) {
}
#Override
public void onLoadingFailed(String arg0, View arg1, FailReason arg2) {
// TODO Auto-generated method stub
}
};
holder.iconImg.setVisibility(View.VISIBLE);
holder.imageIndicator.setVisibility(View.INVISIBLE);
holder.imageTitleTxt.setVisibility(View.VISIBLE);
//Load the image and use our options so caching is handled.
imageLoader.displayImage(getItem(pos).getImgUrl(), holder.iconImg, options, listener);
//Set the relavent text in our TextViews
holder.imageTitleTxt.setText(getItem(pos).getTitle());
}
else if(type==TYPE_SEPARATOR){
holder = new ViewHolder();
holder.contentTxt = (TextView) row.findViewById(R.id.newsTextContentText);
holder.textTitleTxt = (TextView) row.findViewById(R.id.newsTextTitleText);
holder.textIndicator = (ProgressBar) row.findViewById(R.id.newsTextProgressBar);
/*holder.contentTxt.setVisibility(View.INVISIBLE);
holder.textIndicator.setVisibility(View.VISIBLE);
holder.textTitleTxt.setVisibility(View.INVISIBLE);*/
holder.contentTxt.setVisibility(View.VISIBLE);
holder.textIndicator.setVisibility(View.INVISIBLE);
holder.textTitleTxt.setVisibility(View.VISIBLE);
holder.textTitleTxt.setText(getItem(pos).getTitle());
holder.contentTxt.setText(getItem(pos).getContent());
}
}
catch(Exception e){
e.printStackTrace();
}
return row;
}
}
Holder is null. Can you check this using the debugger. Remove the line 172 in com.justduthings.companion.NewsAdapter.
First of all, if (type=="image") or flag != type is not the correct way to compare Strings in Java. See How do I compare strings in Java?. This means that your code won't do what you expect, using the incorrect ifs all the way down
Secondly, for ListViews such as these, with "mixed" item views, there is a much more elegant (and built-in) solution. By implementing getViewTypeCount() (returning 2) and getItemViewType() (returning the type of each item) the framework can keep different recycling lists for the different view types.
This means that you can trust that when you get passed a non-null convertView, it will be one you inflated for the same item type (and you can dispense with the flag!=type check entirely).

How to set onclick parallel with swipe in viewpager?

Here I have developed an app to view full screen images. I was able to develop it with swipe to move to next image. I have used a viewpager element.
How can I use onclick action to viewpager to do something.(delete, share etc..)
My code looks like below,
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen);
Thread child=new Thread(){
#Override
public void run() {
viewPager = (ViewPager) findViewById(R.id.pager);
utils = new Utils(getApplicationContext());
Intent i = getIntent();
int position = i.getIntExtra("position", 0);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this,utils.getFilePaths());
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(position);//show the selected
btnMail=(Button)findViewById(R.id.btnMailThis);
btnRate=(Button)findViewById(R.id.btnRate);
btnMail.setVisibility(View.INVISIBLE);
btnRate.setVisibility(View.INVISIBLE);
}
};
child.start();
}
The FullScreenImageAdapter.java looks like below
public class FullScreenImageAdapter extends PagerAdapter {
private Activity _activity;
private ArrayList<String> _imagePaths;
private LayoutInflater inflater;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this._activity = activity;
this._imagePaths = imagePaths;
}
#Override
public int getCount() {
return this._imagePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
TouchImageView imgDisplay;
//Button btnClose;
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_full_image, container,
false);
imgDisplay = (TouchImageView) viewLayout.findViewById(R.id.imgDisplay);
//btnClose = (Button) viewLayout.findViewById(R.id.btnClose);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(_imagePaths.get(position), options);
imgDisplay.setImageBitmap(bitmap);
/*
// close button click event
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
_activity.finish();
}
});*/
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
Thanks in advance..!
You can create your own class inheriting ViewPager and override onInterceptTouchEvent like this:
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
// TODO Auto-generated method stub
if(arg0.getAction() == MotionEvent.ACTION_UP) {
//Your code here
return false;
} else {
//Do this to keep swipes working. It will also make vertical swiping work. You can avoid the latter by handling MotionEvent action and x,y directions.
return super.onInterceptTouchEvent(arg0);
}
}
Don't forget to replace the ViewPager object in your xml with com.example.yourpackagename.YourViewPagerClass

i am trying to fetch the id of the image to display it in full view

Below is the class where i am not able to get the resource of the image id. I am trying to fetch all the data from the web service. Here i have posted all the classes from where the images are fetched.I have all the images showing it in the gridView. I am not facing problem in that, however when I click on the image of the gridview it shows me the just the xml file which I have called. I guess I am doing wrong somewhere calling the id here in the FullImageAcitivity file.
DefaultGridView.java
public class DefaultGridView extends Activity {
//int position;
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
finish();
}
GridView gridView;
Context context=this;
DisplayImageOptions options;
protected ImageLoader imageLoader = ImageLoader.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.latestphotos);
gridView=(GridView)findViewById(R.id.grid_view);
options = new DisplayImageOptions.Builder()
.showStubImage(R.drawable.stub_image)
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheInMemory()
.cacheOnDisc()
.bitmapConfig(Bitmap.Config.RGB_565)
.build();
gridView.setAdapter(new ImageAdapter());
}
public class ImageAdapter extends BaseAdapter {
LayoutInflater inflater = LayoutInflater.from(context);
public ImageAdapter() {
// TODO Auto-generated constructor stub
imageLoader.init(ImageLoaderConfiguration.createDefault(DefaultGridView.this));
}
#Override
public int getCount() {
return Global.getPhotos_list().size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if(v == null) {
v = inflater.inflate(R.layout.other, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);
Item item = (Item)items.get(i);
picture.setImageResource(item.getDrawable());
name.setText(item.name);
Log.d("position", position+"");
imageLoader.displayImage(Constant.img_URL+Global.getPhotos_list().get(position).get("photo_name"), picture , options,null,context);
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long a) {
Intent i = new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("idkey", position); // pass the id
startActivity(i);
}
});
return v;
}
}
}
FullImageActivity.java
public class FullImageActivity extends Activity {
Button download, setas;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_image);
setas = (Button) findViewById(R.id.setas);
download = (Button)findViewById(R.id.download);
// get intent data
final Intent i = getIntent();
// Selected image id
ImageView imageView = (ImageView) findViewById(R.id.full_image_view);
int id = getIntent().getIntExtra("idkey",-1); //get id
imageView.setImageResource(id);
setas.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
WallpaperManager myWallpaperManager
= WallpaperManager.getInstance(getApplicationContext());
try {
myWallpaperManager.setResource(R.id.full_image_view);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private LayoutInflater inflater;
List<Item> items;
public ImageAdapter(Context context,List<Item> items) {
inflater = LayoutInflater.from(context);
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return items.get(i).drawable;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
View v = view;
ImageView picture;
TextView name;
if(v == null) {
v = inflater.inflate(R.layout.other, viewGroup, false);
v.setTag(R.id.picture, v.findViewById(R.id.picture));
v.setTag(R.id.text, v.findViewById(R.id.text));
}
picture = (ImageView)v.getTag(R.id.picture);
name = (TextView)v.getTag(R.id.text);
Item item = (Item)items.get(i);
picture.setImageResource(item.getDrawable());
name.setText(item.name);
return v;
}
}
Items.java
public class Item {
String name;
int drawable;
public int getDrawable() {
return drawable;
}
public void setDrawable(int drawable) {
this.drawable = drawable;
}
public Item(String name, int id)
{
this.name= name;
this.drawable = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
In gridView item click
Item item =(Item) items.get(position);
int id = item.getDrawable();
Intent i = new Intent(ActivityName.this, FullImageActivity.class);
i.putExtra("idkey", id); // pass the id
startActivity(i);
Then in FullImageActivity
int id = getIntent().getIntExtra("idkey"); //get id
imageview.setImageResource(id); // set the drawable to imageview
You can move the below to onCreate of DefaultFridView
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long a) {
Item item =(Item) items.get(position);
int id = item.getDrawable();
Intent i = new Intent(ActivityName.this, FullImageActivity.class);
i.putExtra("idkey", id); // pass the id
startActivity(i);
}
});
Also you need to have the List in DefaultGridView
List<Item> items = new ArrayList<Item>();
Then
items.add(new Item("One", R.drawable.abstact_one));
items.add(new Item("Two", R.drawable.abstract_three));
items.add(new Item("Three", R.drawable.image_two));
items.add(new Item("Four", R.drawable.image_four));
items.add(new Item("Five", R.drawable.image_five));
items.add(new Item("Six", R.drawable.image_nine));
items.add(new Item("Seven", R.drawable.image_ten));
Then
gridView.setAdapter(new ImageAdapter(),items);
Also i don't understand having the ImageAdapter as separate and as a inner class. WHy do you need both
Try this example my be it is usefull
Grieview Display Full Image

How to show transparent image with instructions over my activity?

I have an activity with some photos, and I'm using ViewPager for swiping those photos. How can I show some transparent image at the activity start, just to show some instructions for swipe and stuff, like ES File Explorer did it on the image below? I have and image, transparent like the one below. I want to show it on top of my first image, and the user can swipe it.
Here's my class:
public class Photo_gallery extends Activity implements OnClickListener{
Button save;
Context mContext;
final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Pictures/Images/");
boolean success = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
mContext = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.photo_gallery);
save = (Button) findViewById(R.id.bSave);
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
final 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);
int currentItem = viewPager.getCurrentItem();
Drawable drawable = mContext.getResources().getDrawable(adapter.mImages[currentItem]);
Bitmap bitmap = ((BitmapDrawable) 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())));
}
});
}
public class ImagePagerAdapter extends PagerAdapter {
public 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
}
}
The simplest solution is probably to use the ShowcaseView library for this.

Categories

Resources