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()?
Related
I am implementing a music player app. I am able to fetch the songs from the sd card. But stuck in something from hours i.e. I am unable to make the songs play inside the fragment.
Here is the MainActivity class which is having 3 tab fragments.
public class MainActivity extends AppCompatActivity {
private final String[] TITLES = {"Now playing", "Library", "Groups"};
private static boolean isInForeground = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//if (savedInstanceState == null) {}
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Initialize the ViewPager and set an adapter
ViewPager pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new PagerAdapter(getSupportFragmentManager(), getBaseContext()));
// Bind the tabs to the ViewPager
PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setShouldExpand(true);
tabs.setViewPager(pager);
//Whenever the user changes tab, we want the title to change too
tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int position) {
setTitle(TITLES[position]);
}
});
//We want to have the library as default view
pager.setCurrentItem(1);
setTitle(TITLES[1]);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class MainFragment extends Fragment {
public MainFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_song_library, container, false);
return view;
}
}
public class PagerAdapter extends FragmentPagerAdapter
implements PagerSlidingTabStrip.CustomTabProvider {
private ArrayList<Integer> tab_icon = new ArrayList<Integer>();
Context myContext;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
myContext = context;
tab_icon.add(context.getResources().getIdentifier("ic_play_arrow_white_36dp", "drawable", context.getPackageName()));
tab_icon.add(context.getResources().getIdentifier("ic_list_white_36dp", "drawable", context.getPackageName()));
tab_icon.add(context.getResources().getIdentifier("ic_group_white_36dp", "drawable", context.getPackageName()));
}
#Override
public CharSequence getPageTitle(int position) {
return TITLES[position];
}
#Override
public int getCount() {
return TITLES.length;
}
#Override
public Fragment getItem(int position) {
if(position == 0){
return SongNowPlayingFragment.newInstance();
} else if (position == 1){
return SongLibraryFragment.newInstance();
} else if(position == 2){
return GroupFragment.newInstance();
}
System.err.println("Invalid tab fragment!");
return new Fragment();
}
#Override
public View getCustomTabView(ViewGroup viewGroup, int position) {
LinearLayout imageView = (LinearLayout) LayoutInflater.from(myContext)
.inflate(R.layout.tab_layout, null, false);
ImageView tabImage = (ImageView) imageView.findViewById(R.id.tabImage);
tabImage.setImageResource(tab_icon.get(position));
return imageView;
}
}
#Override
protected void onResume()
{
super.onResume();
isInForeground = true;
}
#Override
protected void onPause()
{
super.onPause();
isInForeground = false;
}
static boolean isInForeground(){
return isInForeground;
}
}
This is the SongLibraryFragment in which I have added the songs from the user device. Now I want to play those songs.
public class SongLibraryFragment extends Fragment implements MediaPlayerControl {
private ArrayList<SongItem> songList;
private ListView songView;
private MusicService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
private MusicController controller;
private boolean paused=false, playbackPaused=false;
private MainActivity mainActivity = null;
public static SongLibraryFragment newInstance() {
SongLibraryFragment f = new SongLibraryFragment();
Bundle b = new Bundle();
f.setArguments(b);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_song_library, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mainActivity = (MainActivity) SongLibraryFragment.this.getActivity();
songView = (ListView) getView().findViewById(R.id.library_song_list);
songList = new ArrayList<SongItem>();
getSongList();
SongAdapter songAdt = new SongAdapter(getActivity(), songList);
songView.setAdapter(songAdt);
Collections.sort(songList, new Comparator<SongItem>() {
public int compare(SongItem a, SongItem b) {
return a.getTitle().compareTo(b.getTitle());
}
});
setController();
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
#Override
public void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(getActivity(), MusicService.class);
this.getActivity().bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
this.getActivity().startService(playIntent);
}
}
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
public void getSongList() {
//retrieve song info
ContentResolver musicResolver = getActivity().getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if(musicCursor!=null && musicCursor.moveToFirst()){
//get columns
int titleColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex
(android.provider.MediaStore.Audio.Media.ARTIST);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new SongItem(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getPosn();
else return 0;
}
#Override
public int getDuration() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getDur();
else return 0;
}
#Override
public boolean isPlaying() {
if(musicSrv!=null && musicBound)
return musicSrv.isPng();
return false;
}
#Override
public void pause() {
playbackPaused=true;
musicSrv.pausePlayer();
}
#Override
public void seekTo(int pos) {
musicSrv.seek(pos);
}
#Override
public void start() {
musicSrv.go();
}
private void setController(){
//set the controller up
controller = new MusicController(getActivity());
controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
playPrev();
}
});
controller.setMediaPlayer(this);
controller.setAnchorView(getActivity().findViewById(R.id.library_song_list));
controller.setEnabled(true);
}
//play next
private void playNext(){
musicSrv.playNext();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
//play previous
private void playPrev(){
musicSrv.playPrev();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
#Override
public void onPause(){
super.onPause();
paused=true;
}
#Override
public void onResume(){
super.onResume();
if(paused){
setController();
paused=false;
}
}
#Override
public void onStop() {
controller.hide();
super.onStop();
}
#Override
public void onDestroy() {
this.getActivity().stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
SongAdapter class
public class SongAdapter extends BaseAdapter {
private ArrayList<SongItem> songs;
private LayoutInflater songInf;
public SongAdapter(Context c, ArrayList<SongItem> theSongs){
songs=theSongs;
songInf=LayoutInflater.from(c);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return songs.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//map to song layout
LinearLayout songLay = (LinearLayout)songInf.inflate
(R.layout.song, parent, false);
//get title and artist views
TextView songView = (TextView)songLay.findViewById(R.id.song_title);
TextView artistView = (TextView)songLay.findViewById(R.id.song_artist);
//ImageView imageView = (ImageView)songLay.findViewById(R.id.song_image);
//get song using position
SongItem currSong = songs.get(position);
//get title and artist strings
songView.setText(currSong.getTitle());
artistView.setText(currSong.getArtist());
//imageView.setImage(currSong.getImage());
//set position as tag
songLay.setTag(position);
return songLay;
}
Song.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp"
android:onClick="songPicked">
<TextView
android:id="#+id/song_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
style="#style/Base.TextAppearance.AppCompat.Title"
android:textColor="#color/primary_text_default_material_light"/>
<TextView
android:id="#+id/song_artist"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
style="#style/Base.TextAppearance.AppCompat.Subhead"
android:textColor="#color/secondary_text_default_material_light"/>
</LinearLayout>
Error
java.lang.IllegalStateException: Could not find a method
songPicked(View) in the activity class
co.adrianblan.noraoke.MainActivity for onClick handler on view class
android.widget.LinearLayout
So the main problem is with the songPicked method inside SongFragmentLibrary. I have added the onClick: songPicked in the song.xml file but it is searching for the songPicked method inside the MainActivity. I am not getting what is the problem.
Please can anyone help me with this?
You are trying to set onclick listener from your fragment xml android:onClick="songPicked", you can't set onclick listener for a view which is part of fragment, in your getView() setOnClickListener:
LinearLayout songLay = (LinearLayout)songInf.inflate
(R.layout.song, parent, false);
songLay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//Handle click event
}
})
OR
You can simply set OnItemClickListener on your listview
list.setOnItemClickListener(this);// implement OnItemClickListener in your fragment class
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.
I need to get the selected contacts from the SelectContactsActivity and display those selected contacts in ContactListActivity. But i am not getting the contacts which i selected.
my SelectContactsActivity.java
public class SelectContactsActivity extends Activity{
private ListView select_listView;
private EditText search_edt;
private List<ContactBean> list = new ArrayList<ContactBean>();
private ContanctAdapter objAdapter;
//private boolean UpdateAB;
private String groupName;
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.activity_selectcontacts);
select_listView = (ListView) findViewById(R.id.select_contacts_listView);
search_edt = (EditText) findViewById(R.id.inputSearch);
Intent intent = getIntent();
groupName = intent.getStringExtra("group_name");
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,null, null);
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
ContactBean objContact = new ContactBean();
objContact.setName(name);
objContact.setPhoneNo(phoneNumber);
list.add(objContact);
}
phones.close();
objAdapter = new ContanctAdapter(SelectContactsActivity.this, R.layout.select_contacts_list_item, list, updateAB);
select_listView.setAdapter(objAdapter);
objAdapter.setEditMode(true);
if (null != list && list.size() != 0) {
Collections.sort(list, new Comparator<ContactBean>() {
#Override
public int compare(ContactBean lhs, ContactBean rhs) {
return lhs.getName().compareTo(rhs.getName());
}
});
} else {
showToast("No Contact Found!!!");
}
select_listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> listview, View v,
int position, long id) {
// TODO Auto-generated method stub
objAdapter.setChecked(position, v);
objAdapter.notifyDataSetChanged();
invalidateOptionsMenu();
}
});
/**
* Enabling Search Filter
* */
// Capture Text in EditText
search_edt.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = search_edt.getText().toString().toLowerCase(Locale.getDefault());
objAdapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
private void showToast(String msg) {
// TODO Auto-generated method stub
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
objAdapter.setEditMode(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.actions_select_contacts_list, menu);
MenuItem item = null;
if (select_listView.getCount() > 0) {
if(objAdapter.isCheckItem()){
menu.findItem(R.id.action_done).setEnabled(true).setVisible(true);
item = menu.add(Menu.NONE, R.id.action_done, Menu.NONE,R.string.done);
}else{
menu.findItem(R.id.action_done).setEnabled(false).setVisible(false);
}
}else{
menu.findItem(R.id.action_done).setEnabled(false).setVisible(false);
}
Log.v(this.getClass().getName(), "Check update..."+objAdapter.isCheckItem());
return true;
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch (item.getItemId()) {
case R.id.action_done:
StringBuilder _itemBuilder = new StringBuilder();
objAdapter.saveSelected(groupName);
invalidateOptionsMenu();
finish();
break;
}
return true;
}
Handler updateAB = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
invalidateOptionsMenu();
Log.v(SelectContactsActivity.this.getClass().getName(), "Check invalidate cal;l");
}
};
}
My ContanctAdapter.java
public class ContanctAdapter extends ArrayAdapter<ContactBean> {
public Context mcontext;
private List<ContactBean> items;
private ContactBean objBean;
private boolean isEdit;
private ArrayList<ContactBean> arraylist;
public boolean[] contactCheckArray;
private LayoutInflater inflater;
public ContanctAdapter(Activity act, int row, List<ContactBean> items, Handler handler) {
super(act, row, items);
this.mcontext = act;
inflater = LayoutInflater.from(act);
this.items = items;
this.arraylist = new ArrayList<ContactBean>();
this.arraylist.addAll(items);
contactCheckArray = new boolean[items.size()];
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final View view = null==convertView?inflater.inflate(R.layout.select_contacts_list_item, null):convertView;
ViewHolder holder = null;
if (null == view.getTag()) {
holder = new ViewHolder();
holder.tvname = (TextView) view.findViewById(R.id.tvname);
holder.tvPhoneNo = (TextView) view.findViewById(R.id.tvphone);
holder.iv = (ImageView)view.findViewById(R.id.contacts_imageview);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
objBean = items.get(position);
if (holder.tvname != null && null != objBean.getName() && objBean.getName().trim().length() > 0) {
holder.tvname.setText(Html.fromHtml(objBean.getName()));
}
if (holder.tvPhoneNo != null && null != objBean.getPhoneNo()
&& objBean.getPhoneNo().trim().length() > 0) {
holder.tvPhoneNo.setText(Html.fromHtml(objBean.getPhoneNo()));
}
if (isEdit) {
holder.iv.setVisibility(View.VISIBLE);
} else {
holder.iv.setVisibility(View.GONE);
}
return view;
}
public void setEditMode(boolean isEdit) {
this.isEdit = isEdit;
}
public boolean isCheckItem () {
for (boolean value : contactCheckArray) {
if (value)
return true;
}
return false;
}
public void setChecked(final int pos, final View row) {
if (!contactCheckArray[pos]) {
((ViewHolder) row.getTag()).iv.setImageResource(R.drawable.setting_check);
contactCheckArray[pos] = true;
notifyDataSetChanged();
} else {
contactCheckArray[pos] = false;
((ViewHolder) row.getTag()).iv.setImageResource(R.drawable.setting_check_box_bg);
notifyDataSetChanged();
}
}
public class ViewHolder {
public ImageView iv;
public TextView tvname, tvPhoneNo;
}
public void saveSelected(String groupName){
StringBuilder _itemBuilder = new StringBuilder();
ProfilesDatabaseHelper DbHelper = new ProfilesDatabaseHelper(mcontext);
for (int i = 0; i < arraylist.size(); i++) {
if (contactCheckArray[i]) {
_itemBuilder.append("'"+ arraylist.get(i).getPhoneNo() + "'" + ",");
//Toast.makeText(mcontext, "Selected Contacts : "+_itemBuilder.toString(), Toast.LENGTH_LONG).show();
DbHelper.executeSQL("INSERT INTO GroupsTable (GroupName, ContactName, PhoneNumber) VALUES ('"+groupName+"', '"+arraylist.get(i).getName()+"','"+ arraylist.get(i).getPhoneNo()+ "')");
}
}
if (_itemBuilder.length() > 0) {
_itemBuilder.deleteCharAt(_itemBuilder.length() - 1);
Log.v(getClass().getName(), "Check..selected contactss :"+ _itemBuilder.toString());
//Toast.makeText(getApplicationContext(), "Selected Contacts : "+_itemBuilder.toString(), Toast.LENGTH_LONG).show();
// This will clear the buffer
_itemBuilder.delete(0, _itemBuilder.length());
}
}
public void filter(String charText ) {
// TODO Auto-generated method stub
charText = charText.toLowerCase(Locale.getDefault());
items.clear();
if (charText.length() == 0) {
items.addAll(arraylist);
}else {
for (ContactBean ob : arraylist) {
if (ob.getName().toLowerCase(Locale.getDefault()).contains(charText)) {
items.add(ob);
}
}
}
notifyDataSetChanged();
}
}
And if i click on the first item in SelectContactsList activity automatically my 9th and 17th and 25th, 33.... contacts also selected and its returning one contact which i didn't select to the Contactslist activity. And i am not getting any errors. Any one help me to solve this issue.
Your issue is with this line in the first snippet, in your listener.
objAdapter.setChecked(position, v);
POSITION is different from ID. A ListView only renders the number of items that it needs to show. The position is the position in the rendered list.
Change it to id.
See this post as well for a better explanation of this with in-depth examples: Create a ListView with selectable rows/change background color of ListView rows when clicked
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 have a ViewPager / PagerAdapter which should allow me to swipe through a series of footer images in order to change the station (by changing the string PLAYLIST):
...however when I swipe through the images - nothing seems to happen.
Any suggestions are greatly appreciated!
SOURCE:
public class Home extends YouTubeBaseActivity implements
VideoClickListener {
private VideosListView listView;
private ActionBarDrawerToggle actionBarDrawerToggle;
public static final String API_KEY = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX";
public static final String VIDEO_ID = "o7VVHhK9zf0";
private int mCurrentTabPosition = NO_CURRENT_POSITION;
private static final int NO_CURRENT_POSITION = -1;
private DrawerLayout drawerLayout;
private ListView drawerListView;
private String[] drawerListViewItems;
private ViewPager mPager;
ScrollView mainScrollView;
Button fav_up_btn1;
Button fav_dwn_btn1;
String TAG = "DEBUG THIS";
String PLAYLIST = "EminemVEVO";
private OnPageChangeListener mPageChangeListener;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
final ActionBar actionBar = getActionBar();
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
actionBar.setCustomView(R.layout.actionbar_custom_view_home);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
drawerListViewItems = getResources().getStringArray(R.array.items);
drawerListView = (ListView) findViewById(R.id.left_drawer);
drawerListView.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_listview_item, drawerListViewItems));
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
actionBarDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */
drawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
);
drawerLayout.setDrawerListener(actionBarDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true);
drawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
GravityCompat.START);
mainScrollView = (ScrollView) findViewById(R.id.groupScrollView);
listView = (VideosListView) findViewById(R.id.videosListView);
listView.setOnVideoClickListener(this);
new GetYouTubeUserVideosTask(responseHandler, PLAYLIST).execute();
}
Handler responseHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
populateListWithVideos(msg);
};
};
private void populateListWithVideos(Message msg) {
Library lib = (Library) msg.getData().get(
GetYouTubeUserVideosTask.LIBRARY);
listView.setVideos(lib.getVideos());
}
#Override
protected void onStop() {
responseHandler = null;
super.onStop();
}
#Override
public void onVideoClicked(Video video) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse(video.getUrl()));
startActivity(intent);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
actionBarDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (actionBarDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
private class ImagePagerAdapter extends PagerAdapter {
public ImagePagerAdapter() {
super();
}
private int[] mImages = new int[] { R.drawable.selstation_up_btn,
R.drawable.classical_up_btn, R.drawable.country_up_btn,
R.drawable.dance_up_btn, R.drawable.hiphop_up_btn };
#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 = Home.this;
ImageView imageView = new ImageView(context);
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);
}
private final ViewPager.SimpleOnPageChangeListener mPageChangeListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(final int position) {
onTabChanged(mPager.getAdapter(), mCurrentTabPosition, position);
mCurrentTabPosition = position;
}
};
protected void onTabChanged(final PagerAdapter adapter,
final int oldPosition, final int newPosition) {
if (oldPosition > newPosition) {
// left to right
} else {
// right to left
String PLAYLIST = "TimMcGrawVEVO";
View vg = findViewById(R.layout.home);
vg.invalidate();
}
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setOnPageChangeListener(new OnPageChangeListener() {
int oldPos = viewPager.getCurrentItem();
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
if (position > oldPos) {
// Moving to the right
} else if (position < oldPos) {
// Moving to the Left
String PLAYLIST = "TimMcGrawVEVO";
View vg = findViewById(R.layout.home);
vg.invalidate();
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
}
});
}
}
}
You're not adding the Listener to your Pager.
You need to call setOnPageChangeListener(mPageChangeListener) on your pagerAdapter.
For example in the Constructor:
public ImagePagerAdapter(){
super();
setOnPageChangeListener(mPageChangeListener);
}
for more info, check the docs. http://developer.android.com/reference/android/support/v4/view/ViewPager.html