showDialog(DIALOG_EXIT); error - android

what am I doing wrong?
I want to display an AlertDialog - "or close an application" beats me an error
Error:(141, 9) error: cannot find symbol method showDialog(int)
what should I do?
public class ZavdanFragment extends Fragment {
//аргумент індиф.
private static final String ARG_ZAMOV_ID = "zamov_id";
//мітка діалогу календаря
private static final String DIALOG_DATE = "DialogDate";
//мітка діалогу Фото
private static final String DIALOG_FOTO = "DialogFoto";
//private static final String DIALOG_EXIT = "DialogExit";
//призначення цільового фрагменту
private static final int REQUEST_DATE = 0;
//Контакти
private static final int REQUEST_CONTACT = 1;
//камера
private static final int REQUEST_PHOTO = 2;
//тел
private static final int REQUEST_PERMISSION = 3;
private static final int DIALOG_EXIT = 4;
private Zavdannya mZavdannya;
private EditText mTitleField; //назва замов.
private EditText mPrice; //ціна замов.
private Button mDateButton; // дата замов.
private CheckBox mVikonanoCheckBox; //виконання замов.
private CheckBox mTerminovoCheckBox; //термінове замов.
private CheckBox mOplataCheckBox; //оплачене замов.
private Button mRepostButton; //відправка звіту
private Button mContactButton; //список контактів
private ImageButton mPhotoButton; //кнопка фото
private ImageView mPhotoView; //фото
private File mPhotoFile;//фото
private Point mPhotoViewSize;//вікно фото
private Callbacks mCallbacks;
private Spinner mSpinnerWork;
//зателефонувати
private Button mCallContact;
private String mCallID;
//обовязковий інтерфейс для активності-хоста
public interface Callbacks {
void onZamovUpdated(Zavdannya zavdannya);
}
//аргументи індетифікатора
public static ZavdanFragment newInstance(UUID zamovId) {
Bundle args = new Bundle();
args.putSerializable(ARG_ZAMOV_ID, zamovId);
ZavdanFragment fragment = new ZavdanFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (Callbacks) activity;
}
//зберегти і передати інд. замов.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//отримати індетифікатор
UUID zamovId = (UUID) getArguments().getSerializable(ARG_ZAMOV_ID);
mZavdannya = ZamovLab.get(getActivity()).getZavdannya(zamovId);
//збереження місцезнахоження фото
mPhotoFile = ZamovLab.get(getActivity()).getPhotoFile(mZavdannya);
//menu
setHasOptionsMenu(true);
}
//запис оновлення
#Override
public void onPause() {
super.onPause();
ZamovLab.get(getActivity()).updateZamov(mZavdannya);
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
public void onclick(View v){
showDialog(DIALOG_EXIT);
}
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(getActivity());
switch (id){
case DIALOG_EXIT:
return new AlertDialog.Builder(getActivity())
.setTitle(R.string.exit)
.setCancelable(false)
.setMessage(R.string.dial)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
android.os.Process.killProcess(android.os.Process.myPid());
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
})
.create();
}
dialog = builder.show();
return dialog;
}
//меню видалити
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_zamov, menu);
}
//дії при виборі меню
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
//видалити
case R.id.menu_item_delete_zamov:
ZamovLab.get(getActivity()).removeZamov(mZavdannya);
getActivity().finish();
return true;
case R.id.menu_item_exit:
onCreateDialog(DIALOG_EXIT);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
// розмітка (замовлення)
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_zamov,
container, false);
//назва замов.
mTitleField = (EditText) v.findViewById(R.id.zamov_title);
mTitleField.setText(mZavdannya.getTitle());//оновити назву
mTitleField.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) {
mZavdannya.setTitle(s.toString());
updateZamov();
}
#Override
public void afterTextChanged(Editable s) {
}
});
//список
mSpinnerWork = (Spinner) v.findViewById(R.id.spinner_work);
ArrayAdapter<CharSequence> dataAdapter = ArrayAdapter.createFromResource(
getActivity().getApplicationContext(), R.array.catlist, android.R.layout.simple_spinner_item
);
dataAdapter.setDropDownViewResource(android.R.layout
.simple_spinner_dropdown_item);
mSpinnerWork.setAdapter(dataAdapter);
mSpinnerWork.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//відображення позиції
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Вибрано: " + item, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
//mSpinnerWork.setOnItemSelectedListener((AdapterView.OnItemClickListener) this);
/*List<String> work = new ArrayList<String>();
work.add("11a");
work.add("2a");
work.add("5a");
work.add("1a");
work.add("2a");
work.add("3a");
work.add("4a");
work.add("55a");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_spinner_item, work
);*/
//ціна
mPrice = (EditText) v.findViewById(R.id.zamov_title_prise);
mPrice.setText(mZavdannya.getPrice());//оновити ціну
mPrice.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) {
mZavdannya.setPrice(s.toString());
updateZamov();
}
#Override
public void afterTextChanged(Editable s) {
}
});
//дата
mDateButton = (Button) v.findViewById(R.id.zamov_date);
updateDate();
//виклик діал. вікна при натискані на дату
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
//виклик newInstance
DatePickerFragment dialog = DatePickerFragment
.newInstance(mZavdannya.getDate());
dialog.setTargetFragment(ZavdanFragment.this, REQUEST_DATE);
dialog.show(manager, DIALOG_DATE);
}
});
//виконання
mVikonanoCheckBox = (CheckBox) v.findViewById(R.id.zamov_vikonano);
mVikonanoCheckBox.setChecked(mZavdannya.isVikonano());//оновити прапорець
mVikonanoCheckBox.setOnCheckedChangeListener(new CompoundButton
.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
//Прапорець виконання
mZavdannya.setVikonano(isChecked);
updateZamov();
}
});
//оплаченно
mOplataCheckBox = (CheckBox) v.findViewById(R.id.zamov_oplata);
mOplataCheckBox.setChecked(mZavdannya.isOplata());//оновити прапорець
mOplataCheckBox.setOnCheckedChangeListener(new CompoundButton
.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
//Прапорець виконання
mZavdannya.setOplata(isChecked);
updateZamov();
}
});
//терміново
mTerminovoCheckBox = (CheckBox) v.findViewById(R.id.zamov_terminovo);
mTerminovoCheckBox.setChecked(mZavdannya.isTerminovo());//оновити прапорець
mTerminovoCheckBox.setOnCheckedChangeListener(new CompoundButton
.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(
CompoundButton buttonView, boolean isChecked) {
//Прапорець виконання
mZavdannya.setTerminovo(isChecked);
updateZamov();
}
});
//звіт про виконання
mRepostButton = (Button) v.findViewById(R.id.zamov_repost);
mRepostButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_TEXT, getZamovRepost());
i.putExtra(Intent.EXTRA_SUBJECT,
getString(R.string.zamov_repost_subject));
i = Intent.createChooser(i, getString(R.string.send_repost));
startActivity(i);
}
});
//Вибір контакту
final Intent pickContact = new Intent(Intent.ACTION_PICK,
ContactsContract.Contacts.CONTENT_URI);
// pickContact.addCategory(Intent.CATEGORY_HOME);//перевірка фільтра
mContactButton = (Button) v.findViewById(R.id.zamov_contact);
mContactButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//startActivityForResult(pickContact, REQUEST_CONTACT);
//зчитати контакт
int permissionCheck = ContextCompat.checkSelfPermission(getActivity(),
android.Manifest.permission.READ_CONTACTS);
if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
ZavdanFragment.this.requestPermissions(new String[]{
android.Manifest.permission.READ_CONTACTS
}, REQUEST_PERMISSION);
} else {
startActivityForResult(pickContact, REQUEST_CONTACT);
}
}
});
if (mZavdannya.getContact() != null) {
mContactButton.setText(mZavdannya.getContact());
}
//зателефонувати
mCallContact = (Button) v.findViewById(R.id.call_contact_button);
mCallContact.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mCallID != null) {
Cursor cursor = getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?",
new String[]{mCallID}, null);
try {
cursor.moveToFirst();
String phoneNumber = cursor.getString(cursor.getColumnIndex(
ContactsContract.CommonDataKinds.Phone.NUMBER));
Intent callContact = new Intent(Intent.ACTION_DIAL,
Uri.parse("tel:" + phoneNumber));
startActivity(callContact);
} finally {
cursor.close();
}
} else {
Toast.makeText(getActivity().getApplicationContext(),
"Контакт не вибраний",
Toast.LENGTH_LONG).show();
}
}
});
//захист від контакних програм
PackageManager packageManager = getActivity().getPackageManager();
if (packageManager.resolveActivity(pickContact,
PackageManager.MATCH_DEFAULT_ONLY) == null) {
mContactButton.setEnabled(false);
}
//кнопка фото
mPhotoButton = (ImageButton) v.findViewById(R.id.zamov_camera);
final Intent captureImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
boolean canTakePhoto = mPhotoFile != null && captureImage
.resolveActivity(packageManager) != null;
mPhotoButton.setEnabled(canTakePhoto);
//вікно фото
if (canTakePhoto) {
Uri uri = Uri.fromFile(mPhotoFile);
captureImage.putExtra(MediaStore.EXTRA_OUTPUT, uri);
}
mPhotoButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(captureImage, REQUEST_PHOTO);
}
});
//фото
mPhotoView = (ImageView) v.findViewById(R.id.zamov_photo);
// updatePhotoView();
mPhotoView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager manager = getFragmentManager();
PhotoView dialog = new PhotoView();
PhotoView.getPhotoFile(mPhotoFile);
dialog.show(manager, DIALOG_FOTO);
}
});
final ViewTreeObserver observer = mPhotoView.getViewTreeObserver();
observer.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
boolean isFirstPass = (mPhotoViewSize == null);
mPhotoViewSize = new Point();
mPhotoViewSize.set(mPhotoView.getWidth(), mPhotoView.getHeight());
if (isFirstPass) updatePhotoView();
}
});
return v;
}
//реакція на отриману інформацію дати в діал. вікні
#Override
public void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_DATE) {
Date date = (Date) data
.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mZavdannya.setDate(date);
updateZamov();
updateDate();
}//вибрати контакт
else if (requestCode == REQUEST_CONTACT && data != null) {
Uri contactUri = data.getData();
//визначенняя поля які мають бути повернуті запитом
String[] queryFields = new String[]{
ContactsContract.Contacts.DISPLAY_NAME, ContactsContract
.Contacts._ID};
//виконання запиту
Cursor c = getActivity().getContentResolver()
.query(contactUri, queryFields, null, null, null);
try {
//перевірка отриманого результату
if (c.getCount() == 0) {
return;
}
//використання 1 стовбця даних (ім'я контакту)
c.moveToFirst();
String contact = c.getString(0);
mZavdannya.setContact(contact);
updateZamov();
mContactButton.setText(contact);
mCallID = c.getString(c.getColumnIndex(ContactsContract.
Contacts._ID));
} finally {
c.close();
}
} else if (requestCode == REQUEST_PHOTO) {
updateZamov();
updatePhotoView();
}
}
private void updateZamov() {
ZamovLab.get(getActivity()).updateZamov(mZavdannya);
mCallbacks.onZamovUpdated(mZavdannya);
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions,
int[] grantResults) {
if (requestCode == REQUEST_PERMISSION) {
if (grantResults.length > 0 && grantResults[0] == PackageManager
.PERMISSION_GRANTED) {
Intent pickContact = new Intent(Intent.ACTION_DIAL, ContactsContract
.Contacts.CONTENT_URI);
startActivityForResult(pickContact, REQUEST_CONTACT);
}
}
}
private void updateDate() {
//формат дати
SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, dd MMM, yyyy");
//оновити дату
mDateButton.setText(dateFormat.format(mZavdannya.getDate()));
}
//4 строчки звіту та з'єднaння їх
private String getZamovRepost() {
//1 строчка
String vikonanoString = null;
if (mZavdannya.isVikonano()) {
vikonanoString = getString(R.string.zamov_repost_vikonano);
} else {
vikonanoString = getString(R.string.zamov_repost_nevikonano);
}
//2 строчка
String dataFormat = "EEE,dd MMM";
String dataString = android.text.format.DateFormat.format(
dataFormat, mZavdannya.getDate()).toString();
//3 строчка
String contact = mZavdannya.getContact();
if (contact == null) {
contact = getString(R.string.zamov_repost_no_contact);
} else {
contact = getString(R.string.zamov_repost_contact) + mZavdannya.getContact();
}
String price = mZavdannya.getPrice();
String report = getString(R.string.zamov_repost, mZavdannya.
getTitle(), dataString, vikonanoString, contact, price);
return report;
}
//оновлення фото
private void updatePhotoView() {
if (mPhotoFile == null || !mPhotoFile.exists()) {
mPhotoView.setImageDrawable(null);
} else {
/* Bitmap bitmap = PictureUtils.getScaledBitmap(
mPhotoFile.getPath(), getActivity());
mPhotoView.setImageBitmap(bitmap);*/
Bitmap bitmap = (mPhotoViewSize == null) ?
PictureUtils.getScaledBitmap(mPhotoFile.getPath(), getActivity()) :
PictureUtils.getScaledBitmap(mPhotoFile.getPath(),
mPhotoViewSize.x, mPhotoViewSize.y);
mPhotoView.setImageBitmap(bitmap);
mPhotoView.setEnabled(true);
}
}
}

