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

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);
}
}
}

Related

How to pass mediaplayer data from service to fragment in android

I'm making an app that play mp3 file from phone storage using service. I have an activity that has a small view to interact with the songs and a fragment that contains a full media function to interact with the songs will be added in if I tap on the small view told. The problem is I cannot get data from service to pass in the fragment to display data or interact between fragment and service.
Here's my main activity 1st photo
Here's my fragment after touch the field on 1st photo fragment
My code in MainActivity
public class MainActivity extends AppCompatActivity {
private List<AudioModel> mainList;
private ListView mainListView;
private MusicAdapter adapter;
private int REQUEST_CODE_PERMISSION = 2703;
private MusicPlayerService musicPlayerService;
public static Intent intentService;
private boolean boundService = false;
public static TextView txtMainTen, txtMainTacGia;
private ImageButton btnMainPlay, btnMainNext;
private int vitri = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);
ActionBar actionBar = getSupportActionBar();
actionBar.hide();
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_NOTHING);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainList = new ArrayList<>();
if(intentService == null){
intentService = new Intent(this, MusicPlayerService.class);
bindService(intentService, serviceConnection, Context.BIND_AUTO_CREATE);
startService(intentService);
}
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_CODE_PERMISSION);
mainListView = findViewById(R.id.listSong);
adapter = new MusicAdapter(MainActivity.this, R.layout.item_song, mainList);
mainListView.setAdapter(adapter);
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
MainAudioCreate(position);
vitri = position;
}
});
txtMainTen = findViewById(R.id.txtPlaying);
txtMainTacGia = findViewById(R.id.txtAuthor);
btnMainPlay = findViewById(R.id.btnPlayBottom);
btnMainNext = findViewById(R.id.btnNextBottom);
btnMainPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (musicPlayerService.mediaPlayer.isPlaying()){
musicPlayerService.pause();
btnMainPlay.setImageResource(R.drawable.button_play);
}
else{
musicPlayerService.resume();
btnMainPlay.setImageResource(R.drawable.button_pause);
}
}
});
btnMainNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
vitri++;
if (vitri > mainList.size() - 1){
vitri = 0;
}
MainAudioCreate(vitri);
}
});
}
private void MainAudioCreate(int position){
musicPlayerService.setVitri(position);
musicPlayerService.play();
btnMainPlay.setImageResource(R.drawable.button_pause);
txtMainTen.setText(musicPlayerService.serviceList.get(position).getName());
txtMainTacGia.setText(musicPlayerService.serviceList.get(position).getArtist());
}
public void AddFragment(View view){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = null;
int container = 0;
String tag = "";
switch (view.getId()) {
case R.id.layoutClose:
fragment = new FragmentClose();
container = R.id.frameContent;
tag = "fragClose";
break;
case R.id.layoutList:
fragment = new FragmentPlaylist();
container = R.id.frameContent;
tag = "fragList";
break;
case R.id.bottomPlayerTouchable:
fragment = new FragmentPlayer();
container = R.id.mainFrame;
tag = "fragPlayer";
break;
}
fragmentTransaction.add(container, fragment, tag);
fragmentTransaction.addToBackStack("fragment");
fragmentTransaction.commit();
}
public void GetSongFromStorage(Context context, List<AudioModel> list){
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
String[] projection = {MediaStore.Audio.Media.DATA, MediaStore.Audio.Media.ALBUM, MediaStore.Audio.Media.ARTIST, MediaStore.Audio.Media.TITLE,};
Cursor c = context.getContentResolver().query(uri, projection, null, null, MediaStore.Audio.Media.TITLE + " ASC");
if (c != null){
while (c.moveToNext()) {
AudioModel audioModel = new AudioModel();
String path = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
mmr.setDataSource(path);
String album = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM));
String artist = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST));
String name = c.getString(c.getColumnIndexOrThrow(MediaStore.Audio.Media.TITLE));
byte[] image = mmr.getEmbeddedPicture();
String displayName = path.substring(path.lastIndexOf("/") + 1);
audioModel.setName(name);
audioModel.setAlbum(album);
audioModel.setArtist(artist);
audioModel.setPath(path);
audioModel.setDisplayname(displayName);
if (image != null) audioModel.setImgPath(image);
list.add(audioModel);
}
adapter.notifyDataSetChanged();
c.close();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_PERMISSION){
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
mainList.clear();
GetSongFromStorage(MainActivity.this, mainList);
}
else{
Toast.makeText(this, "Chưa cho phép", Toast.LENGTH_SHORT).show();
}
}
}
private ServiceConnection serviceConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicPlayerService.MusicBinder binder = (MusicPlayerService.MusicBinder) service;
musicPlayerService = binder.getService();
musicPlayerService.setList(mainList);
boundService = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
boundService = false;
}
};
}
My Service code
public class MusicPlayerService extends Service {
MediaPlayer mediaPlayer;
List<AudioModel> serviceList;
int vitri;
private final IBinder musicBind = new MusicBinder();
public class MusicBinder extends Binder {
MusicPlayerService getService(){
return MusicPlayerService.this;
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent) {
mediaPlayer.stop();
mediaPlayer.release();
return false;
}
public void initMusicPlayer(){
mediaPlayer.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
public void onCreate() {
super.onCreate();
vitri = 0;
mediaPlayer = new MediaPlayer();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
public void setList(List<AudioModel> mp3List){
serviceList = mp3List;
}
public void play(){
mediaPlayer.reset();
createSong();
}
public void pause(){
mediaPlayer.pause();
}
public void resume(){
mediaPlayer.start();
}
public void createSong(){
mediaPlayer = MediaPlayer.create(this, Uri.parse(serviceList.get(vitri).getPath()));
mediaPlayer.start();
}
public void setVitri(int pos){
vitri = pos;
}
}
My Fragment that will be added in code
public class FragmentPlayer extends Fragment {
ImageButton btnBackPlayer;
TextView txtTitlePlayer, txtTimeCurrent, txtTimeTotal;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_player, container, false);
btnBackPlayer = view.findViewById(R.id.btnBackPlayer);
txtTitlePlayer = view.findViewById(R.id.txtTitlePlayer);
txtTimeCurrent = view.findViewById(R.id.txt_timeCurrent);
txtTimeTotal = view.findViewById(R.id.txt_timeTotal);
view.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
return true;
}
});
btnBackPlayer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getFragmentManager().popBackStack();
}
});
return view;
}
}
You can use a broadcast in your service and set broadcast listener in your fragment.

