Related
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);
}
}
I have 2 Activities in my application.
activityMain contain 3 Fragments
The third fragment is a conversations list. This is a recylerView where each Item leads to a specific chat.
activityConversation contains a Chat.
First, i would like to sort the conversations in the the recyclerView in order of "Last actives". The most recent active should be displayed on top of the list, the second last active on second postition etc...
Secondly, each Item of the recyclerView contains a Textview. For each item, I would like to display the last message posted in the related chat in this Texview.
Finally, i would like to display these Item textViews in Bold since the conversation has not been opened until the last chat update.
Has anyone an Idea to help me achieve that?
Here my Chat Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_conversation);
getWindow().setBackgroundDrawableResource(R.drawable._background_black_lchatxxxhdpi) ;
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.open, R.string.close);
mDrawerLayout.addDrawerListener(mToggle);
mToggle.syncState();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
LinearLayout leftNav = (LinearLayout)findViewById(R.id.conv_left_nav);
LinearLayout helperAdmin = (LinearLayout) getLayoutInflater().inflate(R.layout.list_participant_admin, leftNav, false);
leftNav.addView(helperAdmin);
final EditText input_post = (EditText)findViewById(R.id.input_post);
context = this;
input_post.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
ImageButton btn_submit = (ImageButton)findViewById(R.id.btn_submit);
btn_submit.setEnabled(!TextUtils.isEmpty(s.toString().trim()));
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
Intent intent = getIntent();
if (intent.hasExtra("conversationId"))
conversationId = intent.getStringExtra("conversationId");
rpcHelper = new RPCHelper(context, this);
String unique_device_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
Log.i("US", unique_device_id);
rpcHelper.loginOrRegister(unique_device_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
refreshConversation();
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
dbHelper = new DataBaseHelper(context, "us", null, Statics.DB_VERSION);
userInConv = dbHelper.dbReader.getUserInConversation(Integer.parseInt(conversationId));
storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
leftRecycler = (RecyclerView) helperAdmin.findViewById(R.id.conv_left_recycler);
//mRecyclerView.setHasFixedSize(true);
// use a linear layout manager
leftLayoutManager = new LinearLayoutManager(this);
leftRecycler.setLayoutManager(leftLayoutManager);
leftAdapter = new ConvLeftAdapter(userInConv, storageDir, Integer.parseInt(conversationId));
leftRecycler.setAdapter(leftAdapter);
helpersImg = new View[3];
helpers = new DataBaseReader.User[3];
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(this, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
IntentFilter filter = new IntentFilter(Statics.ACTION_NEW_POST);
this.registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context ctx, Intent intent) {
Log.d("new", " message");
refreshConversation();
}
}, filter);
}
#Override
public void onNewIntent(Intent intent){
if (intent.hasExtra("conversationId"))
conversationId = intent.getStringExtra("conversationId");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_conversation, menu);
DataBaseReader.Conversation conversation = dbHelper.dbReader.getConversation(conversationId);
DataBaseReader.User owner = dbHelper.dbReader.getConversationOwner(conversationId);
final ImageView owner_img = (ImageView)findViewById(R.id.img_userprofilpic);
TextView owner_name = (TextView)findViewById(R.id.lbl_username_owner);
TextView owner_city = (TextView)findViewById(R.id.lbl_usercity_owner);
TextView conversation_question = (TextView)findViewById(R.id.question_text);
owner_name.setText(owner.name);
owner_city.setText(owner.city);
conversation_question.setText(conversation.question.text);
conversation_question.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView text = (TextView)findViewById(R.id.question_text);
int maxLines = TextViewCompat.getMaxLines(text);
if (maxLines==2){
text.setMaxLines(Integer.MAX_VALUE);
}
else{
text.setMaxLines(2);
}
}
});
rpcHelper.getPhoto(storageDir + "/", owner.photo, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
owner_img.setImageBitmap(bm);
}
#Override
public void onPreExecute() {
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(mToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public void refreshConversation(){
dbHelper.dbSyncer.syncPosts(rpcHelper.user_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
DataBaseReader.Post[] posts = dbHelper.dbReader.getPosts(conversationId);
postsRecycler = (RecyclerView) findViewById(R.id.posts_recycler);
postsLayoutManager = new LinearLayoutManager(context);
postsRecycler.setLayoutManager(postsLayoutManager);
postsAdapter = new PostsAdapter(posts, storageDir, rpcHelper);
postsRecycler.setAdapter(postsAdapter);
postsRecycler.scrollToPosition(postsAdapter.getItemCount() - 1);
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
/*
rpcHelper.getPosts(conversationId, new AsyncResponseListener(){
#Override
public void onResponse(JSONArray response) throws JSONException {
LinearLayout posts_root = (LinearLayout) findViewById(R.id.posts_root);
posts_root.removeAllViews();
for (int i = 0; i < response.length(); i++){
Log.d("Conv refresh", response.get(i) + "");
final JSONObject jConversation = (JSONObject) response.get(i);
LinearLayout post;
if (jConversation.getString("userId") == rpcHelper.user_id) {
post = (LinearLayout) getLayoutInflater().inflate(R.layout.item_chatpost_sent, posts_root, false);
}
else{
post = (LinearLayout) getLayoutInflater().inflate(R.layout.item_chatpost_received, posts_root, false);
((TextView)post.findViewById(R.id.post_name_)).setText(jConversation.getString("name"));
}
((TextView)post.findViewById(R.id.lbl_message_chat)).setText(jConversation.getString("text"));
posts_root.addView(post);
}
hideProcessDialog();
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});*/
}
public void onSubmit(View v){
final EditText input_post = (EditText)findViewById(R.id.input_post);
String post_text = input_post.getText().toString();
rpcHelper.post(conversationId, post_text, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
refreshConversation();
input_post.setText("");
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
Button no = (Button)alertDialog.findViewById(R.id.btn_cancel);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
helpersImg[0] = null;
helpersImg[1] = null;
helpersImg[2] = null;
helpers[0] = null;
helpers[1] = null;
helpers[2] = null;
alertDialog.dismiss();
}
});
}
public void onSelectUser(View v){
View vi = snapHelper.findSnapView(participantsLayoutManager);
if (helpersImg[0] == vi || helpersImg[1] == vi || helpersImg[2] == vi)
return;
Log.i("get helper Id", ""+ participantsAdapter.selectedUserId);
ImageView photo = (ImageView) vi.findViewById(R.id.img_userprofilpic);
photo.setDrawingCacheEnabled(true);
Bitmap bmap = photo.getDrawingCache();
ImageView helperImage = null;
if (helpersImg[0] == null) {
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper0);
helpersImg[0] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[0] = userInConv[participantsAdapter.selectedUserId];
}
else if (helpersImg[1] == null){
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper1);
helpersImg[1] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[1] = userInConv[participantsAdapter.selectedUserId];
}
else if (helpersImg[2] == null){
helperImage = (ImageView) alertDialog.findViewById(R.id.reward_dialog_helper2);
helpersImg[2] = vi;
helperImage.setImageBitmap(bmap);
photo.setColorFilter(Color.rgb(123, 123, 123), android.graphics.PorterDuff.Mode.MULTIPLY);
helpers[1] = userInConv[participantsAdapter.selectedUserId];
}
else{
return;
}
}
/**private void showTipDialog(){
final AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
LayoutInflater inflater = LayoutInflater.from(context);
final View dialogView = inflater.inflate(R.layout.dialog_add_tip, null);
final EditText value = (EditText) dialogView.findViewById(R.id.tip_value);
final SeekBar sb = (SeekBar) dialogView.findViewById(R.id.seekBar);
sb.setMax(50);
sb.setProgress(5);
sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean b) {
progress = (Math.round(progress/5 ))*5;
seekBar.setProgress(progress);
value.setText(String.valueOf(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
value.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Convert text to integer. Do you already use editText.setInputType(InputType.TYPE_CLASS_NUMBER), don't you?
Integer enteredProgress = Integer.valueOf(s.toString());
sb.setProgress(enteredProgress);
}
#Override
public void afterTextChanged(Editable s) {}});
dialogBuilder.setView(dialogView);
alertDialog = dialogBuilder.create();
alertDialog.show();
Button ok = (Button)alertDialog.findViewById(R.id.btn_ok);
ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
Button no = (Button)alertDialog.findViewById(R.id.btn_no);
no.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertDialog.dismiss();
}
});
}*/
public void removeHelper(View v){
int index = 0;
if (v == alertDialog.findViewById(R.id.reward_dialog_helper0)){
index = 0;
}
else if (v == alertDialog.findViewById(R.id.reward_dialog_helper1)){
index = 1;
}
else if (v == alertDialog.findViewById(R.id.reward_dialog_helper2)){
index = 2;
}
if (helpersImg[index] == null){
return;
}
ImageView photo = (ImageView) helpersImg[index].findViewById(R.id.img_userprofilpic);
photo.setDrawingCacheEnabled(true);
photo.clearColorFilter();
helpersImg[index] = null;
helpers[index] = null;
ImageView imv = (ImageView)v;
imv.setImageResource(R.drawable.stroke_rounded_corners_white);
}
private void showProcessDialog(){
pd = new ProgressDialog(this);
pd.setTitle("Processing");
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
private void hideProcessDialog(){
pd.hide();
}
#Override
public void onInternetConnectionLost() {
}
#Override
public void onInternetConnectionFound() {
}
public void onTakePicture(View v){
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, Statics.REQUEST_IMAGE_CAPTURE);
}
}
public void onTakePictureFromGallery(View v){
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), Statics.REQUEST_PROFILE_IMAGE_GALLERY);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Bitmap imageBitmap;
if ((requestCode == Statics.REQUEST_IMAGE_CAPTURE || requestCode == Statics.REQUEST_IMAGE_CAPTURE_0
|| requestCode == Statics.REQUEST_IMAGE_CAPTURE_1 || requestCode == Statics.REQUEST_IMAGE_CAPTURE_2) && resultCode == RESULT_OK && data != null) {
Bundle extras = data.getExtras();
if (extras == null){
return;
}
imageBitmap = (Bitmap) extras.get("data");
addPhoto(imageBitmap);
}
else if (requestCode == Statics.REQUEST_PROFILE_IMAGE_GALLERY && resultCode == RESULT_OK){
try {
imageBitmap = getBitmapFromUri(data.getData());
addPhoto(imageBitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void addPhoto(Bitmap image) {
DataBaseReader.Conversation c = dbHelper.dbReader.getConversation(conversationId);
String encodedImage = encodeBitmap(image);
rpcHelper.addPhotosToQuestion("" + c.question.id, encodedImage, null, null, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
dbHelper.dbSyncer.sync(rpcHelper.user_id, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(context, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
}
#Override
public void onResponse() {
photos = dbHelper.dbReader.getPhotosInConversation(Integer.parseInt(conversationId));
photoRecycler = (RecyclerView) findViewById(R.id.photo_recycler);
photoLayoutManager = new GridLayoutManager(context, Math.max(photos.length, 1));
photoRecycler.setLayoutManager(photoLayoutManager);
rightAdapter = new ConvRightAdapter(photos, storageDir, context);
photoRecycler.setAdapter(rightAdapter);
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
}
#Override
public void onPreExecute() {
}
});
}
private String encodeBitmap(Bitmap bitmap){
try{
bitmap = Bitmap.createScaledBitmap(bitmap, Statics.BITMAP_WIDTH, Statics.BITMAP_HEIGHT, true);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
final byte[] imageInByte = stream.toByteArray();
return Base64.encodeToString(imageInByte, Base64.DEFAULT);
}
catch(Exception e){
return "";
}
}
private Bitmap getBitmapFromUri(Uri uri) throws IOException {
ParcelFileDescriptor parcelFileDescriptor =
getContentResolver().openFileDescriptor(uri, "r");
FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);
parcelFileDescriptor.close();
return image;
}
}
This is my Fragment with conversations List:
public class ConversationFragment extends Fragment {
private View v;
private OnFragmentInteractionListener mListener;
public ConversationFragment() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #return A new instance of fragment ConversationFragment.
*/
// TODO: Rename and change types and number of parameters
public static ConversationFragment newInstance() {
ConversationFragment fragment = new ConversationFragment();
Bundle args = new Bundle();
//args.putString(ARG_PARAM1, param1);
//args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if (v == null) {
v = inflater.inflate(R.layout.fragment_conversation, container, false);
}
final SwipeRefreshLayout swipeRefresh = (SwipeRefreshLayout)v.findViewById(R.id.swiperefreshconv);
swipeRefresh.post(new Runnable() {
#Override
public void run() {
swipeRefresh.setRefreshing(true);
}
});
swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
mListener.syncDb();
}
});
return v;
}
#Override
public void onStart(){
super.onStart();
mListener.refreshConversations();
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
}
This is my Conversation Adapter:
public class ConversationsAdapter extends RecyclerView.Adapter {
private final File mStorageDir;
private final RPCHelper mRPCHelper;
private DataBaseReader.Conversation[] mDataset;
Context context;
// Provide a reference to the views for each data item
// Complex data items may need more than one view per item, and
// you provide access to all the views for a data item in a view holder
public static class ViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public View mView;
public ViewHolder(View v) {
super(v);
mView = v;
}
}
// Provide a suitable constructor (depends on the kind of dataset)
public ConversationsAdapter(DataBaseReader.Conversation[] myDataset, File storageDir) {
mDataset = myDataset;
mStorageDir = storageDir;
mRPCHelper = new RPCHelper();
}
// Create new views (invoked by the layout manager)
#Override
public ConversationsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.item_conversations, parent, false);
ViewHolder vh = new ViewHolder(v);
context = parent.getContext();
return vh;
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
Log.d("recy", "bind called");
TextView username = (TextView)holder.mView.findViewById(R.id.lbl_username);
final TextView message = (TextView)holder.mView.findViewById(R.id.question_text);
TextView date_and_time = (TextView)holder.mView.findViewById(R.id.lbl_date_and_time);
ImageView status_pending = (ImageView)holder.mView.findViewById(R.id.lbl_status_conversation_pending);
ImageView status_in = (ImageView)holder.mView.findViewById(R.id.lbl_status_conversation_in);
TextView keyword0 = (TextView)holder.mView.findViewById(R.id.post_keywords0);
TextView keyword1 = (TextView)holder.mView.findViewById(R.id.post_keywords1);
TextView keyword2 = (TextView)holder.mView.findViewById(R.id.post_keywords2);
ImageView userprofilpic = (ImageView)holder.mView.findViewById(R.id.img_userprofilpic);
LinearLayout answer_info = (LinearLayout) holder.mView.findViewById(R.id.answer_info);
Button delete_coversation = (Button) holder.mView.findViewById(R.id.btn_confirm_delete);
userprofilpic.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(context, UserProfileActivity.class);
i.putExtra("userId", mDataset[position].question.userId);
context.startActivity(i);
}
});
username.setText(mDataset[position].question.userName);
message.setText(mDataset[position].question.text);
keyword0.setText(mDataset[position].question.keywords[0]);
keyword1.setText(mDataset[position].question.keywords[1]);
keyword2.setText(mDataset[position].question.keywords[2]);
addImgToView(mDataset[position].question.photo, userprofilpic);
if (Integer.parseInt(mDataset[position].confirmed) == 1) {
status_pending.setEnabled(false);
status_pending.setVisibility(View.GONE);
status_in.setVisibility(View.VISIBLE);
answer_info.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
message.setTypeface(Typeface.DEFAULT);
message.onSaveInstanceState();
int convId = mDataset[position].id;
Intent i = new Intent(context, ConversationActivity.class);
i.putExtra("conversationId", "" + convId);
context.startActivity(i);
}
});
}
}
// Return the size of your dataset (invoked by the layout manager)
#Override
public int getItemCount() {
return mDataset.length;
}
private void addImgToView(final String uri, final ImageView v){
mRPCHelper.getPhoto(mStorageDir + "/", uri, new AsyncResponseListener() {
#Override
public void onResponse(JSONArray response) throws JSONException {
}
#Override
public void onResponse() {
}
#Override
public void onResponse(Bitmap bm) {
v.setImageBitmap(bm);
}
#Override
public void onPreExecute() {
}
});
}
}
Thank you in advance for your time.
maintain a flag in data level to know is it read or unread,based on that you can apply the styles.
There is two way to do this.
First you can ask to backend to write server side to query to handle last activity bases of timestamp .In this case you have to send your particular timestamp to server when you open particular conversation .
Other you can make local database ex-(sql database) and handle it in your own code by updating query when you reading or undreading conversation.
I have viewpager with couple of fragments inside. I need to get confirmation when user presses back button. However, it doesn't get called unless I visit last page.
public class Create_Safety_CheckList_MainFragment extends Fragment
implements View.OnClickListener, Observer {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_create_safety_checklist_pager_main, container, false);
initializeUI();
return view;
}
private void initializeUI() {
setHeader(getResources().getString(R.string.safety_check_list_checklist_screen_name));
addFragments();
mPager = (ViewPager) view.findViewById(R.id.viewPager_home_screen_activity);
mPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
mPager.setOffscreenPageLimit(fragmentArrayList.size());
mPager.setOnPageChangeListener(onPageChangeListener);
mPager.setAdapter(mPagerAdapter);
// mPager.setOnTouchListener(new View.OnTouchListener() {
//
// #Override
// public boolean onTouch(View v, MotionEvent event) {
// v.getParent().requestDisallowInterceptTouchEvent(true);
// return false;
// }
// });
customTextViewChecklistName = (CustomTextView) view.findViewById(R.id.textView_New_Checklist_Name);
if (createChecklistObservationModel.getChecklistName() != null)
customTextViewChecklistName.setText(createChecklistObservationModel.getChecklistName());
}
private void addFragments() {
createChecklistAdditionalTabFragment = new CreateChecklistAdditionalTabFragment();
fragmentArrayList.add(createChecklistAdditionalTabFragment);
Bundle bundle = getArguments();
if (bundle != null) {
if (bundle.containsKey("***")) {
String response = spcl_databaseHandler.getSpecificChecklistAdditionals(bundle.getString("checklistID"));
try {
JSONObject jsonObject = new JSONObject(response);
JSONObject dataJsonObject = jsonObject.getJSONObject("Data");
JSONArray checkListAdditionalFieldDtoJsonArray = dataJsonObject.getJSONArray("***");
int additionalsLength = checkListAdditionalFieldDtoJsonArray.length();
if (additionalsLength > 0) {
dataJsonObject.getJSONArray("***").toString());
additionalInfoFragment = new Additional_Information_Fragment();
fragmentArrayList.add(additionalInfoFragment);
}
JSONArray jsonGroupsArray = dataJsonObject.getJSONArray("***");
int groupsLength = jsonGroupsArray.length();
for (int i = 0; i < groupsLength; i++) {
JSONObject groupJsonObject = (JSONObject) jsonGroupsArray.get(i);
JSONArray questionsJsonArray = groupJsonObject.getJSONArray("Questions");
int questionsLength = questionsJsonArray.length();
for (int j = 0; j < questionsLength; j++) {
checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment();
checklistGroupsDiscussionQuestionOneFragment.setArguments(bundle1);
fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
}
JSONArray subGroupsJsonArray = groupJsonObject.getJSONArray("SubGroups");
int subGroupsJsonArrayLength = subGroupsJsonArray.length();
for (int j = 0; j < subGroupsJsonArrayLength; j++) {
JSONObject subGroupObject = subGroupsJsonArray.getJSONObject(j);
JSONArray subGroupQuestionsJsonArray = subGroupObject.getJSONArray("Questions");
int subGroupQuestionsJsonArrayLength = subGroupQuestionsJsonArray.length();
for (int k = 0; k < subGroupQuestionsJsonArrayLength; k++) {
checklistGroupsDiscussionQuestionOneFragment = new ChecklistGroupsDiscussionQuestionOneFragment(); fragmentArrayList.add(checklistGroupsDiscussionQuestionOneFragment);
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
questionsFragment = new Other_Questions_Fragment();
membersFragment = new Inspection_Members_Fragment();
fragmentArrayList.add(questionsFragment);
fragmentArrayList.add(membersFragment);
}
private void setHeader(String headerTitle) {
}
ViewPager.OnPageChangeListener onPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int pageNumber) {
}
#Override
public void onPageScrolled(int pageNumber, float positionOffset,
int positionOffsetPixels) {
// mPager.getParent().requestDisallowInterceptTouchEvent(true);
showArrows(pageNumber);
}
#Override
public void onPageScrollStateChanged(int state) {
}
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.imageView_Next:
break;
case R.id.imageView_Previous:
break;
case R.id.textView_Cancel :
callToCloseDialog();
break;
default:
break;
}
}
private void callToCloseDialog() {
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000) {
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(getResources().getString(R.string.cancel_dialog_message))
.setTitle("Warning");
builder.setPositiveButton(getResources().getString(R.string.cancel_dialog_yes_button), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
getActivity().getSupportFragmentManager().popBackStackImmediate(getResources().getString(R.string.new_checklist_fragment), FragmentManager.POP_BACK_STACK_INCLUSIVE);
}
});
builder.setNegativeButton(getResources().getString(R.string.cancel_dialog_no_button), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked cancel button
dialog.dismiss();
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void update(Observable observable, Object o) {
}
/**
* A simple pager adapter that represents 3 objects, in sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentArrayList.get(position);
}
#Override
public int getCount() {
return fragmentArrayList.size();
}
}
private void showArrows(int pageNumber) {
}
#Override
public void onResume() {
super.onResume();
EventBus.getDefault().register(this);
getView().setFocusableInTouchMode(true);
getView().requestFocus();
getView().setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
callToCloseDialog();
return true;
}
});
}
#Override
public void onPause() {
EventBus.getDefault().unregister(this);
super.onPause();
}
#Subscribe
public void onEvent(QuestionResponsesModel questionResponsesModel){
}
}
Kept only code for Viewpager & fragments loading.
By Default Fragment Don't have any back Pressed event, so you have to manage it by Activity onBackPressed() method using below code.
Override onBackPressed() method in your Activity and Apply Check for it.
#Override
public void onBackPressed() {
// put condition here
if("Your Fragment is Visible"){
//Apply confirmation check here
}
else{
super.onBackPressed();
}
}
You can override this method in activity and listen backpress
public class MainActivity extends Activity {
...
#Override
public boolean dispatchKeyEvent(KeyEvent event)
{
int action = event.getAction();
int keyCode = event.getKeyCode();
switch (keyCode)
{
case KeyEvent.KEYCODE_BACK:
if (action == KeyEvent.ACTION_DOWN)
{
Log.v("myApp", "Back button pressed.");
return true;
}
default:
return false;
}
return false;
}
}
Problem
I am new to android and i am using viewpager for the first time in my app and
i am suffering from very strange behavior in my app that is i am using viewpager with three fragments ( TrackFragment , AlbumFragment , ArtistFragment ) and when i swip page from TrackFragment to AlbumFragment and again come back to TrackFragment it becomes blank (but it was not at first time when i am at TrackFragment initially) and same thing happened when i jump to ArtistFragment or any other fragments from the tab layout (its become blank).
And in case when i am going to ArtistFragment from TrackFragment via AlbumFragments by swiping the pages it works correctly (that is contents are shown in pages).
Please suggest me a method to overcome the above problem or any other method to implement same thing.
Here is my code....
MainActivity
public class MainActivity extends AppCompatActivity {
private String[] mPlanetTitles={"Tracks","Album","Artist"};
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
SharedPreferences sharedPreferences;
Fragment [] fragments = {new TracksFragment(),new AlbumFragment(), new ArtistFragment()};
PagerAdapter pagerAdapter;
ViewPager viewPager;
public static ImageView im;
int pos= -1 ;
public static Context context;
MusicService musicService;
boolean mBound;
TabLayout tabLayout ;
public static Uri currentsonguri;
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = getSharedPreferences("lastplayed",Context.MODE_PRIVATE);
Intent i = new Intent(MainActivity.this,MusicService.class);
startService(i);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mDrawerList.setAdapter(new NavigationDrawerAdapter(this));
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 3)
{
Intent i = new Intent(MainActivity.this,PlaylistActivity.class);
startActivity(i);
}
if(position == 4)
{
Intent intent = new Intent();
intent.setAction("android.media.action.DISPLAY_AUDIO_EFFECT_CONTROL_PANEL");
if((intent.resolveActivity(getPackageManager()) != null)) {
startActivity(intent);
} else {
// No equalizer found :(
Toast.makeText(getBaseContext(),"No Equaliser Found",Toast.LENGTH_LONG).show();
}
}
}
});
tabLayout = (TabLayout) findViewById(R.id.tablayout);
viewPager = (ViewPager) findViewById(R.id.viewPager);
tabLayout.setTabTextColors(Color.DKGRAY,Color.WHITE);
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
context = getBaseContext();
pagerAdapter = new myfragment(getSupportFragmentManager());
im = (ImageView) findViewById(R.id.currentsong);
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
viewPager.setAdapter(pagerAdapter);
tabLayout.setupWithViewPager(viewPager,true);
SharedPreferences.Editor editor= sharedPreferences.edit();
if(sharedPreferences.getInt("count",0)==0)
{
editor.putInt("count",1);
}
else
{
int c= sharedPreferences.getInt("count",0);
Log.d("Uses count",c+"");
editor.putInt("count",c++);
editor.apply();
}
if(!sharedPreferences.getString("uri","").equals(""))
{
String s = sharedPreferences.getString("uri","");
Uri u = Uri.parse(s);
currentsonguri = u;
MediaMetadataRetriever data=new MediaMetadataRetriever();
data.setDataSource(getBaseContext(),u);
try {
byte[] b = data.getEmbeddedPicture();
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
bitmap = getRoundedCornerBitmap(bitmap);
im.setImageBitmap(bitmap);
}
catch (Exception e)
{
e.printStackTrace();
}
try {
musicService.setsongbyuri(u,getBaseContext());
musicService.setMediaPlayer();
}
catch (Exception e)
{
e.printStackTrace();
}
}
else
{
}
editor.apply();
im.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, MusicPlayerActivity.class);
intent.setData(currentsonguri);
intent.putExtra("flag",1);
startActivity(intent);
}
});
final Uri r= getIntent().getData();
if(r!=null) {
currentsonguri = r;
Intent intent = new Intent(MainActivity.this, MusicPlayerActivity.class);
intent.setData(r);
intent.putExtra("flag",0);
startActivity(intent);
}
}
public class myfragment extends FragmentPagerAdapter {
myfragment(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragments[position];
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
String s = "non";
switch (position)
{
case 0 : s= "Tracks" ;
break;
case 1: s= "Albums" ;
break;
case 2: s= "Artist" ;
break;
}
return s;
}
}
public void setview(byte [] b, int position,Uri uri)
{
currentsonguri = uri;
Log.d("position in set view",""+position);
Log.d("fail","i am here");
if(im!=null)
{
if(b!=null)
{
Bitmap bitmap = BitmapFactory.decodeByteArray(b, 0, b.length);
bitmap = getRoundedCornerBitmap(bitmap);
im.setImageBitmap(bitmap);
}
else {
songDetailloader loader = new songDetailloader(context);
String s = loader.albumartwithalbum(loader.songalbum(position));
Log.d("fail","fail to set small image");
if (s != null) {
im.setImageBitmap(BitmapFactory.decodeFile(s));
Log.d("fail","nowsetting set small image");
} else {
im.setImageResource(R.drawable.default_track_light);
Log.d("ic","ic_launcher setted");
}
}
}
else {
Log.d(""," im is null");
}
}
public static Bitmap getRoundedCornerBitmap(Bitmap bitmap) {
Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
bitmap.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
final RectF rectF = new RectF(rect);
final float roundPx = 100;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
musicService = binder.getService();
mBound =true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBound =false;
}
};
#Override
protected void onDestroy() {
super.onDestroy();
Log.d("MainActivity","Get distoryed");
}
#Override
protected void onResume() {
super.onResume();
Intent i = new Intent(this,MusicService.class);
bindService(i, serviceConnection, Context.BIND_AUTO_CREATE);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
protected void onStop() {
super.onStop();
unbindService(serviceConnection);
}}
Tracks Fragment
public class TracksFragment extends Fragment {
songDetailloader loader = new songDetailloader();
ArrayList<Songs> give = new ArrayList<>();
public int pos = -1;
MediaPlayer mp ;
MusicService musicService;
boolean mBound;
ImageView search;
ListViewAdapter listViewAdapter;
RelativeLayout editreltive;
ListView listView;
EditText editText;
TextView ch;
private Cursor cursor ;
int albumindex,dataindex,titleindex,durationindex,artistindex;
private final static String[] columns ={MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.DURATION, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE, MediaStore.Audio.Media.IS_MUSIC,MediaStore.Audio.Media.IS_RINGTONE,MediaStore.Audio.Media.ARTIST,MediaStore.Audio.Media.SIZE ,MediaStore.Audio.Media._ID};
private final String where = "is_music AND duration > 10000 AND _size <> '0' ";
private final String orderBy = MediaStore.Audio.Media.TITLE;
public TracksFragment() {
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("fragment created","created");
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable final ViewGroup container, #Nullable Bundle savedInstanceState)
{
View v =inflater.inflate(R.layout.listviewofsongs,container,false);
listView = (ListView) v.findViewById(R.id.listView);
allsongs();
intlistview();
new Thread(new Runnable() {
#Override
public void run() {
Intent i = new Intent(getActivity(),MusicService.class);
getActivity().bindService(i, serviceConnection, Context.BIND_AUTO_CREATE);
}
}).start();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
Log.d("Uri of ",""+give.get(position).getSonguri());
musicService.setplaylist(give,give.get(position).getPosition());
musicService.setMediaPlayer();
view.setSelected(true);
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
final AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
View v =LayoutInflater.from(getContext()).inflate(R.layout.select_dialog_layout,null);
builder.setView(v);
builder.setTitle(give.get(position).gettitle()+"\n "+give.get(position).getalbum());
builder.create();
final AlertDialog d=builder.show();
//seting click listner.....
TextView play = (TextView) v.findViewById(R.id.dialogplay);
TextView playnext = (TextView) v.findViewById(R.id.dialogplaynext);
TextView queue = (TextView) v.findViewById(R.id.dialogqueue);
TextView fav = (TextView) v.findViewById(R.id.dialogaddtofav);
TextView album = (TextView) v.findViewById(R.id.dialogalbum);
TextView artist = (TextView) v.findViewById(R.id.dialogartist);
TextView playlist = (TextView) v.findViewById(R.id.dialogaddtoplaylsit);
TextView share = (TextView) v.findViewById(R.id.dialogshare);
TextView delete = (TextView) v.findViewById(R.id.dialogdelete);
TextView properties = (TextView) v.findViewById(R.id.dialogproperties);
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
File f= new File(give.get(position).getSonguri().getLastPathSegment());
Log.d("LENGTH IS",""+f.length());
musicService.setplaylist(give,position);
musicService.setMediaPlayer();
d.dismiss();
}
});
playnext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
queue.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
musicService.insertinqueue(give.get(position));
}
});
fav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
DataBaseClass db = new DataBaseClass(getContext());
int i=db.insetintoliked(give.get(position));
if(i==1)
{
Toast.makeText(getContext(),"Added to Favorites",Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getContext(),"Already in Favorites",Toast.LENGTH_SHORT).show();
}
});
album.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
Intent i = new Intent( getActivity() , AlbumDetail.class);
Bundle b= new Bundle();
b.putCharSequence("album",give.get(position).getalbum());
i.putExtras(b);
startActivity(i);
}
});
artist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getActivity(),ArtistActivity.class);
i.putExtra("artist",give.get(position).getartist());
startActivity(i);
d.dismiss();
}
});
playlist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
b.setMessage("Audio '"+give.get(position).gettitle()+"' will be deleted permanently !");
b.setTitle("Delete ?");
b.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
d.dismiss();
}
});
b.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
File f= new File(give.get(position).getSonguri().getPath());
boolean b = f.delete();
Log.d("Is file exist",f.exists()+"");
Log.d("File Lenth",""+f.length());
Log.d("Return value",""+b);
loader.set(getContext());
loader.deleteSong(getContext(),give.get(position).getPosition());
give.remove(position); // give is Arraylist of Songs(datatype);
listViewAdapter.notifyDataSetChanged();
if(b)
{
Toast.makeText(getContext(),"Deleted",Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getContext(),"Fail to Delete",Toast.LENGTH_SHORT).show();
}
}
});
b.create().show();
d.dismiss();
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, give.get(position).getSonguri());
startActivity(Intent.createChooser(share, "Share Audio"));
}
});
properties.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder b = new AlertDialog.Builder(getContext());
File f= new File(give.get(position).getSonguri().getPath());
long size = (f.length())/1024;
long mb= size/1024;
long kb= size%1024;
b.setMessage("Size:"+"\n"+"Size "+mb+"."+kb+" MB\n"+"Path:"+f.getAbsolutePath()+"\n");
b.setTitle(f.getName());
b.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
b.create().show();
d.dismiss();
}
});
return true;
}
});
return v;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("fragment","instance saved");
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
Log.d("Fragment","Instance Restored");
}
public void intlistview()
{
listViewAdapter = new ListViewAdapter(getContext(),give);
listView.setAdapter(listViewAdapter);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.d("Fragment","Destroyed");
getActivity().unbindService(serviceConnection);
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.LocalBinder binder = (MusicService.LocalBinder) service;
musicService = binder.getService();
mBound =true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
mBound =false;
}
};
public void allsongs()
{
cursor = getContext().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, columns, where, null, orderBy);
dataindex = cursor.getColumnIndex(MediaStore.Audio.Media.DATA);
albumindex = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
titleindex = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
durationindex = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
artistindex = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
cursor.moveToFirst();
for(int i=0;i<cursor.getCount();i++)
{
Songs song = new Songs();
song.setalbum(cursor.getString(albumindex));
song.settitle(cursor.getString(titleindex));
song.setSonguri(Uri.parse(cursor.getString(dataindex)));
song.setartist(cursor.getString(artistindex));
song.setDuration(Long.decode(cursor.getString(durationindex)));
song.setPosition(cursor.getPosition());
this.give.add(song);
cursor.moveToNext();
}
cursor.close();
}}
Album Fragment
public class AlbumFragment extends Fragment {
songDetailloader songDetailloader = new songDetailloader();
public AlbumFragment() {
super();
}
GridView gridView;
AlbumAdapter a;
private static ArrayList<Bitmap> image = new ArrayList<>();
LinearLayout linearLayout;
Cursor cursor ;
ImageView album;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
final View v =inflater.inflate(R.layout.albumgridview,container,false);
gridView = (GridView) v.findViewById(R.id.gridview);
album = (ImageView) v.findViewById(R.id.albumart);
/*Animation animation = AnimationUtils.loadAnimation(getContext(),R.anim.grid_layout_anim);
GridLayoutAnimationController controller = new GridLayoutAnimationController(animation,0.2f,0.2f);
gridView.setLayoutAnimation(controller);*/
final TextView albumname = (TextView) v.findViewById(R.id.albumname);
cursor = songDetailloader.getAlbumCursor(getContext());
if(image.size()==0)
new getbitmaps().execute();
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String s = songDetailloader.albumart(position);
Intent i = new Intent( getActivity() , AlbumDetail.class);
Bundle b= new Bundle();
b.putCharSequence("album",songDetailloader.album(position));
i.putExtras(b);
startActivity(i);
}
});
return v;
}
public class getbitmaps extends AsyncTask<Void,Void,Void>
{
Bitmap b;
public getbitmaps() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
for(int i=0;i<cursor.getCount();i++)
{
cursor.moveToPosition(i);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize= 2;
b=BitmapFactory.decodeFile(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART)),options);
if(b==null)
{
b=BitmapFactory.decodeFile(cursor.getString(cursor.getColumnIndex(MediaStore.Audio.Albums.ALBUM_ART)));
}
image.add(b);
}
cursor.close();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
a =new AlbumAdapter(getContext(),image);
a.setCursor();
gridView.setAdapter(a);
new Thread(new Runnable() {
#Override
public void run() {
songDetailloader.set(getContext());
}
}).start();
}
}}
Artist Fragment
public class ArtistFragment extends Fragment {
ListView listView ;
ArrayList<Artists> aa = new ArrayList<>();
final String[] columns3 = {MediaStore.Audio.Artists._ID, MediaStore.Audio.Artists.ARTIST,MediaStore.Audio.Artists.NUMBER_OF_ALBUMS,MediaStore.Audio.Artists.NUMBER_OF_TRACKS};
final static String orderBy3 = MediaStore.Audio.Albums.ARTIST;
public Cursor cursor3;
public ArtistFragment() {
super();
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v= inflater.inflate(R.layout.listviewofsongs,container,false);
listView = (ListView) v.findViewById(R.id.listView);
new artist().execute();
return v;
}
public class artist extends AsyncTask<Void, Void ,Void>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... params) {
allartist();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
ArtistAdapter artistAdapter = new ArtistAdapter(getActivity().getBaseContext(),aa);
listView.setAdapter(artistAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i= new Intent(getActivity(), ArtistActivity.class);
i.putExtra("artist", aa.get(position).getArtistname());
i.putExtra("noofsongs",aa.get(position).getNofosongs());
startActivity(i);
}
});
}
}
#Override
public void setInitialSavedState(SavedState state) {
super.setInitialSavedState(state);
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void allartist()
{
cursor3 = getContext().getContentResolver().query(MediaStore.Audio.Artists.EXTERNAL_CONTENT_URI, columns3, null, null, orderBy3);
cursor3.moveToFirst();
for(int i=0;i< cursor3.getCount() ;i++)
{
Artists art = new Artists();
art.setArtistname(cursor3.getString(cursor3.getColumnIndex(MediaStore.Audio.Artists.ARTIST)));
art.setNoalbums(Integer.parseInt(cursor3.getString(cursor3.getColumnIndex(MediaStore.Audio.Artists.NUMBER_OF_ALBUMS))));
art.setNofosongs(Integer.parseInt(cursor3.getString(cursor3.getColumnIndex(MediaStore.Audio.Artists.NUMBER_OF_TRACKS))));
this.aa.add(art);
cursor3.moveToNext();
}
cursor3.close();
}}
Maybe you can try to add this property to you viewpager, in the onCreate method of your MainActivity :
viewPager.setOffscreenPageLimit(fragments.size());
Update
Another thing you could try is:
In your myfragment override getItemPosition in this way:
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
And add this code in your onCreate of your MainActivity:
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
int previousState;
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
if (previousState == ViewPager.SCROLL_STATE_SETTLING && state == ViewPager.SCROLL_STATE_IDLE) {
pagerAdapter.notifyDataSetChanged();
}
previousState = state;
}
});
The aim of this code is not to be efficient, but to try to understand your problem.
Hope this can help you
I am displaying a userlist and I am using serachview in my actionbar to search. When I am using the searchView in activity, it works fine but when I use it for fragment, searchview doesn't work. It does not search in the listview.
Below is my code.
UserListFragment.java
public class UsersListFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
Activity activity;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private static final String TAG = "UsersListFragment";
private OnFragmentInteractionListener mListener;
private ListView listView;
private List<UserData> users;
private CustomAdapter adapter;
SharedPreferences.Editor preferenceEditor;
Timer myTimer;
View view;
ActionBar actionBar;
private static final String PREFRENCES_NAME = "setPreferences";
private ProgressDialog progressBar;
String partnerKeyValue;
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment UsersListFragment.
*/
// TODO: Rename and change types and number of parameters
public static UsersListFragment newInstance(String param1, String param2) {
UsersListFragment fragment = new UsersListFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
progressBar = new ProgressDialog(getActivity());
progressBar.setCancelable(false);
progressBar.setMessage("Loading...");
progressBar.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressBar.setProgress(0);
Log.i(TAG, "UsersListFragment onCreate");
users = new ArrayList<>();
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh","userlistview");
preferenceEditor.commit();
FirebaseUtil uts = new FirebaseUtil(getContext());
uts.startListeningNotification(Global.getInstance().ownerId, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
Log.i(TAG, Success);
setHasOptionsMenu(true);
String partnerKey = (String) response.get("key");
if (partnerKey != null) {
Map<String, Object> typeCheck = (Map<String, Object>) response.get("value");
String type = (String) typeCheck.get("type");
if (type.equals("chat")) {
String key1 = Global.getInstance().ownerId;
String key2 = partnerKey;
partnerKeyValue = partnerKey;
if (key2 != null) {
String currentPartner = Global.getInstance().partnerId;
if (currentPartner.length() > 0) {
if (currentPartner.equals(partnerKey)) {
} else {
Global.getInstance().unreadMessageUsers.add(partnerKey);
}
Global.getInstance().unreadMessageUsers.add(partnerKey);
} else {
}
}
}
}
}
});
}
#Override
public void onStart() {
super.onStart();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onResume() {
super.onResume();
Log.i(TAG, "UsersListFragment onResume");
}
#Override
public void onPause() {
super.onPause();
Log.i(TAG, "UsersListFragment onStart");
}
#Override
public void onStop() {
super.onStop();
Log.i(TAG, "UsersListFragment onStop");
}
#Override
public void onDestroyView() {
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
FirebaseUtil util = new FirebaseUtil(getContext());
util.updateUserStatus(Global.getInstance().ownerId, "4");
Log.i(TAG, "UsersListFragment onDestroy");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar();
if(actionBar!=null) {
actionBar.setDisplayUseLogoEnabled(true);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(false);
actionBar.setLogo(R.drawable.ic_logo);
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#006EAD"));
actionBar.setBackgroundDrawable(colorDrawable);
}
Toast.makeText(getActivity(), String.valueOf( Global.getInstance().unreadMessageUsers.size()) , Toast.LENGTH_SHORT).show();
int vd = users.size();
view = inflater.inflate(R.layout.fragment_userslist, container, false);
listView = (ListView) view.findViewById(R.id.userdisplay);
adapter = new CustomAdapter(getActivity(),R.layout.program_list, users );
listView.setAdapter(adapter);
if (users.size()==0){
usersList();
}else {
adapter.notifyDataSetChanged();
}
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
UserData data = users.get(position);
Global.getInstance().someData = data.getId();
Global.getInstance().partnerId = data.getId();
int i = 0;
for (Iterator<String> iter = Global.getInstance().unreadMessageUsers.iterator(); iter.hasNext(); ) {
String element = iter.next();
if (element.equals(data.getId().toString())) {
iter.remove();
}
}
data.setUnreadMessageCount(0);
users.remove(position);
users.add(position, data);
Toast.makeText(getActivity().getApplicationContext(),String.valueOf(Global.getInstance().unreadMessageUsers.size()),Toast.LENGTH_LONG).show();
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getActivity().getSupportFragmentManager().beginTransaction();
Bundle args = new Bundle();
args.putString(ChatFragment.DATA_RECEIVE, data.getName());
fragmentOne .setArguments(args);
ft.addToBackStack(null);
ft.replace(R.id.framecontainerMain, fragmentOne).commit();
}
});
// Inflate the layout for this fragment
return view;
}
public void usersList () {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences(PREFRENCES_NAME,Context.MODE_PRIVATE);
preferenceEditor = preferenceSettings.edit();
//get the data from userlist api
final String URL = "url";
String token = preferenceSettings.getString("authToken","");
final String userId = preferenceSettings.getString("userId","");
HashMap<String, String> params = new HashMap<String, String>();
params.put("user_id",userId);
params.put("auth_token",token);
progressBar.show();
JsonObjectRequest myRequest = new JsonObjectRequest(Request.Method.POST, URL,new JSONObject(params),
new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
Log.i(TAG, "onResponse:" +response);
String success = null;
try {
success = response.getString("success");
} catch (JSONException e) {
e.printStackTrace();
}
if(success == "true") {
JSONArray Array = null;
try {
//get the users
} else {
users.add(data);
}
}
Log.i(TAG, "arraylist");
adapter.notifyDataSetChanged();
onlineUsers();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
TimerMethod();
}
}, 0, 5000);
progressBar.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject Obj;
} else {
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
progressBar.dismiss();
VolleyLog.e("Error: ", error.getMessage());
Log.i(TAG, "onErrorResponse:" +error.networkResponse);
}
});
ApplicationController.getInstance().addToRequestQueue(myRequest);
myRequest.setRetryPolicy(new DefaultRetryPolicy(
5000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
}
public void sortingArray(){
if (users.size()>0) {
synchronized (this) {
if (Global.getInstance().unreadMessageUsers.size() > 0) {
System.out.println("\nExample 3 - Count all with Map");
Map<String, Integer> map = new HashMap<String, Integer>();
for (String temp : Global.getInstance().unreadMessageUsers) {
Integer count = map.get(temp);
map.put(temp, (count == null) ? 1 : count + 1);
}
System.out.println("\nSorted Map");
Map<String, Integer> unreadCount = new TreeMap<String, Integer>(map);
for (String key : unreadCount.keySet()) {
int count_unread = unreadCount.get(key);
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setUnreadMessageCount(count_unread);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}
synchronized (this) {
if (Global.getInstance().userStatus.size() > 0) {
try {
for (Object dict : Global.getInstance().userStatus) {
Map<String, Object> val = (Map<String, Object>) dict;
String key = val.keySet().iterator().next();
val.get(key).toString().trim();
int statusValue;
if (val.get(key).toString().equals("")) {
statusValue = 4;
} else {
statusValue = Integer.valueOf(val.get(key).toString());
}
int i = 0;
for (UserData obj : users) {
UserData user = obj;
if (user.getId().equals(key)) {
user.setOnlineStatus(statusValue);
users.remove(i);
users.add(i, user);
break;
}
i++;
}
}
}catch (ConcurrentModificationException e){
e.printStackTrace();
}
}
}
Log.i(TAG, users.get(0).getName());
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getOnlineStatus() > o2.getOnlineStatus()) {
return 1;
} else if (o1.getOnlineStatus() < o2.getOnlineStatus()) {
return -1;
} else {
return 0;
}
}
});
}
if (users.size() > 0) {
Collections.sort(users, new Comparator<UserData>() {
#Override
public int compare(UserData o1, UserData o2) {
if (o1.getUnreadMessageCount() > o2.getUnreadMessageCount()) {
return -1;
} else if (o1.getUnreadMessageCount() < o2.getUnreadMessageCount()) {
return 1;
} else {
return 0;
}
}
});
Global.getInstance().userStatus.clear();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity().getApplicationContext(), "any mesage", Toast.LENGTH_LONG).show();
adapter.notifyDataSetChanged();
}
});
}
}
}
}
public void TimerMethod() {
synchronized(this) {
SharedPreferences preferenceSettings = getActivity().getSharedPreferences("setPreferences", Context.MODE_PRIVATE);
String checkView = preferenceSettings.getString("refresh", "");
if (checkView.equals("userlistview")) {
if (Global.getInstance().userStatus.size() > 0) {
sortingArray();
}
} else {
preferenceEditor = preferenceSettings.edit();
preferenceEditor.putString("refresh", "userlistview");
preferenceEditor.commit();
if (Global.getInstance().unreadMessageUsers.size() > 0){
sortingArray();
}
}
}
}
public void onlineUsers (){
String value;
for (UserData data : users) {
value = data.getId();
FirebaseUtil online = new FirebaseUtil(getContext());
online.onlineUsers(value, new CallBack() {
#Override
public void onCallback(Map<String, Object> response, String Success) {
if (response == null) {
} else {
Global.getInstance().userStatus.add(response);
}
}
});
}
}
#Override
public void onCreateOptionsMenu(Menu menu,MenuInflater inflater) {
inflater.inflate(R.menu.menu_userlist,menu);
MenuItem item = menu.findItem(R.id.menuSearch);
SearchView searchView = (SearchView)item.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
super.onCreateOptionsMenu(menu,inflater);
}
private void logoutUser(){
Intent I = new Intent(getActivity(), LoginActivity.class);
startActivity(I);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menuSearch :
return true;
case R.id.menuLogout :
logoutUser();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
String val = "'";
mListener.onFragmentInteraction(val);
}
}
public void initlizeval(Context context) {
mListener = (OnFragmentInteractionListener) context;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
myTimer.cancel();
mListener = null;
}
/**
* This interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(String val);
}
}
menu_userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/menuSearch"
android:title="#string/search"
android:icon="#drawable/ic_search"
app:actionViewClass="android.widget.SearchView"
app:showAsAction="always">
</item>
<item android:id="#+id/menuLogout"
android:title="#string/logout"
android:icon="#drawable/ic_logout"
android:tint="#android:color/white"
app:showAsAction="always">
</item>
</menu>
CustomAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class CustomAdapter extends ArrayAdapter<UserData> {
private Activity activity;
private List<UserData> messages;
public CustomAdapter(Activity context, int resource, List<UserData> objects) {
super(context, resource, objects);
this.activity = context;
this.messages = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
packagename.CustomAdapter.ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
int layoutResource = 0; // determined by view type
UserData data = getItem(position);
int viewType = getItemViewType(position);
layoutResource = R.layout.program_list;
if (convertView != null) {
holder = (com.your.package.CustomAdapter.ViewHolder) convertView.getTag();
} else {
convertView = inflater.inflate(layoutResource, parent, false);
holder = new com.your.package.CustomAdapter.ViewHolder(convertView);
convertView.setTag(holder);
}
//set message content
holder.msg.setText(data.getName());
holder.id = data.geId();
holder.roleMsg.setText(data.getRole());
return convertView;
}
#Override
public int getViewTypeCount() {
// return the total number of view types. this value should never change
// at runtime
return 2;
}
#Override
public int getItemViewType(int position) {
// return a value between 0 and (getViewTypeCount - 1)
return position % 2;
}
private class ViewHolder {
private TextView msg;
private String id;
private TextView roleMsg;
public ViewHolder(View v) {
msg = (TextView) v.findViewById(R.id.textView1);
roleMsg = (TextView) v.findViewById(R.id.textView2);
}
}
}
HomeActivity.java
public class HomeActivity extends AppCompatActivity implements UsersListFragment.OnFragmentInteractionListener {
private UsersListFragment mItemsFragment;
private ChatFragment mFragmentOne;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
VideoFragment fragmentTwo ;
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
android.support.v4.app.FragmentTransaction fts = getSupportFragmentManager().beginTransaction();
fts.add(R.id.framecontainer, mItemsFragment).commit();
//Instantiate some stuff here like view components
Fragment fragmentOne = new ChatFragment();
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(R.id.framecontainerTab, fragmentOne).commit();
}else{
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
layout2.removeAllViews();
mItemsFragment = new UsersListFragment();
mItemsFragment.initlizeval(this);
setFragment(mItemsFragment);
}
}
public void setFragment(Fragment frag)
{
android.support.v4.app.FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
}
public void attemptLogin1() {
String test = "one";
String tested = "fail";
}
#Override
public void onFragmentInteraction(String uri) {
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.GONE);
LinearLayout layout2 = (LinearLayout)findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.GONE);
findViewById(R.id.framecontainerVideo);
Toast.makeText(getApplicationContext(), "bullet", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onBackPressed() {
super.onBackPressed();
Fragment fragmentOne = new ChatFragment();
LinearLayout layout1 = (LinearLayout) findViewById(R.id.framecontainer);
layout1.setVisibility(View.VISIBLE);
LinearLayout layout2 = (LinearLayout) findViewById(R.id.framecontainerTab);
layout2.setVisibility(View.VISIBLE);
}
#Override
protected void onStart() {
super.onStart();
getDelegate().onStart();
}
}
I have written setHasOptionsMenu(true); in onCreate of UserFragment.java
The logout functionality works fine but the search isn't working.
I have tried various options given on Stackoverflow as well as from other resource, but nothing worked. :(
Any help is appreciated.
Thanks in advance.
Create Constructor in your fragment. Pass Context object inside fragment constructor.which allows your activity as global access.
Remove this line and it will work
case R.id.menuSearch:
return true;