You need context in order to call showDialog() from Fragment. Try calling
getActivity().showDialog(DIALOG_EXIT);
More info visit here

Related

Repository class returning null values in ViewModel to recycler view list

Here is so far my implementation. I am trying to get the list of Bluetooth devices after the scan is finished. But the observer is not returning a list of devices.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int REQUEST_CODE_OPEN_GPS = 1;
private static final int REQUEST_CODE_PERMISSION_LOCATION = 2;
BluetoothAdapter bluetoothAdapter;
private MutableLiveData<List<DataModel>> deviceLiveData;
public static List<BleDevice> bleDeviceList;
private List<BleDevice> deviceList = new ArrayList<>();
private RecyclerView rvDevices;
private MAdapter devicesAdapter;
private MainViewModel mainViewModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bleDeviceList = new ArrayList<>();
rvDevices = findViewById(R.id.main_rv);
BleManager.getInstance().init(getApplication());
BleManager.getInstance()
.enableLog(true)
.setReConnectCount(5, 5000)
.setConnectOverTime(20000)
.setOperateTimeout(5000);
checkPermissions();
}
private void checkPermissions() {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!bluetoothAdapter.isEnabled()) {
Toast.makeText(this, getString(R.string.please_open_blue), Toast.LENGTH_LONG).show();
return;
}
String[] permissions = {Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION};
List<String> permissionDeniedList = new ArrayList<>();
for (String permission : permissions) {
int permissionCheck = ContextCompat.checkSelfPermission(this, permission);
if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
onPermissionGranted(permission);
} else {
permissionDeniedList.add(permission);
}
}
if (!permissionDeniedList.isEmpty()) {
String[] deniedPermissions = permissionDeniedList.toArray(new String[permissionDeniedList.size()]);
ActivityCompat.requestPermissions(this, deniedPermissions, REQUEST_CODE_PERMISSION_LOCATION);
}
}
Observer<List<BleDevice>> userListUpdateObserver = new Observer<List<BleDevice>>() {
#Override
public void onChanged(List<BleDevice> userArrayList) {
devicesAdapter = new MAdapter(MainActivity.this, userArrayList, new MAdapter.OnClick() {
#Override
public void onItemClick(View v) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_SHORT).show();
}
});
rvDevices.setLayoutManager(new LinearLayoutManager(MainActivity.this));
rvDevices.setAdapter(devicesAdapter);
devicesAdapter.notifyDataSetChanged();
}
};
private void onPermissionGranted(String permission) {
switch (permission) {
case Manifest.permission.ACCESS_FINE_LOCATION:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && !checkGPSIsOpen()) {
new AlertDialog.Builder(this)
.setTitle("Prompt")
.setMessage(R.string.gpsNotifyMsg)
.setNegativeButton(R.string.cancel,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setPositiveButton(R.string.setting,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, REQUEST_CODE_OPEN_GPS);
}
})
.setCancelable(false)
.show();
} else {
startScan();
mainViewModel = new ViewModelProvider(MainActivity.this).get(MainViewModel.class);
mainViewModel.getUserMutableLiveData().observe(this, userListUpdateObserver);
}
break;
}
}
private boolean checkGPSIsOpen() {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
if (locationManager == null)
return false;
return locationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_OPEN_GPS) {
if (checkGPSIsOpen()) {
startScan();
}
}
}
#Override
public final void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_PERMISSION_LOCATION:
if (grantResults.length > 0) {
for (int i = 0; i < grantResults.length; i++) {
if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
onPermissionGranted(permissions[i]);
}
}
}
break;
}
}
public static void startScan() {
BleManager.getInstance().scan(new BleScanCallback() {
#Override
public void onScanStarted(boolean success) {
}
#Override
public void onLeScan(BleDevice bleDevice) {
super.onLeScan(bleDevice);
}
#Override
public void onScanning(BleDevice bleDevice) {
}
#Override
public void onScanFinished(List<BleDevice> scanResultList) {
bleDeviceList.addAll(scanResultList);
}
});
}
public static void clearScanDevice() {
for (int i = 0; i < bleDeviceList.size(); i++) {
BleDevice device = bleDeviceList.get(i);
if (!BleManager.getInstance().isConnected(device)) {
bleDeviceList.remove(i);
}
}
}
public void addDevice(BleDevice bleDevice) {
removeDevice(bleDevice);
String newBleDeviceName = bleDevice.getMac();
if (newBleDeviceName == null) return;
}
public void removeDevice(BleDevice bleDevice) {
for (int i = 0; i < bleDeviceList.size(); i++) {
BleDevice device = bleDeviceList.get(i);
if (bleDevice.getKey().equals(device.getKey())) {
bleDeviceList.remove(i);
}
}
}
#Override
public void onBackPressed() {
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setTitle("Exit?");
builder1.setMessage("Are you sure you want to disconnect?.");
builder1.setCancelable(true);
builder1.setPositiveButton(
"Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
BleManager.getInstance().disconnectAllDevice();
BleManager.getInstance().destroy();
Toast.makeText(MainActivity.this, "Disconnected", Toast.LENGTH_SHORT).show();
dialog.cancel();
finish();
}
});
builder1.setNegativeButton(
"No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
BleManager.getInstance().disconnectAllDevice();
BleManager.getInstance().destroy();
}
#Override
protected void onResume() {
super.onResume();
}
public void clearConnectedDevice() {
for (int i = 0; i < bleDeviceList.size(); i++) {
BleDevice device = bleDeviceList.get(i);
if (BleManager.getInstance().isConnected(device)) {
bleDeviceList.remove(i);
}
}
}
}
I have the startScan() method in MainActivity.java. There I can get the list of discoverable BleDevices in onScanFinished(). I am trying to implement the same method in the repository class MainDataRepository.java. I am getting null data from that class in MainViewModel.java. Here is my implementation of all classes.
MainDataRepository.java
public class MainDataRepository {
private static final String TAG = "MainDataRepository";
private static final MainDataRepository ourInstance = new MainDataRepository();
private MutableLiveData<List<BleDevice>> deviceListLiveData = new MutableLiveData<>();
public static MainDataRepository getInstance() {
return ourInstance;
}
public MutableLiveData<List<BleDevice>> getTodos() {
BleManager.getInstance().scan(new BleScanCallback() {
#Override
public void onScanStarted(boolean success) {
Log.d("View Model", "scAN started");
}
#Override
public void onLeScan(BleDevice bleDevice) {
super.onLeScan(bleDevice);
Log.d("onLeScan", "onLeScan: View Model");
}
#Override
public void onScanning(BleDevice bleDevice) {
Log.d("View Model", "scannig");
}
#Override
public void onScanFinished(List<BleDevice> scanResultList) {
Log.d("View Model", "onScanFinished: " + scanResultList.size());
for (int i = 0; i < scanResultList.size(); i++) {
Log.d("View Model", "onScanFinished: " + scanResultList.get(i).getName() + " and " + scanResultList.get(i).getMac());
}
}
});
return deviceListLiveData;
}
}
MainViewModel.java
public class MainViewModel extends ViewModel {
private MutableLiveData<List<BleDevice>> userLiveData;
public static List<BleDevice> deviceArrayList = new ArrayList<>();
private MainDataRepository repository = MainDataRepository.getInstance();
public MainViewModel() {
super();
userLiveData = new MutableLiveData<>();
userLiveData = repository.getTodos();
Log.d("View Model", "MainViewModel: " + userLiveData.getValue());
init();
}
public MutableLiveData<List<BleDevice>> getUserMutableLiveData() {
return userLiveData;
}
public void init() {
populateList();
userLiveData.setValue(deviceArrayList);
}
public void populateList() {
deviceArrayList = new ArrayList<>();
Log.d("Inside Populate", "populateList: ");
}
}
MAdapter.java
public class MAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private List<BleDevice> bleDeviceList;
public OnClick click;
public MAdapter(Context mContext, List<BleDevice> bleDeviceList, OnClick click) {
this.mContext = mContext;
this.bleDeviceList = bleDeviceList;
this.click = click;
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View rootView = LayoutInflater.from(mContext).inflate(R.layout.card_ll, parent, false);
return new MViewHolder(rootView);
}
#Override
public void onBindViewHolder(#NonNull RecyclerView.ViewHolder holder, int position) {
BleDevice device = bleDeviceList.get(position);
((MViewHolder) holder).tvName.setText(device.getName());
((MViewHolder) holder).tvMac.setText(device.getMac());
((MViewHolder) holder).btnConnect.setText("Pair");
((MViewHolder) holder).btnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
click.onItemClick(v);
((MViewHolder) holder).btnConnect.setText("Paired");
((MViewHolder) holder).btnConnect.setClickable(false);
}
});
}
#Override
public int getItemCount() {
return bleDeviceList.size();
}
static class MViewHolder extends RecyclerView.ViewHolder {
private TextView tvName, tvMac;
private Button btnConnect;
public MViewHolder(#NonNull View itemView) {
super(itemView);
tvName = itemView.findViewById(R.id.device_name);
tvMac = itemView.findViewById(R.id.device_mac_address);
btnConnect = itemView.findViewById(R.id.btn_connect);
}
}
public interface OnClick {
public void onItemClick(View v);
}
}
Thanks in advance.

