Android Code for Refresh Button that destroys and recreates Text MediaPlayer (Hangs)! - android-fragments

viewPager4 Fragment Activities
If I click on the Texts that play short sounds, one after another then after sometimes the mediaplayer hangs and doesn't play any sound. But if I'm able to destroy activity and recreate the same activity with refresh button in Action Bar, I'd be able to click sounds again.
So what to write in the code for R.id.item2?
Or there is any other way that continuous clicking on short sounds by these texts is possible without any hang kind of problem?
Following is the reference code:
public class module1 extends FragmentActivity {
static Context con;
static int length = 0;
ViewPager mViewPager;
SectionsPagerAdapter mSectionsPagerAdapter;
static MediaPlayer mediaplayer, mediaplayert, m;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
con = this;
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mains, menu);
// Just .main into .mains [created new for different behavior of Action Bar]
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.item1) {
Intent in = new Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.google.com"));
startActivity(in);
}
if (item.getItemId() == R.id.item2) {
//what should i write here? to destroy and recreate the same fragment activity again.
//Problem: After clicking fast on one after another text links, mediaplayert hangs and doesnt play
//Solution: exit app destroy and reopen, then mediaplayer works fine...
//SO, what to write here? kindly help!
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int arg0) {
Fragment ff = new DummySectionFragment1();
switch (arg0) {
case 0:
ff = new DummySectionFragment1();
break;
}
Bundle args = new Bundle();
args.putInt(DummySectionFragment1.ARG_SECTION_NUMBER, arg0 + 1);
ff.setArguments(args);
return ff;
}
#Override
public int getCount() {
return 1;
}
#Override
public CharSequence getPageTitle(int arg0) {
Locale l = Locale.getDefault();
switch (arg0) {
case 0:
return getString(R.string.title_section27).toUpperCase(l);
}
return null;
}
}
public static class DummySectionFragment1 extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.m01set01, container, false);
// Genius Shot by Stupid vIC//
TextView Text = (TextView) rootView.findViewById(R.id.textView2);
Text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound1);
mediaplayert.start();
}
});
TextView Text1 = (TextView) rootView.findViewById(R.id.textView4);
Text1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound2);
mediaplayert.start();
}
});
TextView Text2 = (TextView) rootView.findViewById(R.id.textView6);
Text2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
mediaplayert = MediaPlayer.create(MainActivity.con,
R.raw.sound3);
mediaplayert.start();
}
});
return rootView;
}
}
#Override
protected void onDestroy() {
if (mediaplayert != null) {
mediaplayert.stop();
mediaplayert= null;
}
super.onDestroy();
}
}

Related

Why are my floating action buttons not working properly in my ViewPager?

