I have an activity who load a list of data, this activity its a TabActivity with 3 Tabs, all tabs load a diferent data type.
But the data may be really a bunch of data, for that reason my activity may take a lot of time to show itself.
I start teh activity using
Intent intent = new Intent(MainActivity.this, PcapAnalisys.class);
startActivity(intent);
Then, when the activity is loading shows a black screen, and after a few seconds show the content properly.
There is a way on how to show a message like: "Loading activity... please wait" or something?
This is my code for a my TabActivity:
public class PcapAnalysis extends AppCompatActivity {
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
private TabLayout tabLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pcap_analysis);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mViewPager = (ViewPager) findViewById(R.id.container);
tabLayout = (TabLayout) findViewById(R.id.tabs);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//fab.setImageResource(R.drawable.ic_attach_file_white_24dp);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
FileChooserDialog dialog = new FileChooserDialog(PcapAnalysis.this);
dialog.show();
dialog.addListener(new FileChooserDialog.OnFileSelectedListener() {
#Override
public void onFileSelected(Dialog source, File file) {
source.hide();
Toast.makeText(source.getContext(),
"File selected: " + file.getAbsolutePath(),
Toast.LENGTH_LONG).show();
Log.i("Archivo seleccionado", file.getAbsolutePath());
new AsyncTask_load(PcapAnalysis.this, file.getAbsolutePath()).execute();
}
public void onFileSelected(Dialog source, File folder, String name) {
source.hide();
Toast.makeText(source.getContext(),
"File created: " + folder.getName() + "/" + name,
Toast.LENGTH_LONG).show();
}
});
}
});
new Task().execute();
}
#Override
public void recreate()
{
super.recreate();
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_pcap_analysis, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/*public static class PlaceholderFragment extends Fragment {
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_pcap_analysis, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
return rootView;
}
}*/
private class Task extends AsyncTask<Void, Integer, Void> {
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(PcapAnalysis.this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setMessage("Procesando...");
pDialog.setCancelable(true);
pDialog.setMax(100);
pDialog.setCanceledOnTouchOutside(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... voids) {
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager.setOffscreenPageLimit(3); //cuantas paginas se precargan
mViewPager.setAdapter(mSectionsPagerAdapter);
tabLayout.setupWithViewPager(mViewPager);
//publishProgress(progress);
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
}
#Override
protected void onPostExecute(Void result) {
pDialog.dismiss();
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private Fragment http = new HttpList();
private Fragment dns = new DnsList();
private Fragment ip = new IpList();
private Fragment resume = new ResumeList();
SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
//return PlaceholderFragment.newInstance(position + 1);
switch (position) {
case 0:
return http;
case 1:
return dns;
case 2:
return ip;
case 3:
return resume;
}
return null;
}
#Override
public int getCount() {
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "HTTP";
case 1:
return "DNS";
case 2:
return "RESOURCE IP";
case 3:
return "RESUME";
}
return null;
}
}
}
As you can see this activity use fragments to show the data, and each fragment has a for cicle to load the data (that is in a String array).
Also I use a AsyncTask trying to solve this problem, but is not working. Please help!
Related
I'm using the firebaseRecyclerAdaper on a fragment and i want to open an item from de populated list from firebase and send the data to a new fragment. Can u guys tell me please how can i start the FragmentDetail from the onCLickListener on FragmentAllPosts and pass the PostModel parameter to it?
Main Activity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private static final String TAG = "TAG" ;
private FirebaseAuth firebaseAuth;
private DatabaseReference databaseReference , postsRef;
private StorageReference profileImgRef;
private CircleImageView circleImageViewMain;
private TextView nameEdtTxt, emailEdtTxt;
Fragment fragment= null;
private RecyclerView recyclerView;
private FloatingActionButton fab;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
progressDialog= new ProgressDialog(this);
progressDialog.setMessage("Please wait!");
progressDialog.setCanceledOnTouchOutside(false);
//Initialize Firebase modules
firebaseAuth=FirebaseAuth.getInstance();
databaseReference= FirebaseDatabase.getInstance().getReference().child("users");
postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
profileImgRef= FirebaseStorage.getInstance().getReference();
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
View header = navigationView.getHeaderView(0);
circleImageViewMain = (CircleImageView) header.findViewById(R.id.circleImageHeader);
nameEdtTxt = (TextView) header.findViewById(R.id.txtName);
emailEdtTxt =(TextView)header.findViewById(R.id.txtEmail);
if (firebaseAuth.getCurrentUser()!=null){
LoadUserData(CheckUserDataBase());
}
ViewPager vp_pages= (ViewPager) findViewById(R.id.vp_pages);
PagerAdapter pagerAdapter=new FragmentAdapter(getSupportFragmentManager());
vp_pages.setAdapter(pagerAdapter);
TabLayout tbl_pages= (TabLayout) findViewById(R.id.tabs);
tbl_pages.setupWithViewPager(vp_pages);
tbl_pages.setTabTextColors(ColorStateList.valueOf(Color.parseColor("#FFFFFF")));
tbl_pages.setHorizontalScrollBarEnabled(true);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
fragment= new AddPostFrag();
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.add(R.id.add_post_container, fragment).commit();
fab.hide();
}
});
}
class FragmentAdapter extends FragmentPagerAdapter {
public FragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
return new FragmentAllPosts();
case 1:
return new FragmentLosts();
case 2:
return new FragmentFounds();
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position){
//
//Your tab titles
//
case 0:return "All";
case 1:return "Losts";
case 2: return "Founds";
default:return null;
}
}
}
#Override
protected void onStart() {
super.onStart();
FirebaseUser user= firebaseAuth.getCurrentUser();
if (user == null){
SendUserToLogin();
} else {
CheckUserDataBase();
}
}
public static class PostsViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
ImageView imageView;
TextView authorNdate, location, description;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
circleImageView= itemView.findViewById(R.id.circleImageView_cv);
imageView= itemView.findViewById(R.id.imageView_cv);
authorNdate= itemView.findViewById(R.id.author_date_cv);
location = itemView.findViewById(R.id.location_cv);
description = itemView.findViewById(R.id.description_cv);
}
}
private void UpdateHome() {
}
private void LoadUserData(final String uid) {
try {
final File localFile =File.createTempFile("profile","png");
StorageReference filepath=profileImgRef.child(uid).child("profileImg/profile.png");
filepath.getFile(localFile)
.addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
#Override
public void onSuccess(FileDownloadTask.TaskSnapshot taskSnapshot) {
Picasso.get()
.load(localFile)
.placeholder(R.drawable.ic_account)
.into(circleImageViewMain);
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Toast.makeText(MainActivity.this,
"Profile photo not found, please update your profile!",
Toast.LENGTH_SHORT).show();
SendUserToSetup();
}
});
} catch (IOException e) {
e.printStackTrace();
}
databaseReference.child(uid).child("userInfo").addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.hasChild("name")){
String name = dataSnapshot.child("name").getValue().toString();
nameEdtTxt.setText(name);
String email = dataSnapshot.child("email").getValue().toString();
emailEdtTxt.setText(email);
} else {
Toast.makeText(MainActivity.this,
"Profile name does not exists, please update your profile",
Toast.LENGTH_SHORT).show();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
}
#Override
protected void onStop() {
super.onStop();
}
private String CheckUserDataBase() {
final String userID =firebaseAuth.getCurrentUser().getUid();
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (!dataSnapshot.child(userID).hasChild("userInfo")){
SendUserToSetup();
} else {
UpdateHome();
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
}
);
return userID;
}
private void SendUserToSetup() {
Intent i = new Intent(this,SetupActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
private void SendUserToLogin() {
Intent i = new Intent(this,LoginActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(i);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else if (getSupportFragmentManager().getBackStackEntryCount() >0)
{
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
} else
{
super.onBackPressed();
}
fab.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id){
case R.id.nav_home:
super.onResume();
if (fragment!=null){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction= fragmentManager.beginTransaction();
transaction.remove(fragment).commit();
fab.show();
}
break;
case R.id.nav_profile:
super.onPause();
break;
case R.id.nav_my_posts:
super.onPause();
break;
case R.id.nav_messeges:
super.onPause();
break;
case R.id.nav_settings:
super.onPause();
break;
case R.id.nav_logout:
SendUserToLogin();
firebaseAuth.signOut();
break;
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Fragment with the FirebaseRecyclerAdapter
public class FragmentAllPosts extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
private DatabaseReference postsRef;
private Context context= getContext();
Fragment mFragment;
Bundle mBundle;
public FragmentAllPosts() {
// Required empty public constructor
}
public static FragmentAllPosts newInstance(String param1, String param2) {
FragmentAllPosts fragment = new FragmentAllPosts();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
private RecyclerView recyclerAllPosts;
private ProgressDialog progressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
progressDialog= new ProgressDialog(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_all_posts,container,false);
postsRef= FirebaseDatabase.getInstance().getReference().child("posts");
recyclerAllPosts= v.findViewById(R.id.recycler_all_posts);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
linearLayoutManager.setReverseLayout(true);
linearLayoutManager.setStackFromEnd(true);
recyclerAllPosts.setLayoutManager(linearLayoutManager);
return v;
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
this.context=context;
}
#Override
public void onStart() {
super.onStart();
progressDialog.show();
FirebaseRecyclerOptions<PostsModel> options=
new FirebaseRecyclerOptions.Builder<PostsModel>()
.setQuery(postsRef,PostsModel.class)
.setLifecycleOwner(this)
.build();
FirebaseRecyclerAdapter<PostsModel,PostsViewHolder> adapter=
new FirebaseRecyclerAdapter<PostsModel, PostsViewHolder>(options) {
#Override
protected void onBindViewHolder(#NonNull final PostsViewHolder holder, int position, #NonNull final PostsModel model) {
String processedTime= CalculateTime(model.getData());
Picasso.get().load(Uri.parse(model.getUserImg())).into(holder.circleImageView);
Picasso.get().load(Uri.parse(model.getImageUri())).into(holder.imageView);
holder.authorNdate.setText(model.getAuthor()+" updated "+processedTime);
holder.location.setText(model.getLocation());
holder.description.setText(model.getDescription());
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Fragment frag= new FragmentDetail();
getFragmentManager().beginTransaction().replace(R.id.add_post_container,frag)
.addToBackStack(null).commit();
}
});
}
#NonNull
#Override
public PostsViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view= LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.card_view,viewGroup,false );
PostsViewHolder viewHolder= new PostsViewHolder(view);
return viewHolder;
}
};
recyclerAllPosts.setAdapter(adapter);
progressDialog.dismiss();
adapter.startListening();
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
public String CalculateTime(String inputTime){
String timeOut;
Calendar currentTime= Calendar.getInstance();
SimpleDateFormat dateFormat= new SimpleDateFormat(getString(R.string.date_format));
dateFormat.format(currentTime.getTime());
SimpleDateFormat postFormat= new SimpleDateFormat(getString(R.string.date_format));
Calendar postTime = Calendar.getInstance();
try {
Date datePost=postFormat.parse(inputTime);
postTime.setTime(datePost);
} catch (ParseException e) {
e.printStackTrace();
}
long timeCurrent= currentTime.getTimeInMillis();
long timePost = postTime.getTimeInMillis();
long diff= timeCurrent- timePost;
long minutes= diff/(60*1000);
long hours = diff/(60 * 60 * 1000);
long days = diff/(24 * 60 * 60 * 1000);
if (minutes<59 && minutes>1){
timeOut=Long.toString(minutes)+" mins ago";
} else if (minutes<1){
timeOut=" just now";
}else if (hours<24 && minutes>59){
timeOut=Long.toString(hours)+" hour(s) ago";
}else {
timeOut=Long.toString(days)+" day(s) ago";
}
return timeOut;
}
static class PostsViewHolder extends RecyclerView.ViewHolder {
CircleImageView circleImageView;
ImageView imageView;
TextView authorNdate, location, description;
public PostsViewHolder(#NonNull View itemView) {
super(itemView);
itemView.setTag(this);
circleImageView= itemView.findViewById(R.id.circleImageView_cv);
imageView= itemView.findViewById(R.id.imageView_cv);
authorNdate= itemView.findViewById(R.id.author_date_cv);
location = itemView.findViewById(R.id.location_cv);
description = itemView.findViewById(R.id.description_cv);
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
Detail Fragment:
public class FragmentDetail extends Fragment {
public FragmentDetail() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_detail, container, false);
}
}
I'd suggest a read on the documentation. Passing data between two activities should be done via interfaces.
As suggested by the official site
I got a problem with updating ViewPager fragments. We need to show fragments with data to registered user, when he doesn't registered we need to show fragments with message to register. I use this method to check it in MainActivity:
#Override
public void setAdapter(boolean isUserExist) {
Log.d("RegDebug", "In setAdapter");
mainPagerAdapter.clearData();
mainPagerAdapter.addFragment(searchFragment, getString(R.string.search_title));
if (isUserExist) {
Log.d("RegDebug", "In setAdapter reg");
mainPagerAdapter.addFragment(new ChatsFragment(), getString(R.string.chats_title));
mainPagerAdapter.addFragment(new ActionsFragment(), getString(R.string.actions_title));
Toast.makeText(getApplicationContext(), "Registered!", Toast.LENGTH_SHORT).show();
} else {
Log.d("RegDebug", "In setAdapter unreg");
mainPagerAdapter.addFragment(RegisterFragment.newInstance(Consts.CHATS_TAB_NAME), getString(R.string.chats_title));
mainPagerAdapter.addFragment(RegisterFragment.newInstance(Consts.ACTIONS_TAB_NAME), getString(R.string.actions_title));
Toast.makeText(getApplicationContext(), "Unregistered!!!", Toast.LENGTH_SHORT).show();
}
mainPagerAdapter.notifyDataSetChanged();
viewPager.setAdapter(mainPagerAdapter);
}
I call this method in presenter with setting value from firebase auth, checking if user exists:
public void checkForUserExist() {
if (mainInteractor.isUserExist()) {
getViewState().setRegAdapter();
} else getViewState().setUnregAdapter();
}
And then call presenter method in onCreate of MainActivity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialogFragment = new FilterDialogFragment();
searchFragment = new SearchFragment();
//UI
toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
viewPager = findViewById(R.id.main_view_pager);
tabLayout = findViewById(R.id.main_tabs);
//mainPagerAdapter = new MainPagerAdapter(getSupportFragmentManager());
mainPresenter.checkForUserExist();
tabLayout.setupWithViewPager(viewPager);
}
I try to log the boolean result and it returns exactly value that must be, but pager adapter can't update its content.Code of MainPagerAdapter:
public class MainPagerAdapter extends FragmentPagerAdapter{
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> fragmentTitleList = new ArrayList<>();
public MainPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return fragmentTitleList.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragmentTitleList.get(position);
}
public void addFragment(Fragment fragment, String title){
fragmentList.add(fragment);
fragmentTitleList.add(title);
}
public void clearData(){
fragmentList.clear();
fragmentTitleList.clear();
notifyDataSetChanged();
Log.d("RegDebug", " fragmentList size is " + fragmentList.size()
+ " fragmentTitleList size is " + fragmentTitleList.size());
}
}
Use OnPageChangeListener of ViewPager class & notify to your current fragment from there using interface.
This is kind of hard to explain so I took screenshots of my problem.
So this is my MainActivity.java
I open the navigation drawer and click on Milestones which will bring me to Milestones.java
Here I am at Milestones.java fragment...
working fine for now...
Just how I want it to look.
But when we leave Milestones and go anywhere else and come back it will be messed up. So I will go to Kick Counter.
Here I am in my KickCounter.java fragment
Open navigation drawer and going back to Milestones...
So right now I have fragment Months0Through6 open with Milestones fragment. Some times Months0Through6 and Month12Plus fragments does not show up right away after coming back some times it does. What is always messed up at this point is the Months6Through12 fragment will never display again unless you restart the app. Also swapping between the three fragments is laggy after coming back but never on first view.
Here it is. Where did it go?
youtube video: https://www.youtube.com/watch?v=6yMYcluvqbs
Get Source Here: https://github.com/delaroy/RecyclerViewFragment
I got my code from this youtube video which is almost exactly identical but his MainActivity (which I made into my Milestones fragment) is an activity whereas I used a fragment so I was thinking that might have something to do with my problem.
Milestones.java
public class Milestones extends Fragment {
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private OnFragmentInteractionListener mListener;
public Milestones() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment Milestones.
*/
// TODO: Rename and change types and number of parameters
public static Milestones newInstance(String param1, String param2) {
Milestones fragment = new Milestones();
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) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_milestones, container, false);
Toolbar toolbar = (Toolbar) rootView.findViewById(R.id.toolbar);
ViewPager viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
//dont know if this will work
PagerAdapter pagerAdapter = new PagerAdapter(getFragmentManager(), getContext());
viewPager.setAdapter(pagerAdapter);
TabLayout tabLayout = (TabLayout) rootView.findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
for(int i = 0; i < tabLayout.getTabCount(); i++){
TabLayout.Tab tab = tabLayout.getTabAt(i);
tab.setCustomView(pagerAdapter.getTabView(i));
}
// Inflate the layout for this fragment
return rootView;
}
// not boiler plate
#Override
public void onResume() {
super.onResume();
}
// probably just adding extra menu dont need it
/*#Override
public boolean onCreateOptionsMenu(Menu menu){
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
*/
//not boilerplate
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id = item.getItemId();
if(id == R.id.action_settings){
return true;
}
return super.onOptionsItemSelected(item);
}
//not boilerplate
class PagerAdapter extends FragmentPagerAdapter {
String tabTitles[] = new String[]{"0-6 Months", "6-12 Months", "12+ Months"};
Context context;
public PagerAdapter(FragmentManager fm, Context context) {
super(fm);
this.context = context;
}
#Override
public int getCount() {
return tabTitles.length;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Months0Through6();
case 1:
return new Months6Through12();
case 2:
return new Months12Plus();
}
return null;
}
#Override
public CharSequence getPageTitle(int position){
return tabTitles[position];
}
public View getTabView(int position){
View tab = LayoutInflater.from(getContext()).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#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 interface must be implemented by activities that contain this
* fragment to allow an interaction in this fragment to be communicated
* to the activity and potentially other fragments contained in that
* activity.
* <p>
* See the Android Training lesson <a href=
* "http://developer.android.com/training/basics/fragments/communicating.html"
* >Communicating with Other Fragments</a> for more information.
*/
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
MilestonesAdapter.java
public class MilestonesAdapter extends RecyclerView.Adapter<MilestonesAdapter.MyViewHolder> {
private String[] mDataset;
public static class MyViewHolder extends RecyclerView.ViewHolder{
public CardView mCardView;
public TextView mTextView;
public MyViewHolder(View v){
super(v);
mCardView = (CardView) v.findViewById(R.id.card_view);
mTextView = (TextView) v.findViewById(R.id.tv_text);
}
}
public MilestonesAdapter(String[] myDataset){
mDataset = myDataset;
}
#Override
public MilestonesAdapter.MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_item, parent, false);
MyViewHolder vh = new MyViewHolder(v);
return vh;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
holder.mTextView.setText(mDataset[position]);
}
#Override
public int getItemCount() { return mDataset.length; }
Just posting Months0Through6.java because the other two are exactly the same just different strings.
public class Months0Through6 extends android.support.v4.app.Fragment {
public Months0Through6() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_blank, container, false);
RecyclerView rv = (RecyclerView) rootView.findViewById(R.id.rv_recycler_view);
rv.setHasFixedSize(true);
MilestonesAdapter adapter = new MilestonesAdapter(new String[]{"Month 0 stuff", "Example Two", "Example Three", "Example Four", "Example Five" , "Example Six" , "Example Seven"});
rv.setAdapter(adapter);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
rv.setLayoutManager(llm);
return rootView;
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity
implements KickCounter.OnFragmentInteractionListener, MommyMetrics.OnFragmentInteractionListener, Milestones.OnFragmentInteractionListener, NavigationView.OnNavigationItemSelectedListener {
Intent shareIntent;
String sharetext = "Hey check out mommy-info here at http://www.mommy-info.com";
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//Connects to www.mommy-info.com
myWebView = (WebView)findViewById(R.id.webView_ID);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.loadUrl("http://www.mommy-info.com");
myWebView.setWebViewClient(new WebViewClient());
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
//back button in navigation drawer logic
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
}
//back button in webView logic
else if(myWebView.canGoBack()){
myWebView.goBack();
}
else if(getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStack();
}
else{
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.kick_counter_ID) {
KickCounter kickCounter = new KickCounter();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, kickCounter).addToBackStack(null).commit();
} else if (id == R.id.nav_mommy_metrics) {
MommyMetrics mommyMetrics = new MommyMetrics();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, mommyMetrics).addToBackStack(null).commit();
} else if (id == R.id.nav_milestones) {
Milestones milestones = new Milestones();
android.support.v4.app.FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.full_screen_ID, milestones).addToBackStack(null).commit();
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_SUBJECT, "my app");
shareIntent.putExtra(Intent.EXTRA_TEXT, sharetext);
startActivity(Intent.createChooser(shareIntent, "share via"));
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onFragmentInteraction(Uri uri) {
}
In Fragments you need to use getChildFragmentManager(), You are using same Fragment manager in the fragments as in Activity. Hope this will help
I have developed a app in which we can change ip address to connect to database running on xampp server..
This is my MainActivity.java
In which I declared a public static string variable called "ip" and set a default value for it. I changed this ip using menu option using alert box. and when displayed the changed ip using snackbar it shows changes. But trying to access that "ip" in another activity called "doctor_login.java" by Mainactivity.ip. It does not takes changed ip instead it takes default ip itself. Below I have shown screenshots and code. Please help me in this issue.
public class MainActivity extends AppCompatActivity { public static String ip="192.168.43.97";// This is default ip
public static final String dbuser = "root";
public static final String dbpass = "kughan";
private SectionsPagerAdapter mSectionsPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "App by KUGHAN EV", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
AlertDialog.Builder ipalert = new AlertDialog.Builder(MainActivity.this);
ipalert.setCancelable(false);
ipalert.setTitle("Change IP");
ipalert.setMessage("Enter your server ip below:");
final EditText input = new EditText(MainActivity.this);
input.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
RelativeLayout.LayoutParams lp=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
input.setLayoutParams(lp);
ipalert.setView(input);
ipalert.setPositiveButton("CHANGE", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String cip=input.getText().toString();
ip=cip; // Trying to change ip address from edittext
Snackbar.make(getCurrentFocus(),"Ip changed to "+ip,Snackbar.LENGTH_LONG).setAction(null,null).show();
}
});
ipalert.setNegativeButton("CANCEL",null);
ipalert.show();
}
if(id== R.id.showip){
Snackbar.make(getCurrentFocus(),"Your IP is "+ip,Snackbar.LENGTH_LONG).setAction(null,null).show();
}
return super.onOptionsItemSelected(item);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position){
case 0:
doctor_login tab1 = new doctor_login();
return tab1;
case 1:
patient_login tab2 = new patient_login();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
// Show 3 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "DOCTOR";
case 1:
return "PATIENT";
}
return null;
}
}
//This is my doctor_login activity
public class doctor_login extends Fragment {
public static String logged;
public static String loggedid;
private String url;
private static final String user = MainActivity.dbuser;
private static final String pass = MainActivity.dbpass;
EditText usertxt,passtxt;
Button login,reg;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
final View rootView = inflater.inflate(R.layout.activity_doctor_login, container, false);
url ="jdbc:mysql://"+MainActivity.ip+":3306/mediapp"; //getting value from mainactivity ip value
usertxt=(EditText) rootView.findViewById(R.id.editText);
passtxt=(EditText)rootView.findViewById(R.id.editText2);
login=(Button)rootView.findViewById(R.id.button);
reg=(Button)rootView.findViewById(R.id.button2);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(usertxt.getText().toString().length()==0 || passtxt.getText().toString().length()==0){
Snackbar.make(getView(),"Fill all credential details",Snackbar.LENGTH_LONG).setAction("Action",null).show();
}else{
testDB();
}
}
});
reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent1 = new Intent(doctor_login.this.getActivity(),doctor_signup.class);
startActivity(intent1);
}
});
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Snackbar.make(getView(),"Welcome to DigiMedApp",Snackbar.LENGTH_LONG).setAction("Action",null).show();
}
public void testDB(){
Toast.makeText(getContext(),url,Toast.LENGTH_LONG).show();
try
{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url,user,pass);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select name,id from doctorlogin where username='"+usertxt.getText().toString()+"' and password='"+passtxt.getText().toString()+"';");
if(rs.next()){
logged=rs.getString(1);
loggedid=rs.getString(2);
Toast.makeText(getContext(),"Welcome "+rs.getString(1),Toast.LENGTH_LONG).show();
Intent intent = new Intent(doctor_login.this.getActivity(),doctor_home.class);
startActivity(intent);
} else
{
Snackbar.make(getView(),"Wrong Username or password",Snackbar.LENGTH_LONG).setAction("Action",null).show();
}
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(getContext(),e.toString(),Toast.LENGTH_LONG).show();
}
}
}
Changing the ip using alertdialog
See the editetxt__Screenshot
When trying to login from doctor_login page it shows connection exception as you can see the ip on which it is trying to connect even after changing the ip
Exeption__Screenshot
Here :
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
final View rootView = inflater.inflate(R.layout.activity_doctor_login, container, false);
url ="jdbc:mysql://"+MainActivity.ip+":3306/mediapp"; //getting value from mainactivity ip value
The doctor_login fragment is created before the ip change in MainActivity.
This valuation is so not at the convenient place as url will use the MainActivity.ip value present during its initialization and will not take into consideration ip change performed by the user in MainActivity.
To solve your problem, generate the url with the IP in the testDB() method.
Replace
public void testDB(){
Toast.makeText(getContext(),url,Toast.LENGTH_LONG).show();
by
public void testDB(){
url ="jdbc:mysql://"+MainActivity.ip+":3306/mediapp";
Toast.makeText(getContext(),url,Toast.LENGTH_LONG).show();
I'm currently using FragmentStatePagerAdapter and I would like it to have a "navigate up" feature (DisplayHomeAsUpEnabled). When I set the following code it shows up as a correct navigate back button. But nothing happens when I click on it, can you guys see anything that I', doing wrong in my code, I get no error while pressing the "navigate up" button and I get no compiler errors.
Here is the code, its in the "public boolean onOptionsItemSelected(MenuItem item) {" it gets interesting at the bottom.
public class ShareholdingDetailFragment extends FragmentActivity {
final int NUM_ITEMS = Portfolio.getPortfolio().count();
MyAdapter mAdapter;
ViewPager mPager;
Bundle extras;
#Override
protected void onCreate(Bundle savedInstanceState) {
System.out.println(NUM_ITEMS + "e");
super.onCreate(savedInstanceState);
setContentView(R.layout.shareholdingdetailview_fragment_wrapper);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
}
public class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
public int getCount() {
return NUM_ITEMS;
}
public Fragment getItem(int position) {
return ShareholdingFragment.newInstance(position);
}
}
public static class ShareholdingFragment extends Fragment {
int mNum;
static ShareholdingFragment newInstance(int num) {
ShareholdingFragment f = new ShareholdingFragment();
// Supply num input as an argument.
Bundle args = new Bundle();
args.putInt("num", num);
f.setArguments(args);
return f;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mNum = getArguments() != null ? getArguments().getInt("num") : 1;
}
#SuppressLint({ "NewApi", "NewApi" })
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.shareholdingdetailview_fragment, container, false);
/****************Setting the Display as home and it shows*******************/
ActionBar bar = getActivity().getActionBar();
bar.setDisplayHomeAsUpEnabled(true);
/**********************************/
return view;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home://Not working
System.out.println("test");//This isn't printed out
Intent upIntent = new Intent(getActivity(), DetailShareHoldingActivity.class);
if (NavUtils.shouldUpRecreateTask(getActivity(), upIntent)) {
getActivity().finish();
} else {
NavUtils.navigateUpTo(getActivity(), upIntent);
}
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
Try adding: setHasOptionsMenu(true); in your onCreate() in ShareholdingFragment.
Add setHomeButtonEnabled(true) on API Level 14 and higher when you configure your action bar. On API Level 11-13, the home button is enabled automatically.
If you're using the new Toolbar and ActionbarDrawerToggle. You can assign clickHandler directly. For my activities that have this drawer toolbar I implemented an interface to enable drawer if at root,
#Override
public void enableDrawer(boolean enable) {
mDrawerToggle.setDrawerIndicatorEnabled(enable);
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Pop fragment back stack or pass in a custom click handler from the fragment.
}
});
}