How to sort recyclerView, Bold item if unread and unbold if item opened?

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.

Access data between two class Adapter & Activity

I have two class PremiumAdapter & PreviewActivity, and now I want to access data in PremiumAdapter and the data located inside onBindViewHolder methods from PreviewActivity trough Onclick method.
Here is data in PremiumAdapter.java:
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
PremiumVideo video = data.get(position);
final VH vh = (VH) holder;
String price_id = video.price; // target data
String content_id** = video.content_id; // target data
and here is where the data will accessed on PreviewActivity.java:
public void onClick(DialogInterface dialogInterface, int i) {
// Here
}
here is my full code PreviewActivity:
public class PremiumVideoPreviewActivity extends BaseActivity {
private TextView Nama;
private TextView Judul;
private TextView Harga;
private Button btnBuy;
private ImageView imgPreview;
private VideoView video;
MediaController mediaController;
private ProgressBar progressBar;
List<PremiumVideo> premiumVideoList = new ArrayList<>();
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_premium_video_preview);
setDefaultToolbar(true);
Nama = findViewById(R.id.txtNamaPreview);
Judul = findViewById(R.id.txtJudulPreview);
Harga = findViewById(R.id.txtHargaPreview);
imgPreview = findViewById(R.id.imgPreview);
video = findViewById(R.id.vv_preview);
btnBuy = findViewById(R.id.btnBuy);
progressBar = new ProgressBar(this);
mediaController = new MediaController(this);
mediaController.setAnchorView(mediaController);
video.setMediaController(mediaController);
video.setZOrderOnTop(true);
video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.setLooping(true);
}
});
video.setOnErrorListener(new MediaPlayer.OnErrorListener() {
#Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
return false;
}
});
loadPremiumVideo();
PremiumVideo premiumVideo = new PremiumVideo();
String nama = premiumVideo.name;
final String judul = premiumVideo.judul;
final String harga = premiumVideo.price;
String img = premiumVideo.thumb_pic;
Nama.setText(nama);
Judul.setText(judul);
Harga.setText(harga);
Picasso.with(imgPreview.getContext())
.load(img)
.into(imgPreview);
btnBuy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View view) {
final AlertDialog.Builder adb = new AlertDialog.Builder(PremiumVideoPreviewActivity.this);
adb.setTitle("Konfirmasi Belangganan");
adb.setMessage("\n Anda akan berlangganan video ini..");
adb.setCancelable(false);
adb.setPositiveButton("Iya", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
progressBar.setVisibility(View.VISIBLE);
ContactItem caller = SessionManager.getProfile(PremiumVideoPreviewActivity.this);
// i want use data from PremiumAdapter here
Call<APIResponse<DataJsonCharging>> call = ServicesFactory.getService().getCharging(/* Then passing here */);
call.enqueue(new Callback<APIResponse<DataJsonCharging>>() {
#Override
public void onResponse(Call<APIResponse<DataJsonCharging>> call, Response<APIResponse<DataJsonCharging>> response) {
int status = response.code();
APIResponse<DataJsonCharging> chargingResponse = response.body();
Log.d("SetVideoActivity", "onResponse: " + status);
progressBar.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<APIResponse<DataJsonCharging>> call, Throwable t) {
Log.d("SetVideoActivity", "onFailure: " + t.getMessage());
progressBar.setVisibility(View.GONE);
}
});
PremiumVideoModelCharging judul = new PremiumVideoModelCharging();
String judulVideo = judul.getJudul();
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(PremiumVideoPreviewActivity.this);
LayoutInflater inflater = (LayoutInflater) PremiumVideoPreviewActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.popup_pembelian, null);
dialogBuilder.setView(dialogView);
dialogBuilder.setTitle("Berhasil Berlangganan");
TextView txtJudul = dialogView.findViewById(R.id.txtNoteJudul);
txtJudul.setText(judulVideo);
final AlertDialog alertDialog = dialogBuilder.create();
alertDialog.getWindow().setLayout(400, 600);
alertDialog.setIcon(R.drawable.logo_1);
alertDialog.show();
Button button = (Button) dialogView.findViewById(R.id.btn_check_collection);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent checkCollectionIntent = new Intent(view.getContext(), UploadVideoToneActivity.class);
view.getContext().startActivity(checkCollectionIntent);
alertDialog.dismiss();
}
});
}
});
adb.setNegativeButton("Tidak", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.cancel();
}
});
AlertDialog alertDialog = adb.create();
alertDialog.show();
}
});
}
private void loadPremiumVideo() {
Call<APIResponse<List<PremiumVideo>>> call = ServicesFactory.getService().getPremiumVideo();
call.enqueue(new Callback<APIResponse<List<PremiumVideo>>>() {
#Override
public void onResponse(Call<APIResponse<List<PremiumVideo>>> call, Response<APIResponse<List<PremiumVideo>>> response) {
if (response.isSuccessful() && response.body().isSuccessful()) {
List<PremiumVideo> data = response.body().data;
if (data != null) {
premiumVideoList.clear();
premiumVideoList.addAll(data);
}
} else {
Toast.makeText(PremiumVideoPreviewActivity.this, response.errorBody().toString(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<APIResponse<List<PremiumVideo>>> call, Throwable t) {
Toast.makeText(PremiumVideoPreviewActivity.this, t.getLocalizedMessage(), Toast.LENGTH_LONG).show();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_UPLOAD) {
if (OwnVideoManager.isOwnVideoExist(this)) {
Uri ownVideoUri = OwnVideoManager.getOwnVideoUri(this);
video.setVideoURI(ownVideoUri);
video.seekTo(100);
}
}
}
super.onActivityResult(requestCode, resultCode, data);
}
}
here is my PremiumAdapter :
public class PremiumVideoAdapter extends
RecyclerView.Adapter<RecyclerView.ViewHolder> {
static List<PremiumVideo> data;
private ClickCallback clickCallback;
public PremiumVideoAdapter(List<PremiumVideo> data) {
this.data = data;
}
public void setClickCallback(ClickCallback clickCallback) {
this.clickCallback = clickCallback;
}
public interface ClickCallback {
void itemClick(PremiumVideo video);
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
PremiumVideo video = data.get(position);
final VH vh = (VH) holder; //Target data
String harga = video.price; //Target Data
You need to:
Create interface in Adapter
public interface ClickCallback {
void itemClick(PremiumVideo video);
}
Add field and setter in Adapter
private ClickCallback clickCallback;
public void setClickCallback(ClickCallback clickCallback) {
this.clickCallback = clickCallback;
}
Set and implement callback in Activity
episodeAdapter.setClickCallback(this);
Add onClickListener in ViewHolder
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(clickCallback!=null){
clickCallback.itemClick(date.get(getAdapterPosition()));
}
}
});

ViewPager does not redraw content on swipe back

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

How can fragment in fragmentStatePagerAdapter get data from Fragment hosting the viewPager?

FragmentHost has ViewPager, and Fragments of viewpager need data from FragmentHost to create their views.
How to get the data. The data is custom Class.
One way is using Serializable implementation of the custom class. But I want to avoid that, as the class contains array and Map of other custom classes.
Also there can be multiple instances of FragmentHost active at a time, one FragmentHost per activity.
Check this out for communication
public class CrimePagerActivity extends AppCompatActivity {
private static final String EXTRA_CRIME_ID = "com.android.ankitt.criminalintent.activities.extra.crime.id";
private ViewPager mViewPager;
private List<Crime> mCrimes;
public static Intent newIntent(Context packageContext, UUID crimeId) {
Intent intent = new Intent(packageContext, CrimePagerActivity.class);
intent.putExtra(EXTRA_CRIME_ID, crimeId);
return intent;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crime_pager);
UUID crimeId = (UUID) getIntent().getSerializableExtra(EXTRA_CRIME_ID);
mViewPager = (ViewPager) findViewById(R.id.actvity_crime_pager_view_pager);
mCrimes = CrimeLab.get(this).getCrimes();
FragmentManager manager = getSupportFragmentManager();
mViewPager.setAdapter(new FragmentPagerAdapter(manager) {
#Override
public Fragment getItem(int position) {
Crime crime = mCrimes.get(position);
return CrimeFragment.newInstance(crime.getId());
}
#Override
public int getCount() {
return mCrimes.size();
}
});
for (int i = 0; i < mCrimes.size(); i++) {
if (mCrimes.get(i).getId().equals(crimeId)) {
mViewPager.setCurrentItem(i);
break;
}
}
}
}
Fragment
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(ARG_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/*mCrime = new Crime();*/
/*UUID crimeId = (UUID)getActivity().getIntent().getSerializableExtra(CrimeActivity.EXTRA_CRIME_ID);*/
UUID crimeId = (UUID) getArguments().getSerializable(ARG_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
mFilePhoto = CrimeLab.get(getActivity()).getPhotoFile(mCrime);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_crime, container, false);
mEditText = (EditText) view.findViewById(R.id.crime_title);
mEditText.setText(mCrime.getTitile()); //Updating Crime fragment with crime
mEditText.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) {
mCrime.setTitile(toString());
}
#Override
public void afterTextChanged(Editable s) {
}
});
final Intent pickContact = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
/*pickContact.addCategory(Intent.CATEGORY_HOME);*/
mSuspectButton = (Button) view.findViewById(R.id.crime_suspect);
mSuspectButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(pickContact, REQUEST_CONTACT);
}
});
mReportButton = (Button) view.findViewById(R.id.crime_report);
mReportButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, getCrimeReport());
intent.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.crime_report_subject));
intent = Intent.createChooser(intent, getString(R.string.send_report));
startActivity(intent);
}
});
mDateButton = (Button) view.findViewById(R.id.crime_date);
updateDate((mCrime.getDate()).toString());
/*mDateButton.setEnabled(false);*/
/* Design a date picker for an application */
mDateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
/*DatePickerFragment dialog = new DatePickerFragment();*/
DatePickerFragment dialog = DatePickerFragment.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(fragmentManager, DIALOG_DATE);
}
});
mCheckBox = (CheckBox) view.findViewById(R.id.crime_solved);
mCheckBox.setChecked(mCrime.isSolved()); //Updating Crime fragment with crime
mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
mCrime.setSolved(isChecked);
}
});
if (mCrime.getSuspect() != null) {
mSuspectButton.setText(mCrime.getSuspect());
}
PackageManager packageManager = getActivity().getPackageManager();
if (packageManager.resolveActivity(pickContact, PackageManager.MATCH_DEFAULT_ONLY) == null) {
mSuspectButton.setEnabled(false);
}
mImageButton = (ImageButton) view.findViewById(R.id.crime_camera);
final Intent captureImage = new Intent(MediaStore.ACTION_IMAGE_CAPTURE) ;
boolean canTakePhoto = mFilePhoto != null &&
captureImage.resolveActivity(packageManager)!=null;
mImageButton.setEnabled(canTakePhoto);
if (canTakePhoto){
Uri uri = Uri.fromFile(mFilePhoto);
captureImage.putExtra(MediaStore.EXTRA_OUTPUT,uri);
}
mImageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivityForResult(captureImage,REQUEST_PHOTO);
}
});
mImageView = (ImageView) view.findViewById(R.id.crime_photo);
updatePhotoView();
return view;
}
public void returnResult() {
getActivity().setResult(Activity.RESULT_OK, null);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
if (requestCode == REQUEST_DATE) {
Date date = (Date) data
.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate(mCrime.getDate().toString());
} else if (requestCode == REQUEST_CONTACT && data != null) {
Uri contactUri = data.getData();
String[] queryFields = new String[]{
ContactsContract.Contacts.DISPLAY_NAME
};
Cursor cursor = getActivity().getContentResolver().query(contactUri, queryFields, null, null, null);
try {
if (cursor.getCount() == 0) {
return;
}
cursor.moveToFirst();
String suspect = cursor.getString(0);
mCrime.setSuspect(suspect);
mSuspectButton.setText(suspect);
} finally {
cursor.close();
}
}else if (requestCode == REQUEST_PHOTO){
updatePhotoView();
}
}
private void updateDate(String text) {
mDateButton.setText(text);
}
private String getCrimeReport() {
String solvedString = null;
if (mCrime.isSolved()) {
solvedString = getString(R.string.crime_report_solved);
} else {
solvedString = getString(R.string.crime_report_unsolved);
}
String dateFormat = "EEE, MM dd";
String dateString = DateFormat.format(dateFormat, mCrime.getDate()).toString();
String suspect = mCrime.getSuspect();
if (suspect == null) {
suspect = getString(R.string.crime_report_no_suspect);
} else {
suspect = getString(R.string.crime_report_suspect, suspect);
}
String report = getString(R.string.crime_report, mCrime.getTitile(), dateString, solvedString, suspect);
return report;
}
#Override
public void onPause() {
super.onPause();
CrimeLab.get(getActivity()).updateCrime(mCrime);
}
private void updatePhotoView() {
if (mFilePhoto == null || !mFilePhoto.exists()) {
mImageView.setImageDrawable(null);
} else {
Bitmap bitmap = PictureUtils.getScaledBitmap(
mFilePhoto.getPath(), getActivity());
mImageView.setImageBitmap(bitmap);
}
}
}

Categories

Resources