I have a ViewPager set up with my app and am trying to also set two floating action buttons, a left one and a right one, to do the same thing as the ViewPager, so that the user has a choice in terms of navigation. I'm trying to have it set so that the left button is invisible on the first page, and the right button is invisible on the last page, but the appearances of the buttons seem to be sporadic. I've tried debugging the app, and upon testing each situation, the appropriate code is executed, so I can't understand why this behavior is happening. Any help would be appreciated.
TestFragment:
public class TestFragment extends Fragment {
public static final String ARG_ID = "Id";
private int Id;
private String title;
private TextView titleTV;
private String description;
private TextView descriptionTV;
private int number;
private TextView numberTV;
private FloatingActionButton leftBtn;
private FloatingActionButton rightBtn;
public static TestFragment newInstance(int Id) {
Bundle args = new Bundle();
args.putSerializable(ARG_ID, Id);
TestFragment fragment = new TestFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_test, container, false);
Id = getArguments().getInt(ARG_ID);
title = Test.testData[Id].getTitle();
description = Test.testData[Id].getDescription();
number = Test.testData[Id].getNumber();
titleTV = view.findViewById(R.id.title);
titleTV.setText(title);
descriptionTV = view.findViewById(R.id.description);
descriptionTV.setText(description);
numberTV = view.findViewById(R.id.number);
numberTV.setText(String.valueOf(number));
leftBtn = view.findViewById(R.id.left_btn);
rightBtn = view.findViewById(R.id.right_btn);
toggleButtons();
leftBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
testViewPager.setCurrentItem(--index);
toggleButtons();
}
});
rightBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
testViewPager.setCurrentItem(++index);
toggleButtons();
}
});
return view;
}
public void toggleButtons() {
if(index == 0) {
leftBtn.setVisibility(View.INVISIBLE);
}
else if(index == Test.testData.length - 1) {
rightBtn.setVisibility(View.INVISIBLE);
}
else {
leftBtn.setVisibility(View.VISIBLE);
rightBtn.setVisibility(View.VISIBLE);
}
}
}
TestPagerActivity:
public class TestPagerActivity extends AppCompatActivity {
public static int index;
public static ViewPager testViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_pager);
index = (int) getIntent().getSerializableExtra(EXTRA_ID);
testViewPager = findViewById(R.id.test_view_pager);
FragmentManager fragmentManager = getSupportFragmentManager();
testViewPager.setAdapter(new FragmentStatePagerAdapter(fragmentManager) {
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(position);
}
#Override
public int getCount() {
return Test.testData.length;
}
});
for(int i = 0; i < Test.testData.length; i++) {
if(i == index) {
testViewPager.setCurrentItem(i);
break;
}
}
}
}

How to open a specific website in a fragment from a button in another fragment

I'm using TabLayout and ViewPager in MainActivity and I want to open a specific website in a fragment(BrowserFragment) that contains a webview by clicking a button in another fragment(FragmentHome). In HomeFragment I've 2 buttons, goToFacebook which lead to Facebook and goToAmazon which lead to Amazon.
This is my code:
MainActivity extends AppCompatActivity
TabLayout tabLayout;
ViewPager viewPager;
TabItem homeTabItem;
TabItem browserTabItem;
TabItem profilTabItem;
PagerAdapter pagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabLayout=findViewById(R.id.tabLayout);
homeTabItem=findViewById(R.id.homeTabItem);
browserTabItem=findViewById(R.id.browserTabItem);
profilTabItem=findViewById(R.id.profilTabItem);
viewPager=findViewById(R.id.viewPager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(pagerAdapter);
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
}
PagerAdapter extends FragmentPagerAdapter
private int numOfTabs;
public PagerAdapter(#NonNull FragmentManager fm, int numOfTabs) {
super(fm);
this.numOfTabs=numOfTabs;
}
#NonNull
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch(position){
case 0 :
return new HomeFragment();
case 1 :
return new BrowserFragment();
case 2 :
return new ProfilFragment();
default:
return null;
}
}
#Override
public int getCount() {
return numOfTabs;
}
BrowserFragment extends Fragment
WebView webView;
ProgressBar progressBar;
public BrowserFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_browser, container, false);
progressBar = v.findViewById(R.id.progressBar);
progressBar.setMax(100);
webView=v.findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
webView.setWebChromeClient(new MyWebChromeClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("https://www.google.com/");
return v;
}
private class MyWebViewClient extends WebViewClient
{
#Override
public boolean shouldOverrideUrlLoading(WebView view, String request)
{
view.loadUrl(request);
return true;
}
#Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
progressBar.setVisibility(View.GONE);
progressBar.setProgress(100);
}
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(0);
}
}
private class MyWebChromeClient extends WebChromeClient
{
public void onProgressChanged(WebView view, int progress)
{
progressBar.setProgress(progress);
}
}
HomeFragment extends Fragment
Button goToAmazon, goToFacebook;
String urlAmazon ="https://www.amazon.com";
String urlFacebook="https://www.facebook.com";
String urlDestination;
public HomeFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_home, container, false);
goToAmazon=v.findViewById(R.id.goToAmazon);
goToFacebook=v.findViewById(R.id.goToFacebook);
goToAmazon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
urlDestination=urlAmazon;
}
});
goToFacebook.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
urlDestination=urlFacebook;
}
});
return v;
}
Which code should I put in onClick() method to load the specific address in the webview and display the fragment containing webview?

