I am trying to create a vertical viewpager with scrollview in one of its fragment. The problem is when i am swiping up, i am not going into second fragment. I have uploaded my code in Github(https://github.com/RajuMandala/verticalviewpager). Please let me know, if i am doing anything wrong. Thanks for your time.
My FirstFragment.java code is below,
public class FirstFragment extends Fragment {
// Scrolling code
private LinearLayout verticalOuterLayout;
private ScrollView verticalScrollview;
private TextView verticalTextView;
private int verticalScrollMax;
private Timer scrollTimer = null;
private TimerTask clickSchedule;
private TimerTask scrollerSchedule;
private TimerTask faceAnimationSchedule;
private int scrollPos = 0;
private Boolean isFaceDown = true;
private Timer clickTimer = null;
private Timer faceTimer = null;
private Button clickedButton = null;
private String[] nameArray = {"Apple", "Banana", "Grapes", "Orange", "Strawberry","Apple", "Banana","Grapes"};
private String[] imageNameArray = {"apple", "banana", "grapes", "orange", "strawberry","apple", "banana","grapes"};
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag,container,false);
// Scrolling code
verticalScrollview = (ScrollView) v.findViewById(R.id.vertical_scrollview_id);
verticalOuterLayout = (LinearLayout) v.findViewById(R.id.vertical_outer_layout_id);
//addImagesToView();
addTextsToView();
ViewTreeObserver vto = verticalOuterLayout.getViewTreeObserver();
/*vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
verticalOuterLayout.getViewTreeObserver().re
getScrollMaxAmount();
startAutoScrolling();
}
});*/
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
//
// mycode
//
if (Build.VERSION.SDK_INT<16) {
removeLayoutListenerPre16(verticalOuterLayout.getViewTreeObserver(),this);
} else {
removeLayoutListenerPost16(verticalOuterLayout.getViewTreeObserver(), this);
}
getScrollMaxAmount();
startAutoScrolling();
}
});
verticalOuterLayout.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
v.getParent().requestDisallowInterceptTouchEvent(true);
return true;
}
});
return v;
}
#SuppressWarnings("deprecation")
private void removeLayoutListenerPre16(ViewTreeObserver observer, ViewTreeObserver.OnGlobalLayoutListener listener){
observer.removeGlobalOnLayoutListener(listener);
}
#TargetApi(16)
private void removeLayoutListenerPost16(ViewTreeObserver observer, ViewTreeObserver.OnGlobalLayoutListener listener){
observer.removeOnGlobalLayoutListener(listener);
}
// Scrolling code
public void addTextsToView(){
for (int i=0;i<nameArray.length;i++){
final TextView textView = new TextView(getActivity());
textView.setText(nameArray[i]);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(256,256);
textView.setLayoutParams(params);
verticalOuterLayout.addView(textView);
}
}
public void getScrollMaxAmount(){
int actualWidth = (verticalOuterLayout.getMeasuredHeight()-(256*3));
verticalScrollMax = actualWidth;
}
public void startAutoScrolling(){
if (scrollTimer == null) {
scrollTimer = new Timer();
final Runnable Timer_Tick = new Runnable() {
public void run() {
moveScrollView();
}
};
if(scrollerSchedule != null){
scrollerSchedule.cancel();
scrollerSchedule = null;
}
scrollerSchedule = new TimerTask(){
#Override
public void run(){
getActivity().runOnUiThread(Timer_Tick);
}
};
scrollTimer.schedule(scrollerSchedule, 30, 30);
}
}
public void moveScrollView(){
scrollPos = (int) (verticalScrollview.getScrollY() + 1.0);
if(scrollPos >= verticalScrollMax){
scrollPos = 0;
}
verticalScrollview.scrollTo(0,scrollPos);
}
public void onDestroy(){
clearTimerTaks(clickSchedule);
clearTimerTaks(scrollerSchedule);
clearTimerTaks(faceAnimationSchedule);
clearTimers(scrollTimer);
clearTimers(clickTimer);
clearTimers(faceTimer);
clickSchedule = null;
scrollerSchedule = null;
faceAnimationSchedule = null;
scrollTimer = null;
clickTimer = null;
faceTimer = null;
super.onDestroy();
}
private void clearTimers(Timer timer){
if(timer != null) {
timer.cancel();
timer = null;
}
}
private void clearTimerTaks(TimerTask timerTask){
if(timerTask != null) {
timerTask.cancel();
timerTask = null;
}
}
}
Please see the screenshot of first fragment below,
Related
I'm making an app that play mp3 file from phone storage using service. I have an activity that has a small view to interact with the songs and a fragment that contains a full media function to interact with the songs will be added in if I tap on the small view told. The problem is I cannot get data from service to pass in the fragment to display data or interact between fragment and service.
Here's my main activity 1st photo
Here's my fragment after touch the field on 1st photo fragment
My code in MainActivity
public class MainActivity extends AppCompatActivity {
private List<AudioModel> mainList;
private ListView mainListView;
private MusicAdapter adapter;
private int REQUEST_CODE_PERMISSION = 2703;
private MusicPlayerService musicPlayerService;
public static Intent intentService;
private boolean boundService = false;
public static TextView txtMainTen, txtMainTacGia;
private ImageButton btnMainPlay, btnMainNext;
private int vitri = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainList = new ArrayList<>();
if(intentService == null){
intentService = new Intent(this, MusicPlayerService.class);
bindService(intentService, serviceConnection, Context.BIND_AUTO_CREATE);
startService(intentService);
}
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION);
mainListView = findViewById(R.id.listSong);
adapter = new MusicAdapter(MainActivity.this, R.layout.item_song, mainList);
mainListView.setAdapter(adapter);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MainAudioCreate(position);
vitri = position;
}
});
txtMainTen = findViewById(R.id.txtPlaying);
txtMainTacGia = findViewById(R.id.txtAuthor);
btnMainPlay = findViewById(R.id.btnPlayBottom);
btnMainNext = findViewById(R.id.btnNextBottom);
btnMainPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (musicPlayerService.mediaPlayer.isPlaying()){
musicPlayerService.pause();
btnMainPlay.setImageResource(R.drawable.button_play);
}
else{
musicPlayerService.resume();
btnMainPlay.setImageResource(R.drawable.button_pause);
}
}
});
btnMainNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vitri++;
if (vitri > mainList.size() - 1){
vitri = 0;
}
MainAudioCreate(vitri);
}
});
}
private void MainAudioCreate(int position){
musicPlayerService.setVitri(position);
musicPlayerService.play();
btnMainPlay.setImageResource(R.drawable.button_pause);
txtMainTen.setText(musicPlayerService.serviceList.get(position).getName());
txtMainTacGia.setText(musicPlayerService.serviceList.get(position).getArtist());
}
public void AddFragment(View view){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = null;
int container = 0;
String tag = "";
switch (view.getId()) {
case R.id.layoutClose:
fragment = new FragmentClose();
container = R.id.frameContent;
tag = "fragClose";
break;
case R.id.layoutList:
fragment = new FragmentPlaylist();
container = R.id.frameContent;
tag = "fragList";
break;
case R.id.bottomPlayerTouchable:
fragment = new FragmentPlayer();
container = R.id.mainFrame;
tag = "fragPlayer";
break;
}
fragmentTransaction.add(container, fragment, tag);
fragmentTransaction.addToBackStack("fragment");
fragmentTransaction.commit();
}
public void GetSongFromStorage(Context context, List<AudioModel> list){
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
String[] projection = {MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE,};
Cursor c = context.getContentResolver().query(uri, projection, null, null, MediaStore.Audio.Media.TITLE + " ASC");
if (c != null){
while (c.moveToNext()) {
AudioModel audioModel = new AudioModel();
String path = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
mmr.setDataSource(path);
String album = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
String artist = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
String name = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
byte[] image = mmr.getEmbeddedPicture();
String displayName = path.substring(path.lastIndexOf("/") + 1);
audioModel.setName(name);
audioModel.setAlbum(album);
audioModel.setArtist(artist);
audioModel.setPath(path);
audioModel.setDisplayname(displayName);
if (image != null) audioModel.setImgPath(image);
list.add(audioModel);
}
adapter.notifyDataSetChanged();
c.close();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_PERMISSION){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
mainList.clear();
GetSongFromStorage(MainActivity.this, mainList);
}
else{
Toast.makeText(this, "Chưa cho phép", Toast.LENGTH_SHORT).show();
}
}
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicPlayerService.MusicBinder binder = (MusicPlayerService.MusicBinder) service;
musicPlayerService = binder.getService();
musicPlayerService.setList(mainList);
boundService = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
boundService = false;
}
};
}
My Service code
public class MusicPlayerService extends Service {
MediaPlayer mediaPlayer;
List<AudioModel> serviceList;
int vitri;
private final IBinder musicBind = new MusicBinder();
public class MusicBinder extends Binder {
MusicPlayerService getService(){
return MusicPlayerService.this;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent) {
mediaPlayer.stop();
mediaPlayer.release();
return false;
}
public void initMusicPlayer(){
mediaPlayer.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
public void onCreate() {
super.onCreate();
vitri = 0;
mediaPlayer = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void setList(List<AudioModel> mp3List){
serviceList = mp3List;
}
public void play(){
mediaPlayer.reset();
createSong();
}
public void pause(){
mediaPlayer.pause();
}
public void resume(){
mediaPlayer.start();
}
public void createSong(){
mediaPlayer = MediaPlayer.create(this, Uri.parse(serviceList.get(vitri).getPath()));
mediaPlayer.start();
}
public void setVitri(int pos){
vitri = pos;
}
}
My Fragment that will be added in code
public class FragmentPlayer extends Fragment {
ImageButton btnBackPlayer;
TextView txtTitlePlayer, txtTimeCurrent, txtTimeTotal;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_player, container, false);
btnBackPlayer = view.findViewById(R.id.btnBackPlayer);
txtTitlePlayer = view.findViewById(R.id.txtTitlePlayer);
txtTimeCurrent = view.findViewById(R.id.txt_timeCurrent);
txtTimeTotal = view.findViewById(R.id.txt_timeTotal);
view.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
btnBackPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().popBackStack();
}
});
return view;
}
}
You can use a broadcast in your service and set broadcast listener in your fragment.
I need to update the textview which is inside view pager adpater's fragment
I have 2 fragments inside viewpager adapter.
and adapter itself is within the fragment.
Main fragment is initialize from MainActivity.
I used Greenrobot approach.for updating textview values on runtime.i get that value but UI is flickering means not getting good UI.
So Shall i used another approach please suggest me.
Adapter Code:-
public class SamplePagerAdapter extends FragmentPagerAdapter {
private final Random random = new Random();
private int mSize = 2;
private int heart_rate;
FragmentManager fm;
public SamplePagerAdapter(FragmentActivity activity, FragmentManager supportFragmentManager, int heart) {
super(supportFragmentManager);
fm = supportFragmentManager;
heart_rate = heart;
}
#Override
public int getCount() {
return mSize;
}
#Override
public Fragment getItem(int position) {
Fragment f = null;
if (position == 0) {
f = new MyFragment();
} else if (position == 1) {
f = new SecondFragment();
}
return f;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
fm.beginTransaction()
.replace(R.id.fragment_container, fragment)
.addToBackStack(null)
.commit();
return true;
}
return false;
}
}
//code for loading main Fragment:-MeasureFragment
private boolean loadFragment(Fragment fragment) {
//switching fragment
if (fragment != null) {
Bundle bundle = new Bundle();
bundle.putString("ble_address",bleAddress);
fragment.setArguments(bundle);
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.fragment_container,fragment)
.addToBackStack(null)
.commit();
return true;
}
return false;
}
//also add measure fragment code:-
public class MeasureFragment extends Fragment implements ISmctAlgoCallback, IBleOperateCallback {
protected boolean measureSwitch = false;
private EcgAlgo ecgAlgo;
private BluetoothLeService mBluetoothLeService;
protected ProgressDialog mProgressDialog;
protected boolean isContecting = false;
private TextView btn_start;
private TextView tv_heartrate, tv_time, tv_pauseorresume;
private RelativeLayout linear, linear1;
private LinearLayout linear_pause, linear_stop;
private CountDownTimer timer;
private int count = 0;
private boolean running;
private Handler handler;
Runnable runnable;
ImageView iv_pauseorresume;
private boolean onclick = true;
private boolean isstop = false;
private String bleAddress;
View view1, view2, view3, view4, view5;
TextView tv_toolbar_title, tv_alarm_setting, tv_battery_percentage;
private int heart_rate;
SamplePagerAdapter samplePagerAdapter;
private FragmentActivity myContext;
ViewPager viewpager;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_measure, container, false);
bleAddress = getArguments().getString("ble_address");
viewpager = (ViewPager) view.findViewById(R.id.viewpager);
CircleIndicator indicator = (CircleIndicator) view.findViewById(R.id.indicator);
btn_start = (TextView) view.findViewById(R.id.btn_start);
linear = (RelativeLayout) view.findViewById(R.id.linear);
linear1 = (RelativeLayout) view.findViewById(R.id.linear1);
linear_pause = (LinearLayout) view.findViewById(R.id.linear_pause);
linear_stop = (LinearLayout) view.findViewById(R.id.linear_stop);
tv_heartrate = (TextView) view.findViewById(R.id.tv_heart_rate);
tv_toolbar_title = (TextView) view.findViewById(R.id.tv_toolbar_title);
tv_alarm_setting = (TextView) view.findViewById(R.id.tv_alarm_setting);
tv_battery_percentage = (TextView) view.findViewById(R.id.tv_battery_percentage);
view1 = (View) view.findViewById(R.id.view1);
view2 = (View) view.findViewById(R.id.view2);
view3 = (View) view.findViewById(R.id.view3);
view4 = (View) view.findViewById(R.id.view4);
view5 = (View) view.findViewById(R.id.view5);
iv_pauseorresume = (ImageView) view.findViewById(R.id.iv_pauseorresume);
tv_pauseorresume = (TextView) view.findViewById(R.id.btn_pause);
tv_time = (TextView) view.findViewById(R.id.time);
ecgAlgo = new EcgAlgo();
ecgAlgo.setISmctAlgoCallback(this);
handler = new Handler();
samplePagerAdapter = new SamplePagerAdapter(getActivity(), getChildFragmentManager(), heart_rate);
viewpager.setAdapter(samplePagerAdapter);
indicator.setViewPager(viewpager);
viewpager.setCurrentItem(0);
linear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (isstop) {
measureSwitch = true;
linear1.setVisibility(View.VISIBLE);
linear.setVisibility(View.GONE);
handler.post(runnable = new Runnable() {
#Override
public void run() {
int hours = count / 3600;
int minutes = (count % 3600) / 60;
int sec = count % 60;
String time = String.format("%02d:%02d:%02d", hours, minutes, sec);
tv_time.setText(time);
if (running) {
count++;
}
handler.postDelayed(this, 1000);
}
});
} else {
connectBle();
running = true;
}
}
});
linear_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ecgAlgo.clearECGParam();
isstop = true;
measureSwitch = false;
count = 0;
handler.removeCallbacks(runnable);
linear1.setVisibility(View.GONE);
linear.setVisibility(View.VISIBLE);
}
});
linear_pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (onclick) {
iv_pauseorresume.setImageResource(R.drawable.resume1);
tv_pauseorresume.setText("Resume");
running = false;
onclick = false;
} else {
onclick = true;
running = true;
iv_pauseorresume.setImageResource(R.drawable.pause);
tv_pauseorresume.setText("Pause");
}
}
});
return view;
}
private void connectBle() {
if (TextUtils.isEmpty(bleAddress)) {// 蓝牙地址为空
showToast(R.string.ble_address_empty);
} else if (mBluetoothLeService != null && !isContecting) {// 蓝牙未连接
showDialog();
mBluetoothLeService.connect(bleAddress);
measureSwitch = true;
} else if (mBluetoothLeService == null) {// 连接服务
connectBleService();
} else {// 其它
disDialog();
showToast(R.string.ble_connect_fail);
}
}
/**
* 连接蓝牙服务
*/
public void connectBleService() {
Intent gattServiceIntent = new Intent(getActivity(), BluetoothLeService.class);
getActivity().bindService(gattServiceIntent, mServiceConnection, BIND_AUTO_CREATE);
}
#Override
public void bleData(short key, short value) {
// TODO Auto-generated method stub
switch (key) {
case SmctConstant.KEY_BLE_CONNECT_STATE:// 连接状态改变
if (SmctConstant.VALUE_BLE_CONNECTED == value) {// 已连接
// hasReConnectCount = 0;
//updateNotification(getString(R.string.notification_nomal));
} else if (SmctConstant.VALUE_BLE_DISCONNECTED == value) {// 连接断开
disDialog();
if (isContecting) {//如果已连接 提示设备以断开连接
showToast(R.string.ble_connect_disconnect);
} else {//没有连接 提示连接失败
//showToast(R.string.ble_connect_fail);
}
isContecting = false;
//changeButtonSate(isContecting);
//changeSwitchView(false);
} else if (SmctConstant.VALUE_BLE_SERVICE_DISCOVERED == value) {// 发现服务
if (mBluetoothLeService != null) {
mBluetoothLeService.setCharacteristic(mBluetoothLeService.getSupportedGattServices(),
SmctConstant.UUID_KEY_DATA_FFE2);
}
disDialog();
isContecting = true;
//changeButtonSate(isContecting);
//changeSwitchView(false);
showToast(R.string.ble_connect_success);
}
break;
case SmctConstant.KEY_DEVICE_POWER_LEVEL:// 电量
//refrashPowerLevel(value);
//Log.d("power leve", "" + value);
break;
case SmctConstant.KEY_DEVICE_ELECTRODE_DROP:// 电极脱落
if (measureSwitch)
showToast("Elctrode Dropout!!!");
break;
case SmctConstant.KEY_ECG_DATA:// ecg数据
// 正在测量中
if (measureSwitch) {
//refrashEcgData(value);
//Log.d("Ecg data", "" + value);
//算法计算
ecgAlgo.addECGParam(value);
}
break;
case SmctConstant.KEY_BODY_POSE:// 姿态
if (value == SmctConstant.VALUE_POSE_WALK) {
//refrashPose("go");
Log.d("pose", "go");
} else if (value == SmctConstant.VALUE_POSE_FALL_DOWN) {
showToast("Falls!!!!!!");
Log.d("pose", "Falls");
} else if (value == SmctConstant.VALUE_POSE_LIE_LOW) {
//refrashPose("Flat lay");
Log.d("pose", "Flat lay");
} else if (value == SmctConstant.VALUE_POSE_STAND) {
//refrashPose("Flat lay");
Log.d("pose", "Standing");
} else if (value == SmctConstant.VALUE_POSE_SIDE_DECUBITUS) {
Log.d("pose", "Standing");
}
break;
}
}
#Override
public void bleData(short key, float[] value) {
if (SmctConstant.KEY_ACC_DATA == key) {
//refreshAccData(value);
}
}
/**
* 算法数据
*/
#Override
public void algoData(final int key, final int value) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
switch (key) {
case SmctConstant.KEY_ALGO_HEART_RATE:// 心率
//tv_heartrate.setText(String.valueOf(value));
//arc_progress.setProgress(value);
//heart_rate=value;
// Bundle bundle = new Bundle();
//bundle.putInt("heart_rate", value);
//fragment.setArguments(bundle);
heart_rate = value;
Bundle bundle=new Bundle();
bundle.putInt("heart_rate",value);
samplePagerAdapter.getItem(0).setArguments(bundle);
//notifyViewPagerDataSetChanged();
break;
case SmctConstant.KEY_ALGO_ARRHYTHMIA:// 心律失常
//tvArr.setText(formatString(R.string.arrhythmia, value));
break;
}
}
});
}
public ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
mBluetoothLeService = ((BluetoothLeService.LocalBinder) service).getService();
if (!mBluetoothLeService.initialize()) {
// LogUtil.e("smctservice", "Unable to initialize Bluetooth");
// mHandler.sendEmptyMessage(MSG_BLE_UNINIT);
} else {
mBluetoothLeService.setBleOperate(MeasureFragment.this);
connectBle();
}
}
#Override
public void onServiceDisconnected(ComponentName componentName) {
// LogUtil.e("smctservice", "onServiceDisconnected");
mBluetoothLeService = null;
}
};
private void notifyViewPagerDataSetChanged() {
Log.d(TAG, "\nnotifyDataSetChanged()");
samplePagerAdapter.notifyDataSetChanged();
}
protected void disDialog() {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (mProgressDialog != null) {
mProgressDialog.dismiss();
linear.setVisibility(View.GONE);
linear1.setVisibility(View.VISIBLE);
//new MyCountDownTimer(System.currentTimeMillis(),1000).start();
}
handler.post(runnable = new Runnable() {
#Override
public void run() {
int hours = count / 3600;
int minutes = (count % 3600) / 60;
int sec = count % 60;
String time = String.format("%02d:%02d:%02d", hours, minutes, sec);
tv_time.setText(time);
if (running) {
count++;
}
handler.postDelayed(this, 1000);
}
});
}
});
}
protected void showToast(String msg) {
ToastUtils.showToast(getActivity(), msg);
}
/**
* 统一显示toast管理
*/
protected void showToast(int id) {
ToastUtils.showToast(getActivity(), getResources().getString(id));
}
/**
* 显示连接蓝牙dialog
*/
protected void showDialog() {
if (mProgressDialog != null && mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
mProgressDialog = null;
}
mProgressDialog = new ProgressDialog(getActivity());
mProgressDialog.setMessage(getResources().getString(R.string.text_conn_ble));
mProgressDialog.setCanceledOnTouchOutside(false);
mProgressDialog.show();
}
}
And need to update textview already discuss.in this fragment.
public class MyFragment extends Fragment {
private int heart_rate;
private ArcProgress arc_progress;
private TextView tv_heartrate;
private Handler handler;
private Runnable runnable;
private View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle saveBundle) {
view = inflater.inflate(R.layout.ecg_layout, container, false);
arc_progress = (ArcProgress) view.findViewById(R.id.arc_progress);
tv_heartrate = (TextView) view.findViewById(R.id.tv_heart_rate);
handler = new Handler();
handler.post(runnable = new Runnable() {
#Override
public void run() {
Log.d("heartrate", "" + heart_rate);
arc_progress.setProgress(heart_rate);
tv_heartrate.setText(String.valueOf(heart_rate));
handler.postDelayed(this, 1000);
}
});
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
}
Hi all I am now integrating youtube API in my app where I have to parse the list of video id's from API then I have to show the videos in a list view when we click on it the video has to be played Until this works fine
There after when the user selects the full-screen mode that is landscape mode I get some errors
public final class VideoGallery extends Fragment implements OnFullscreenListener {
public static Context context;
public static final int ANIMATION_DURATION_MILLIS = 300;
public static final int LANDSCAPE_VIDEO_PADDING_DP = 5;
public final int RECOVERY_DIALOG_REQUEST = 1;
public static VideoListFragment listFragment;
public static VideoFragment videoFragment;
View videoBox;
View view;
View closeButton;
boolean isFullscreen;
public static YouTubePlayer.OnFullscreenListener onFullscreenListener;
static boolean back = false;
FrameLayout relativeLayout;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getContext();
onFullscreenListener = this;
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
relativeLayout = new FrameLayout(getActivity());
inflater.inflate(R.layout.video_list_demo, relativeLayout, true);
MainActivity.headerText.setText("Video Gallery");
listFragment = (VideoGallery.VideoListFragment) getChildFragmentManager().findFragmentById(R.id.list_fragment);
videoFragment = (VideoGallery.VideoFragment) getActivity().getFragmentManager().findFragmentById(R.id.video_fragment_container);
videoBox = relativeLayout.findViewById(R.id.video_box);
closeButton = relativeLayout.findViewById(R.id.close_button);
closeButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listFragment.getListView().clearChoices();
listFragment.getListView().requestLayout();
videoFragment.pause();
ViewPropertyAnimator animator = videoBox.animate()
.translationYBy(videoBox.getHeight())
.setDuration(ANIMATION_DURATION_MILLIS);
runOnAnimationEnd(animator, new Runnable() {
#Override
public void run() {
videoBox.setVisibility(View.INVISIBLE);
}
});
}
});
videoBox.setVisibility(View.INVISIBLE);
layout();
checkYouTubeApi();
return relativeLayout;
}
private void checkYouTubeApi() {
YouTubeInitializationResult errorReason =
YouTubeApiServiceUtil.isYouTubeApiServiceAvailable(context);
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(getActivity(), RECOVERY_DIALOG_REQUEST).show();
} else if (errorReason != YouTubeInitializationResult.SUCCESS) {
String errorMessage =
String.format(getString(R.string.error_player), errorReason.toString());
Toast.makeText(context, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Recreate the activity if user performed a recovery action
getActivity().recreate();
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
layout();
}
#Override
public void onFullscreen(boolean isFullscreen) {
this.isFullscreen = isFullscreen;
layout();
}
private void layout() {
boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
listFragment.getView().setVisibility(isFullscreen ? View.GONE : View.VISIBLE);
listFragment.setLabelVisibility(isPortrait);
closeButton.setVisibility(isPortrait ? View.VISIBLE : View.GONE);
if (isFullscreen) {
videoBox.setTranslationY(0); // Reset any translation that was applied in portrait.
setLayoutSize(videoFragment.getView(), MATCH_PARENT, MATCH_PARENT);
setLayoutSizeAndGravity(videoBox, MATCH_PARENT, MATCH_PARENT, Gravity.TOP | Gravity.LEFT);
} else if (isPortrait) {
setLayoutSize(listFragment.getView(), MATCH_PARENT, MATCH_PARENT);
setLayoutSize(videoFragment.getView(), MATCH_PARENT, WRAP_CONTENT);
setLayoutSizeAndGravity(videoBox, MATCH_PARENT, WRAP_CONTENT, Gravity.BOTTOM);
} else {
videoBox.setTranslationY(0); // Reset any translation that was applied in portrait.
int screenWidth = dpToPx(getResources().getConfiguration().screenWidthDp);
setLayoutSize(listFragment.getView(), screenWidth / 4, MATCH_PARENT);
int videoWidth = screenWidth - screenWidth / 4;
setLayoutSize(videoFragment.getView(), videoWidth, WRAP_CONTENT);
setLayoutSizeAndGravity(videoBox, videoWidth, WRAP_CONTENT,
Gravity.RIGHT | Gravity.CENTER_VERTICAL);
}
}
#TargetApi(16)
private void runOnAnimationEnd(ViewPropertyAnimator animator, final Runnable runnable) {
if (Build.VERSION.SDK_INT >= 16) {
animator.withEndAction(runnable);
} else {
animator.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
runnable.run();
}
});
}
}
public static final class VideoListFragment extends ListFragment {
private static List<VideoEntry> VIDEO_LIST;
private PageAdapter adapter;
private View videoBox;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
callApi();
}
private void callApi() {
new DoGet(this, "videogallery").execute(WebserviceEndpoints.VIDEO_GALLERY);
}
public void handleVideoGalleryResponse(String response) {
try {
List<VideoEntry> list = new ArrayList<VideoEntry>();
if (response.length() > 0) {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.optJSONArray("items");
for (int i = 0; i < array.length(); i++) {
JSONObject data = array.optJSONObject(i);
JSONObject obj = data.optJSONObject("id");
JSONObject obj1 = data.optJSONObject("snippet");
String videoId = obj.optString("videoId");
String videoTitle = obj1.getString("title");
if (!videoId.equals("")) {
list.add(new VideoEntry(videoTitle, videoId));
}
}
VIDEO_LIST = Collections.unmodifiableList(list);
adapter = new PageAdapter(getActivity(), VIDEO_LIST);
setListAdapter(adapter);
}
} catch (Exception e) {
Log.d("", "handleResponse: ", e);
}
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
videoBox = getActivity().findViewById(R.id.video_box);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
String videoId = VIDEO_LIST.get(position).videoId;
back = false;
VideoFragment videoFragment = (VideoFragment) getActivity().getFragmentManager().findFragmentById(R.id.video_fragment_container);
videoFragment.setVideoId(videoId);
if (videoBox.getVisibility() != View.VISIBLE) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
videoBox.setTranslationY(videoBox.getHeight());
}
videoBox.setVisibility(View.VISIBLE);
}
if (videoBox.getTranslationY() > 0) {
videoBox.animate().translationY(0).setDuration(ANIMATION_DURATION_MILLIS);
}
}
#Override
public void onDestroyView() {
super.onDestroyView();
VideoFragment f = (VideoFragment) getActivity().getFragmentManager().findFragmentById(R.id.video_fragment_container);
if (f != null)
getActivity().getFragmentManager().beginTransaction().remove(f).commit();
if (adapter != null)
adapter.releaseLoaders();
}
public void setLabelVisibility(boolean visible) {
if (adapter != null)
adapter.setLabelVisibility(visible);
}
}
private static final class PageAdapter extends BaseAdapter {
private final List<VideoEntry> entries;
private final List<View> entryViews;
private final Map<YouTubeThumbnailView, YouTubeThumbnailLoader> thumbnailViewToLoaderMap;
private final LayoutInflater inflater;
private final ThumbnailListener thumbnailListener;
private boolean labelsVisible;
public PageAdapter(Context context, List<VideoEntry> entries) {
this.entries = entries;
entryViews = new ArrayList<View>();
thumbnailViewToLoaderMap = new HashMap<YouTubeThumbnailView, YouTubeThumbnailLoader>();
inflater = LayoutInflater.from(context);
thumbnailListener = new ThumbnailListener();
labelsVisible = true;
}
public void releaseLoaders() {
for (YouTubeThumbnailLoader loader : thumbnailViewToLoaderMap.values()) {
loader.release();
}
}
public void setLabelVisibility(boolean visible) {
labelsVisible = visible;
for (View view : entryViews) {
view.findViewById(R.id.text).setVisibility(visible ? View.VISIBLE : View.GONE);
}
}
#Override
public int getCount() {
return entries.size();
}
#Override
public VideoEntry getItem(int position) {
return entries.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
VideoEntry entry = entries.get(position);
// There are three cases here
if (view == null) {
// 1) The view has not yet been created - we need to initialize the YouTubeThumbnailView.
view = inflater.inflate(R.layout.video_list_item, parent, false);
YouTubeThumbnailView thumbnail = (YouTubeThumbnailView) view.findViewById(R.id.thumbnail);
thumbnail.setTag(entry.videoId);
thumbnail.initialize("AIzaSyB8BPeIbu5T1-flG4tpEdrHDPI3Rk2VTDY", thumbnailListener);
} else {
YouTubeThumbnailView thumbnail = (YouTubeThumbnailView) view.findViewById(R.id.thumbnail);
YouTubeThumbnailLoader loader = thumbnailViewToLoaderMap.get(thumbnail);
if (loader == null) {
// 2) The view is already created, and is currently being initialized. We store the
// current videoId in the tag.
thumbnail.setTag(entry.videoId);
} else {
// 3) The view is already created and already initialized. Simply set the right videoId
// on the loader.
thumbnail.setImageResource(R.drawable.no_thumbnail);
loader.setVideo(entry.videoId);
}
}
TextView label = ((TextView) view.findViewById(R.id.text));
label.setText(entry.text);
label.setVisibility(labelsVisible ? View.VISIBLE : View.GONE);
return view;
}
private final class ThumbnailListener implements
YouTubeThumbnailView.OnInitializedListener,
YouTubeThumbnailLoader.OnThumbnailLoadedListener {
#Override
public void onInitializationSuccess(
YouTubeThumbnailView view, YouTubeThumbnailLoader loader) {
loader.setOnThumbnailLoadedListener(this);
thumbnailViewToLoaderMap.put(view, loader);
view.setImageResource(R.drawable.no_thumbnail);
String videoId = (String) view.getTag();
loader.setVideo(videoId);
}
#Override
public void onInitializationFailure(
YouTubeThumbnailView view, YouTubeInitializationResult loader) {
view.setImageResource(R.drawable.no_thumbnail);
}
#Override
public void onThumbnailLoaded(YouTubeThumbnailView view, String videoId) {
}
#Override
public void onThumbnailError(YouTubeThumbnailView view, YouTubeThumbnailLoader.ErrorReason errorReason) {
view.setImageResource(R.drawable.no_thumbnail);
}
}
}
public static final class VideoFragment extends YouTubePlayerFragment
implements YouTubePlayer.OnInitializedListener {
private YouTubePlayer player;
private String videoId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initialize("AIzaSyB8BPeIbu5T1-flG4tpEdrHDPI3Rk2VTDY", this);
}
#Override
public void onDestroy() {
if (player != null) {
player.release();
}
super.onDestroy();
}
public void setVideoId(String videoId) {
if (videoId != null && !videoId.equals(this.videoId)) {
this.videoId = videoId;
if (player != null) {
player.cueVideo(videoId);
}
}
}
public void pause() {
if (player != null) {
player.pause();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean restored) {
this.player = player;
player.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CUSTOM_LAYOUT);
player.setOnFullscreenListener(onFullscreenListener);
if (!restored && videoId != null) {
player.cueVideo(videoId);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult result) {
this.player = null;
}
}
private static final class VideoEntry {
private final String text;
private final String videoId;
public VideoEntry(String text, String videoId) {
this.text = text;
this.videoId = videoId;
}
}
private int dpToPx(int dp) {
return (int) (dp * getResources().getDisplayMetrics().density + 0.5f);
}
private static void setLayoutSize(View view, int width, int height) {
ViewGroup.LayoutParams params = view.getLayoutParams();
params.width = width;
params.height = height;
view.setLayoutParams(params);
}
private static void setLayoutSizeAndGravity(View view, int width, int height, int gravity) {
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) view.getLayoutParams();
params.width = width;
params.height = height;
params.gravity = gravity;
view.setLayoutParams(params);
}
}
This is my fragment
The layout file is
<merge xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent">
<fragment
android:id="#+id/list_fragment"
class="com.mycristoparish.Fragments.VideoGallery$VideoListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="?attr/actionBarSize" />
<LinearLayout
android:id="#+id/video_box"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:orientation="vertical">
<ImageButton
android:id="#+id/close_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="#android:drawable/btn_dialog" />
<fragment
android:id="#+id/video_fragment_container"
class="com.mycristoparish.Fragments.VideoGallery$VideoFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</merge>
When I try to play the video in full-screen mode I get the following error
java.lang.IllegalArgumentException: Binary XML file line #42: Duplicate id 0x7f0d0117, tag null, or parent id 0x7f0d0115 with another fragment for com.mycristoparish.Fragments.VideoGallery$VideoFragment
Please guide me how can I move further.
Thanks in advance.
The problem is that you are inflating a layout with a fragment inside a fragment.You cannot do it and so you get the error.However you can dynamically add them.
More details
Note: You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically.
I am developing a welcome screen which will show four slides. I have created the adapter and set it in the activity. Every thing is working fine but the problem is the screen only showing first and third slide. But if I scroll manually I can see all the screens. I am not able to figure out why this is happening.
Here is my activity class:
public class ProgramLandingActivity extends AppCompatActivity implements View.OnClickListener {
private String TAG = ProgramLandingActivity.class.getSimpleName();
ActivityProgramLandingBinding binding;
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private int[] layouts = {
R.drawable.slider3,
R.drawable.slider1,
R.drawable.slider2,
R.drawable.slider4};
private int[] icons = {
R.drawable.note,
R.drawable.mic,
R.drawable.up_arrow,
R.drawable.weight};
private String[] text = {
"Personalized Running Programs \n and flexible calender",
"Audio tips in Hindi and English \n From your mentors,\n Gul Panag and Milind Soman",
"Track your running, see achievements and share daily progress","includes weight loss and running performance nutrition plans"};
private ArrayList<Integer> layoutArray = new ArrayList<Integer>();
private ArrayList<Integer> layouticons = new ArrayList<Integer>();
private ArrayList<String> layouttext = new ArrayList<String>();
private static int currentPage = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this,R.layout.activity_program_landing);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
}
intializeViews();
setAdapter();
}
private void setAdapter() {
for (int i = 0; i < layouts.length; i++) {
layoutArray.add(layouts[i]);
layouticons.add(icons[i]);
layouttext.add(text[i]);
myViewPagerAdapter = new MyViewPagerAdapter(this, layoutArray,layouticons,layouttext);
viewPager.setAdapter(myViewPagerAdapter);
CirclePageIndicator indicator = (CirclePageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(viewPager);
Log.d("laypou_length", String.valueOf(layouts.length));
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == layouts.length) {
currentPage = 0;
}
viewPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 2500, 2500);
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener(){
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
private void intializeViews() {
viewPager = (ViewPager) findViewById(R.id.view_pager);
}
My adapter class:
class MyViewPagerAdapter extends PagerAdapter {
private ArrayList<Integer> layouts;
private ArrayList<Integer> icons;
private ArrayList<String> text;
private LayoutInflater inflater;
private Context context;
public MyViewPagerAdapter(Context context,ArrayList<Integer> layouts, ArrayList<Integer> icons,ArrayList<String> text ) {
this.context = context;
this.layouts=layouts;
this.icons = icons;
this.text=text;
inflater = LayoutInflater.from(context);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View myImageLayout = inflater.inflate(R.layout.slider,container,false);
ImageView myImage = (ImageView) myImageLayout.findViewById(R.id.image1);
ImageView icon = (ImageView)myImageLayout.findViewById(R.id.icon);
TextViewWithFont slider_text = (TextViewWithFont)myImageLayout.findViewById(R.id.text_program_landing_body);
myImage.setImageResource(layouts.get(position));
icon.setImageResource(icons.get(position));
slider_text.setText(text.get(position));
container.addView(myImageLayout, 0);
return myImageLayout;
}
#Override
public int getCount() {
return layouts.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
Can someone tell me what I am doing wrong?
try this
you can user time for auto scroll like this
Timer timer;
timer = new Timer();
timer.scheduleAtFixedRate(new RemindTask(), 0, 3000); // delay*/
private class RemindTask extends TimerTask {
int current = viewPager.getCurrentItem();
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if (current < layouts.length) {
viewPager.setCurrentItem(current);
current += 1;
} else {
timer.cancel();
}
}
});
}
}
Looks like the problem is in the 'viewpager.setCurrentPage' put prints for the 'currentPage' there and see if it is getting called twice.
Let me know the observation in the comments.
Cheers :)
am building an open source project, here is its link
http://slidese.github.io/slidese/2013/11/25/update_listview_item.html
I've imported all library projects which it is using into eclipse. All are fine except PullToRefresh library. it is giving me the error "PullToRefreshAttacher.OnRefreshListener cannot be resolved to a type" where fragment implements it
2nd error is at
mPullToRefreshAttacher.addRefreshableView(mListview, this);
it says "The method addRefreshableView(View, ViewDelegate) in the type PullToRefreshAttacher is not applicable for the arguments (ListView, ContentFragment)"
3rd error is at
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
It is asking me to remove override annotation. here is complete code of fragment.
public class ContentFragment extends Fragment implements PullToRefreshAttacher.OnRefreshListener {
private final String TAG = "ContentFragment";
public static final String CONTENT_MODE = "content_mode";
public static final int MODE_ADFREE = 0;
public static final int MODE_PREMIUM = 1;
private StartActivity mListener;
private PullToRefreshAttacher mPullToRefreshAttacher;
private UpdaterAsyncTask mUpdater;
private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE;
ListView mListview;
Button mPlayButton;
ContentAdapter mAdapter;
int mMode;
Map<String, UpdateHolder> mUpdates = new HashMap<String, UpdateHolder>();
public ContentFragment() {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (StartActivity) activity;
Log.d(TAG, "Attached podcast list fragment");
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must be the StartActivity");
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_content, null);
mListview = (ListView) view.findViewById(android.R.id.list);
mListview.setEmptyView(view.findViewById(R.id.empty_list_view));
mListview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListview.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.contextual_menu_content, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
if (item.getItemId() == R.id.action_delete) {
SparseBooleanArray checked = mListview.getCheckedItemPositions();
Content[] params = new Content[checked.size()];
int index = 0;
int first = mListview.getFirstVisiblePosition();
int last = mListview.getLastVisiblePosition();
for (int i = 0; i < mListview.getCount(); i++) {
if (checked.get(i)) {
params[index++] = (Content)mListview.getItemAtPosition(i);
if (i >= first && i <= last) {
View view = mListview.getChildAt(i-first);
Animation animation = AnimationUtils.loadAnimation(getActivity(), android.R.anim.slide_out_right);
animation.setDuration(200);
//animation.setFillAfter(true);
animation.setStartOffset(100 * (index) );
view.startAnimation(animation);
}
}
}
new AsyncTask<Content, Void, Void>() {
#Override
protected Void doInBackground(Content... params) {
for (Content content : params) {
File file = Utils.getFilepath(content.getFilename());
file.delete();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
mAdapter.notifyDataSetChanged();
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, params);
mode.finish();
return true;
}
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
});
mListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
Content content = mAdapter.getItem(position);
mListener.showContentDetails(content);
}
});
mListview.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mScrollState = scrollState;
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
}
});
mPullToRefreshAttacher = ((StartActivity) getActivity()).getPullToRefreshAttacher();
mPullToRefreshAttacher.addRefreshableView(mListview, this);
mMode = getArguments().getInt(CONTENT_MODE);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
#Override
public void onPause() {
super.onPause();
if (mUpdater != null)
mUpdater.stop();
}
#Override
public void onResume() {
super.onResume();
updateAdapter();
mUpdater = new UpdaterAsyncTask();
mUpdater.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, (Void)null);
}
public void refresh() {
updateAdapter();
}
public void replaceCurrentlyPlayingContent() {
GlobalContext.INSTANCE.replaceCurrentlyPLayingContent(mAdapter.getObjects(), mListener.getCurrentTrack());
}
private void updateAdapter() {
Log.d(TAG, "updateAdapter");
//new FetchContentAsyncTask(mMode).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
final String mp3 = mListener.getSavedStateMp3();
final boolean isPlaying = mListener.getSavedStateIsPlaying();
final boolean isPaused = mListener.getSavedStateIsPaused();
List<Content> listOfContent = GlobalContext.INSTANCE.getCachedContent(mMode, mp3, isPlaying, isPaused);
mAdapter = new ContentAdapter(getActivity(), R.layout.list_item_card, listOfContent);
mListview.setAdapter(mAdapter);
}
#Override
public void onRefreshStarted(View view) {
Intent intent = new Intent(getActivity(), DownloaderService.class);
intent.putExtra(DownloaderService.EXTRA_USER_INITIATED, true);
getActivity().startService(intent);
}
private class UpdaterAsyncTask extends AsyncTask<Void, Void, Void> {
boolean isRunning = true;
public void stop() {
isRunning = false;
}
#Override
protected Void doInBackground(Void... params) {
while (isRunning) {
/*
Map<String, UpdateHolder> map = gatherMetadata();
publishProgress(map);
*/
updateCurrentAdapterContent();
publishProgress();
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... params) {
super.onProgressUpdate();
if (mScrollState == OnScrollListener.SCROLL_STATE_IDLE) {
// http://stackoverflow.com/questions/2123083/android-listview-refresh-single-row
int start = mListview.getFirstVisiblePosition();
for(int i = start, j = mListview.getLastVisiblePosition(); i<=j; i++) {
View view = mListview.getChildAt(i-start);
if (((Content)mListview.getItemAtPosition(i)).dirty) {
Log.v(TAG, "Content is dirty");
mListview.getAdapter().getView(i, view, mListview);
}
}
}
}
}
private void updateCurrentAdapterContent() {
List<Content> listOfContent = mAdapter.getObjects();
Map<String, UpdateHolder> map = new HashMap<String, UpdateHolder>();
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterByStatus(DownloadManager.STATUS_PENDING | DownloadManager.STATUS_RUNNING);
try {
Cursor cursor = ContentDownloadManager.INSTANCE.query(q);
while (cursor.moveToNext()) {
//long id = cursor.getLong(cursor.getColumnIndex(DownloadManager.COLUMN_ID));
String uri = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_URI));
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
int downloaded = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
int total = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
float progress = (float)downloaded/(float)total;
UpdateHolder holder = new UpdateHolder();
holder.progress = progress;
holder.status = status;
map.put(uri, holder);
}
cursor.close();
final Content currentContent = mListener.getCurrentTrack();
final boolean isPlaying = mListener.isPlaying();
final boolean isPaused = mListener.isPaused();
for (Content content : listOfContent) {
// First update any download progress we might have for this specific content item
UpdateHolder holder = map.get(content.mp3);
if (holder != null) {
if (content.downloadProgress != holder.progress) {
content.downloadProgress = holder.progress;
content.dirty = true;
}
if (content.downloadStatus != holder.status) {
content.downloadStatus = holder.status;
content.dirty = true;
}
}
else {
if (content.downloadProgress != 0f) {
content.downloadProgress = 0f;
content.dirty = true;
}
if (content.downloadStatus != -1) {
content.downloadStatus = -1;
content.dirty = true;
}
}
// Update with elapsed (to be done)
// File exists?
File file = Utils.getFilepath(content.getFilename());
if (content.exists != file.exists()) {
content.exists = file.exists();
content.dirty = true;
}
// Is this the currently playing content
if (currentContent != null && content.mp3.equals(currentContent.mp3)) {
if (content.isPlaying != isPlaying) {
content.isPlaying = isPlaying;
content.dirty = true;
}
if (content.isPaused != isPaused) {
content.isPaused = isPaused;
content.dirty = true;
}
}
else {
if (content.isPlaying != false) {
content.isPlaying = false;
content.dirty = true;
}
if (content.isPaused != false) {
content.isPaused = false;
content.dirty = true;
}
}
if (content.dirty) {
DatabaseManager.getInstance().createOrUpdateContent(content);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
public class UpdateHolder {
public String mp3;
public int status;
public boolean played;
public float progress;
public boolean exists = false;
public boolean isPlaying = false;
public boolean isPaused = false;
//public int elapsed;
//public int duration;
}
}
I couldn't find the issue in it. I'm stuck here for last 40 hours. Please help. Thank you!
Maybe you are using old version of the library. I found that PullToRefreshAttacher doesn't contain OnRefreshListener. (https://github.com/chrisbanes/ActionBar-PullToRefresh/blob/master/library/src/main/java/uk/co/senab/actionbarpulltorefresh/library/PullToRefreshAttacher.java)
Try to import uk.co.senab.actionbarpulltorefresh.library.listeners.OnRefreshListener; and use it instead of PullToRefreshAttacher.OnRefreshListener.