Android restore filter on custom adapter listview

Starting from one activity, I open another one and filter the result of a custom listview.
This is the first activity:
public class PersonaFragment extends Fragment {
private PersonaAdapter personaAdapter;
private ListView personeListView;
private ArrayList<Persona> personeList = new ArrayList<Persona>();
private ArrayList<String> listIdClas = new ArrayList<String>();
private final static int INSERT_REQUEST = 1;
private final static int FILTER_REQUEST = 2;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.persona_fragment, null);
setHasOptionsMenu(true);
personaAdapter = new PersonaAdapter(getActivity(), personeList, R.layout.persona_row_layout);
personeListView = view.findViewById(R.id.lvPersone);
personeListView.setAdapter(personaAdapter);
blsRequest request = new blsRequest(getActivity(), blsVolleyResponse());
request.add(blsUrl.listaPersone(), "00");
return view;
}
private void startFilterActivity() {
Intent intent = new Intent(getActivity(), PersonaFilterActivity.class);
intent.putStringArrayListExtra("listIdClas", this.listIdClas);
startActivityForResult(intent, FILTER_REQUEST);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == FILTER_REQUEST) {
if (resultCode == RESULT_OK) {
this.listIdClas = data.getStringArrayListExtra("listIdClas");
personaAdapter.filterManual(this.listIdClas);
}
}
}
private blsVolleyResponse blsVolleyResponse() {
return new blsVolleyResponse() {
#Override
public void onResponse(String result, String tag) {
switch (tag) {
case "00":
personeList = blsJSON.ParseList(result, tag);
personaAdapter.updateData(personeList);
break;
}
}
#Override
public void onError(VolleyError error, String tag) {
Toast.makeText(getActivity(), "Ops! Qualcosa è andato storto", Toast.LENGTH_SHORT).show();
blsLog.i("blsVolleyResponse.onError: TAG = " + tag + " ERROR = " + error);
}
};
}
}
and this is the filter activity:
public class PersonaFilterActivity extends AppCompatActivity {
private ClasseAdapter classeAdapter;
private ListView classiListView;
private ArrayList<Classe> classiList = new ArrayList<Classe>();
private ArrayList<String> listIdClas = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.persona_filter_activity);
Bundle extras = getIntent().getExtras();
if (extras != null) {
listIdClas = extras.getStringArrayList("listIdClas");
}
classiListView = findViewById(R.id.lvClassi);
classeAdapter = new ClasseAdapter(this, classiList);
classiListView.setAdapter(classeAdapter);
classiListView.addOnLayoutChangeListener(onListLoaded);
blsRequest request = new blsRequest(this, blsVolleyResponse());
request.add(blsUrl.listaClassi(), "00");
}
private View.OnLayoutChangeListener onListLoaded = new View.OnLayoutChangeListener() {
#Override
public void onLayoutChange(View view, int i, int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
setFilter();
}
};
private void applyFilter() {
fillListId();
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("listIdClas", listIdClas);
setResult(Activity.RESULT_OK, returnIntent);
finish();
}
private void fillListId() {
listIdClas.clear();
for (int i = 0; i < classiListView.getChildCount(); i++) {
View child = classiListView.getChildAt(i);
Classe classe = (Classe) classiListView.getItemAtPosition(i);
Switch aSwitch = child.findViewById(R.id.swFlt);
if (aSwitch.isChecked())
listIdClas.add(classe.getId());
}
}
private void ReturnValue(int Result) {
Intent returnIntent = new Intent();
setResult(Result, returnIntent);
finish();
}
private void clearFilter() {
listIdClas.clear();
for (int i = 0; i < classiListView.getChildCount(); i++) {
View child = classiListView.getChildAt(i);
Switch aSwitch = child.findViewById(R.id.swFlt);
aSwitch.setChecked(false);
}
}
private void setFilter() {
for (int i = 0; i < classiListView.getChildCount(); i++) {
for (String idCat : listIdClas) {
View child = classiListView.getChildAt(i);
Switch aSwitch = child.findViewById(R.id.swFlt);
Classe classe = (Classe) classiListView.getItemAtPosition(i);
if (classe.getId().compareTo(idCat) == 0)
aSwitch.setChecked(true);
}
}
}
private blsVolleyResponse blsVolleyResponse() {
return new blsVolleyResponse() {
#Override
public void onResponse(String result, String tag) {
switch (tag) {
case "00":
classiList = blsJSON.ParseList(result, tag);
classeAdapter.updateData(classiList);
break;
}
}
#Override
public void onError(VolleyError error, String tag) {
Toast.makeText(PersonaFilterActivity.this, "Ops! Qualcosa è andato storto", Toast.LENGTH_SHORT).show();
blsLog.i("blsVolleyResponse.onError: TAG = " + tag + " ERROR = " + error);
}
};
}
}
As you can see I don't use:
classiListView.getCount()
but
classiListView.getChildCount()
Because there are a lot of items on filter listview and if I use "getCount()" I get an error like:
"Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference"
I don't have any problem to filter the custom adapter of the listview: using an array list I store the rows id that I selected and I apply them on the first activity listview. Right now I need to open the second activity and set checked the Switch object for each row (if it was/wasn't checked) but when I re-click the filter button to add other filters the filter item's listview aren't restored correctly, due to using "getChildCount()".
Hope I was clear. How do I perform it?

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.

showDialog(DIALOG_EXIT); error

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

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

Categories

Resources