Retrieve data from Firebase in Recycler view using fragment take too much time

I am using two fragments in the main activity, In first fragment[FirstFragment] load data from firebase and show in Recycler view, In the second fragment[uploadUserCarInformation] take data from user and store at the firebase,
I am facing a problem when the application starts then first fragment load very quickly and data show but when replace the first fragment from the second fragment and when replacing back from the second fragment to the first fragment then take 4 to 5 minutes to load data from firebase in recyclerView.
Kindly tell me where I modify the code,
Main Activity
public class MainActivity extends AppCompatActivity {
FrameLayout simpleFrameLayout;
TabLayout tabLayout;
Fragment fragment1 = new FirstFragment();
Fragment fragment2 =new SecondFragment();
#SuppressLint("WrongViewCast")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// get the reference of FrameLayout and TabLayout
tabLayout=findViewById(R.id.simpleTabLayout);
simpleFrameLayout = (FrameLayout) findViewById(R.id.simpleFrameLayout);
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment1);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
// perform setOnTabSelectedListener event on TabLayout
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
// get the current selected tab's position and replace the fragment accordingly
switch (tab.getPosition()) {
case 0:
tab.getIcon().setColorFilter(null);
fragmentReplace(fragment1,"fragment1");
break;
case 1:
fragmentReplace(fragment2,"fragment2");
break;
}
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
}
public void fragmentReplace(Fragment fragment,String fragmentName)
{
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
Log.d("Running Fragment",fragmentName+ " is running");
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
}
FirstFragment
public class FirstFragment extends Fragment {
private RecyclerView mRecyclerView;
private ImageAdapter mAdapter;
private DatabaseReference mDatabaseRef;
private List<carInformation> mUpload;
View view;
public FirstFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//retrieveAndSendData();
Log.d("Lifecycle","onCreate called");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d("Lifecycle","onCreateView called");
view=inflater.inflate(R.layout.fragment_first,container,false);
mRecyclerView=view.findViewById(R.id.recyler_view);
mRecyclerView.setHasFixedSize(true);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Log.d("Lifecycle","onViewCreate called");
retrieveAndSendData();
}
public void retrieveAndSendData()
{
mUpload=new ArrayList<>();
mDatabaseRef= FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener=new ValueEventListener() {
#Override
//get firebase data using datasnapshot (read data)
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for(DataSnapshot postSnapshot : dataSnapshot.getChildren())
{
String key = postSnapshot.getKey();
DatabaseReference databaseReference=mDatabaseRef.child(key);
for (DataSnapshot child: postSnapshot.getChildren())
{
String userBookId = child.getKey();
if(userBookId.equals("city") )
{
break;
}
else
{
// Toast.makeText(getActivity(),userBookId,Toast.LENGTH_LONG).show();
databaseReference.child(userBookId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
carInformation userInformationObj=dataSnapshot.getValue(carInformation.class);
mUpload.add(userInformationObj);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
mAdapter = new ImageAdapter(getActivity(),mUpload);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Toast.makeText(getActivity(),databaseError.getMessage(),Toast.LENGTH_SHORT).show();
}
};
mDatabaseRef.addValueEventListener(valueEventListener);
}
uploadUserCarInformation
public class uploadUserCarInformation extends Fragment {
View view;
FirebaseAuth firebaseAuth;
DatabaseReference databaseReference;
StorageReference storageReference;
private StorageTask mUploadTask;
ImageView imageView;
static int PICK_IMAGE=1;
Spinner spin;
// mdatabase.push().getkey() -> generate uniqe id
RadioGroup radioGroupCondition,radioGroupTransmission,radioGroupSupported;
RadioButton radioButtonCondition,radioButtonTranmission,radioButtonSupported;
String radioButtonConditionString,radioButtonSupportedString,radioButtonTransmissionString;
Button addCar,signout;
int selectedIdCondition,selectedIdTransmission,selectedIdSupported;
String ownerName,carName,phoneNuberString,countryString;
TextInputLayout name,carNamePlusModel,phoneNumber,country;
carInformation car_Information=new carInformation();
private ProgressBar progressBar;
private Uri imageUri;
String[] bankNames=new String[374];
InputStream in;
int i=0;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view=inflater.inflate(R.layout.upload_user_car_information,container,false);
firebaseAuth=FirebaseAuth.getInstance();
storageReference=FirebaseStorage.getInstance().getReference("uploads");
name=view.findViewById(R.id.textFieldCarOwner);
carNamePlusModel=view.findViewById(R.id.textFieldCarNameModel);
phoneNumber=view.findViewById(R.id.textFieldPhoneNumber2);
addCar=view.findViewById(R.id.addCar);
signout=view.findViewById(R.id.sign_out);
progressBar=view.findViewById(R.id.progress_bar);
// progressBar.getProgressDrawable().setColorFilter(
// Color.RED, android.graphics.PorterDuff.Mode.SRC_IN);
radioGroupCondition=view.findViewById(R.id.radioGroupCarCondtion);
radioGroupSupported=view.findViewById(R.id.radioGroupCarSupport);
radioGroupTransmission=view.findViewById(R.id.radioGroupCarTransmission);
// progressBar=new ProgressBar(getActivity());
spin = view.findViewById(R.id.Countryspinner2);
imageView=(ImageView) view.findViewById(R.id.selectImage);
//imageView.setImageResource(R.drawable.select_image);
try
{
InputStream fr = this.getResources().openRawResource(R.raw.cities);
BufferedReader br = new BufferedReader(new InputStreamReader(fr));
ArrayList<String> lines=new ArrayList<String>();
String currentLine=br.readLine();
while(currentLine!=null)
{
lines.add(currentLine);
currentLine=br.readLine();
}
Collections.sort(lines);
fr.close(); //closes the stream and release the resources
for(String line : lines)
{
bankNames[i]=line;
// System.out.println(line);
i++;
}
}
catch(IOException e)
{
e.printStackTrace();
}
ArrayAdapter<String> aa=new ArrayAdapter<String>(getActivity(),android.R.layout.simple_spinner_item,bankNames);
aa.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
AdapterView.OnItemSelectedListener listener = new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
};
spin.setOnItemSelectedListener(listener);
spin.setAdapter(aa);
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firebaseAuth.signOut();
Fragment fragment = new SecondFragment();
FragmentManager fm = getFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.simpleFrameLayout, fragment);
ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.commit();
}
});
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onFileChooser();
}
});
addCar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mUploadTask !=null && mUploadTask.isInProgress())
{
Toast.makeText(getActivity(),"Uploading Task",Toast.LENGTH_SHORT).show();
}
else
{
carImageAndDetailUploading();
}
}
});
return view;
}
#Override
public void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == PICK_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null)
{
imageUri = data.getData();
//A powerful image downloading and caching library and get image from library for Android
Picasso.with(getActivity()).load(imageUri).into(imageView);
}
}
private void carImageAndDetailUploading()
{
FirebaseUser user=firebaseAuth.getCurrentUser();
databaseReference= FirebaseDatabase.getInstance().getReference(user.getUid());
selectedIdCondition=radioGroupCondition.getCheckedRadioButtonId();
radioButtonCondition=view.findViewById(selectedIdCondition);
radioButtonConditionString=radioButtonCondition.getText().toString();
selectedIdSupported=radioGroupSupported.getCheckedRadioButtonId();
radioButtonSupported=view.findViewById(selectedIdSupported);
radioButtonSupportedString=radioButtonSupported.getText().toString();
selectedIdTransmission=radioGroupTransmission.getCheckedRadioButtonId();
radioButtonTranmission=view.findViewById(selectedIdTransmission);
radioButtonTransmissionString=radioButtonTranmission.getText().toString();
ownerName=name.getEditText().getText().toString().trim();
carName=carNamePlusModel.getEditText().getText().toString().trim();
phoneNuberString=phoneNumber.getEditText().getText().toString().trim();
countryString=spin.getSelectedItem().toString();
if(TextUtils.isEmpty(ownerName) || TextUtils.isEmpty(carName) || TextUtils.isEmpty(phoneNuberString) || TextUtils.isEmpty(countryString))
{
Toast.makeText(getActivity(),"Please fill the empty fields ",Toast.LENGTH_LONG).show();
return; //return stooping the function to execute further
}
else if(imageUri == null)
{
Toast.makeText(getActivity(),"No file Selected ",Toast.LENGTH_LONG).show();
return;
}
long phone=Long.parseLong(phoneNuberString);
car_Information.setCarName(carName);
car_Information.setOwnerName(ownerName);
car_Information.setUserPhoneNumber(phone);
car_Information.setCountry(countryString);
car_Information.setCarCondtion(radioButtonConditionString);
car_Information.setCarSupported(radioButtonSupportedString);
car_Information.setCarTransmission(radioButtonTransmissionString);
StorageReference fileReference=storageReference.child(System.currentTimeMillis()+ "." + getFileExtension(imageUri));
mUploadTask = fileReference.putFile(imageUri)
.addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
#Override
public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
//below code user can see 100 % progress bar for 5 sec
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
progressBar.setProgress(0);
}
},5000);
String uniqueKey=databaseReference.push().getKey();
Task<Uri> urlTask = taskSnapshot.getStorage().getDownloadUrl();
while (!urlTask.isSuccessful());
Uri downloadUrl = urlTask.getResult();
car_Information.setImageUrl(downloadUrl.toString());
car_Information.setUnique_key(uniqueKey);
// databaseReference.child("car details"+car_Information.getUnique_key());
// databaseReference.child("car details"+car_Information.getUnique_key()).setValue(car_Information);
databaseReference.child(car_Information.getUnique_key());
databaseReference.child(car_Information.getUnique_key()).setValue(car_Information);
Toast.makeText(getActivity(),"Successfully Upload",Toast.LENGTH_SHORT).show();
clear_editText();
}
})
.addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(getActivity(),e.getMessage(),Toast.LENGTH_SHORT).show();
}
})
.addOnProgressListener(new OnProgressListener<UploadTask.TaskSnapshot>() {
#Override
public void onProgress(UploadTask.TaskSnapshot taskSnapshot) {
double progress=(100.0 * taskSnapshot.getBytesTransferred() / taskSnapshot.getTotalByteCount());
progressBar.setProgress((int) progress);
}
});
}
private void onFileChooser()
{
Intent intent =new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent,PICK_IMAGE);
//startActivityForResult(Intent.createChooser(intent,"Select Picture"),PICK_IMAGE);
}
private String getFileExtension(Uri uri)
{
//this method for get file extension
ContentResolver cR=getActivity().getContentResolver();
MimeTypeMap mime=MimeTypeMap.getSingleton();
return mime.getExtensionFromMimeType(cR.getType(uri));
}
private void clear_editText()
{
name.getEditText().setText(" ");
carNamePlusModel.getEditText().setText(" ");
phoneNumber.getEditText().setText(" ");
}
}
enter image description here
enter image description here

Getting a Fragment inside a ViewPager in Android using getRegisteredFragment returns null

I've been searching a lot and I can't make it work.
I have a problem trying to get fragments inside a viewpager with a tabstrip.
I've implemented a SparseArray as I read here and several methods that I found here but I can't make it work.
The thing is that everytime I call adapter.getRegisteredFragment(position).. I always receive null unless I made it inside the onPageSelected event of the tabsStrip, there it works.. but I don't want to get the fragments there.
Those are my classes:
My fragment:
public class WeekFragment extends Fragment implements View.OnClickListener
{
private static final String ARG_POSITION = "position";
private int position;
private LinearLayout[] btns;
public static WeekFragment newInstance(int position) {
WeekFragment f = new WeekFragment();
Bundle b = new Bundle();
b.putInt(ARG_POSITION, position);
f.setArguments(b);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
position = getArguments().getInt(ARG_POSITION);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
fillFragment();
}
private void fillFragment()
{
// Irrelevant stuff..
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstance)
{
return inflater.inflate(R.layout.week_fragment, container, false);
}
#Override
public void onClick(View v)
{
// Irrelevant stuff
}
public LinearLayout[] getBtns()
{
return btns;
}
public void setBtns(LinearLayout[] btns)
{
this.btns = btns;
}
}
My adapter:
public class WeekAdapter extends FragmentPagerAdapter
{
Calendar cal;
Context context;
SparseArray<Fragment> registeredFragments;
private String[] TITLES = new String[6];
public WeekAdapter(FragmentManager fm, Context context)
{
super(fm);
registeredFragments = new SparseArray<>();
this.context = context;
fillTitles();
}
private void fillTitles()
{
// Fill titles
}
#Override
public CharSequence getPageTitle(int position)
{
return TITLES[position];
}
#Override
public int getCount()
{
return TITLES.length;
}
#Override
public Fragment getItem(int position)
{
return WeekFragment.newInstance(position);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
and my activity:
public class MyActivity extends FragmentActivity
{
private PagerSlidingTabStrip tabs;
private ViewPager pager;
private WeekAdapter adapter;
private List<DayResumeItem> listDayResumesItems;
private User u;
private View mProgressView;
private View mRotaView;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rota2);
mProgressView = findViewById(R.id.view_progress);
mRotaView = findViewById(R.id.view_rota);
this.u = this.getIntent().getExtras().getParcelable(getString(R.string.parcel_user));
// Initialize the ViewPager and set an adapter
pager = (ViewPager) findViewById(R.id.pager);
adapter = new WeekAdapter(getSupportFragmentManager(), getApplicationContext());
pager.setAdapter(adapter);
// Bind the tabs to the ViewPager
tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabs.setViewPager(pager);
tabs.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
WeekFragment f = (WeekFragment)adapter.getRegisteredFragment(week);
// Do stuff.. Here, f is not null. Here I can work, but I don't want to.
}
#Override
public void onPageSelected(int position)
{
}
#Override
public void onPageScrollStateChanged(int state)
{
}
});
WeekFragment f = (WeekFragment)adapter.getRegisteredFragment(week);
// Do stuff.. Here, f is null and I can't work.
}
#Override
protected void onResume()
{
super.onResume();
getList();
}
}
It is everytime I call adapter.getRegisteredFragment(position) on my activity where it crash because it always return null..
I swear that I've been searching a lot but I'm unable to make it work.
Thank you very much everybody!
I think my problem was that I was calling this adapter.getRegisteredFragment(position) in the onCreate of my activity, and in the onCreate, the viewpager is still not fully loaded and the registeredFragments aren't still instantiated, so the list is still empty..
If you move this callings to another place when the viewpager is fully loaded, it will work.
The items in registeredFragments are initialized in instantiateItem() method, which should be called during the process of drawing views. And this drawing process happens after onCreate()/onResume().
I am not sure what stuff you want to do by getting Fragment in onCreate(), but generally it is not a good idea since the Fragment is not initialized at that moment. You should access the fragment in onPageSelected() as you said.

Saving GridView state in a Fragment (Android) on Back Button

In my android application, I am switching between the two set of images-(Set1, Set2) displayed in a GridView-A inside a Fragment-A.I am doing this on a button press using a boolean variable. Clicking on any GridView icon leads to another Fragment-B. The problem is when I press back button on Fragment-B , the Fragment-A is always loaded with the images of Set1 by default. I want the same set of images (Set1 or Set2 ) to be loaded on FramentA that were displayed before going to FragmentB.
EDITED:
Fragment Code
public class GridViewFragment extends Fragment {
Context context;
GridView GridMenu;
GridViewAdapter ga;
Button Btn_Settings;
Button Btn_lang_Ch;
Button favoriteDuas;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//fragment = new GridViewFragment();
if (view == null) {
context = inflater.getContext();
view = inflater.inflate(R.layout.fragment_gridview, container, false);
ga = new GridViewAdapter(context);
Btn_lang_Ch = (Button) view.findViewById(R.id.lng_ch);
Btn_Settings = (Button) view.findViewById(R.id.button_settings);
favoriteDuas = (Button) view.findViewById(R.id.btn_favorite_duas);
GridMenu = (GridView) view.findViewById(R.id.gridView1);
GridMenu.setAdapter(ga);
} else {
// remove view from previously attached ViewGroup
ViewGroup parent = (ViewGroup) view.getParent();
parent.removeView(view);
}
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setRetainInstance(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
Btn_lang_Ch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ga.changeImages(!ga.imageSetChange);
ga.Lang_Status();
}
});
GridMenu.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
((MainActivity) context).loadSingleDuaFragment();
}
});
super.onActivityCreated(savedInstanceState);
}
}
GridView Adapter
public class GridViewAdapter extends BaseAdapter {
public boolean imageSetChange = false;
public static boolean curr_lang = false;//english
public Integer[] mThumbIds = {
R.drawable.eng_pic1, R.drawable.eng_pic2,
R.drawable.eng_pic3, R.drawable.eng_pic4,
R.drawable.eng_pic5, R.drawable.eng_pic6,
R.drawable.eng_pic7, R.drawable.eng_pic8,
R.drawable.eng_pic9, R.drawable.eng_pic10,
R.drawable.eng_pic11, R.drawable.eng_pic12,
R.drawable.eng_pic13, R.drawable.eng_pic14,
R.drawable.eng_pic15, R.drawable.eng_pic16,
R.drawable.eng_pic17, R.drawable.eng_pic18,
R.drawable.eng_pic19, R.drawable.eng_pic20,
R.drawable.eng_pic21
};
public Integer[] mThumbIds1 = {
R.drawable.urdu_dua1, R.drawable.urdu_dua2,
R.drawable.urdu_dua3, R.drawable.urdu_dua4,
R.drawable.urdu_dua5, R.drawable.urdu_dua6,
R.drawable.urdu_dua7, R.drawable.urdu_dua8,
R.drawable.urdu_dua9, R.drawable.urdu_dua10,
R.drawable.urdu_dua11, R.drawable.urdu_dua12,
R.drawable.urdu_dua13, R.drawable.urdu_dua14,
R.drawable.urdu_dua15, R.drawable.urdu_dua16,
R.drawable.urdu_dua17, R.drawable.urdu_dua18,
R.drawable.urdu_dua19, R.drawable.urdu_dua20,
R.drawable.urdu_dua21
};
private Context mContext;
public GridViewAdapter(Context c) {
mContext = c;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mThumbIds.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return mThumbIds[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View MyView;
if (convertView == null) {
LayoutInflater li = ((Activity) mContext).getLayoutInflater();
MyView = li.inflate(R.layout.menuitem, parent, false);
} else {
MyView = (View) convertView;
}
ImageView iv = (ImageView) MyView.findViewById(R.id.image);
if (imageSetChange) {
iv.setImageResource(mThumbIds1[position]);
} else {
iv.setImageResource(mThumbIds[position]);
}
return MyView;
}
public void changeImages(boolean change) {
this.imageSetChange = change;
notifyDataSetChanged();
// gf.Lang_Status();
}
public void Lang_Status() {
// if curr_eng
if (!curr_lang)
this.curr_lang = true; // change to urdu
// if curr_urdu
else
this.curr_lang = false; // change to english
}
}
EDIT:
MainActivity
public void loadGridViewFragment() {
if (activityActive) {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if(getSupportFragmentManager().findFragmentByTag(GridViewFragment.TAG)!=null){
ft.replace(R.id.fl_view, frag,GridViewFragment.TAG);
}
else
{
frag = new GridViewFragment();
ft.replace(R.id.fl_view, frag,GridViewFragment.TAG);
}
ft.commit();
}
}
So, can anybody help me out regarding what should be done to load the previous set of images on coming back to gridview fragment instead of having the default images of Set1.

Resources