use viewpager with different fragments? - java

I recently started to write an application which let me to get information from a forum. I used JSoup library for scraping the data. My first part is going well.
When the app opens, it just gets data from the site(sub-forum names) and pass it so the listview is able to show them. When I press an item in the listview it just gets the thread list in the sub-forum. All the things are working properly excepts the listview doesn't get updated correctly.
As you can see when I press an item from the list(Just the first item in the list) then it set loadedSub to true then it gets the thread list using an async-task then in the postexecute it calls notifyDataSetChanged() on PagerAdapter. The problem is it just updates the UI perfectly, even leaving 1 tab only as I wanted, but the problem is that threadList doesn't appear in the listview. It only shows me the listview with previous data, not the threadlist.
Should I use another activity or is there something I am missing?
MainActivity.java
package com.ovnis.sscattered.elakiriunofficial;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import java.io.IOException;
public class MainActivity extends AppCompatActivity {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
public static SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
public static ViewPager mViewPager;
public static String[][] forumListSubForumsList = new String[13][];
public static String[][] forumListSubForumListLinks = new String[13][];
public static String[][] threadListLinks = new String[2][];
static Context context;
public String[] forumNumbers = {"1", "86", "89", "6",
"66", "79", "70", "12",
"16", "33", "42", "25",
"22"};
public static String subforumLink;
static boolean loaded = false;
static boolean loadedSub = false;
static boolean subForumMode = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// 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 = (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, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
new GetSubForumList().execute();
context = getBaseContext();
}
#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_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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class SubForumsFrag extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
static ListView listview;
static ForumListAdapter adapter;
int pos = 0;
public SubForumsFrag() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static SubForumsFrag newInstance(int pos) {
SubForumsFrag fragment = new SubForumsFrag();
Bundle args = new Bundle();
args.putInt("poskey", pos);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_base, container, false);
listview = (ListView) rootView.findViewById(R.id.listview);
pos = getArguments().getInt("poskey");
if(loaded){
adapter = new ForumListAdapter(getActivity(), forumListSubForumsList[pos]);
}
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getContext(), forumListSubForumListLinks[pos][position], Toast.LENGTH_SHORT).show();
subForumMode = true;
subforumLink = forumListSubForumListLinks[pos][position];
new GetThreadList().execute();
}
});
return rootView;
}
}
public static class ThreadListFrag extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
static ListView listview;
static ForumListAdapter adapter;
int pos = 0;
public ThreadListFrag() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static ThreadListFrag newInstance() {
ThreadListFrag fragment = new ThreadListFrag();
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.list_base, container, false);
listview = (ListView) rootView.findViewById(R.id.listview);
if(loadedSub){
adapter = new ForumListAdapter(getActivity(), threadListLinks[0]);
}
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getContext(), forumListSubForumListLinks[pos][position], Toast.LENGTH_SHORT).show();
}
});
return rootView;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a SubForumsFrag (defined as a static inner class below).
if(!subForumMode){
return SubForumsFrag.newInstance(position);
}else{
return ThreadListFrag.newInstance();
}
}
#Override
public int getCount() {
// Show 13 total pages.
if(!subForumMode){
return 13;
}else{
return 1;
}
}
#Override
public CharSequence getPageTitle(int position) {
if(!subForumMode){
switch (position) {
case 0:
return "Elakiri";
case 1:
return "Cooking";
case 2:
return "B & M";
case 3:
return "General";
case 4:
return "E. Traveler";
case 5:
return "Automobile";
case 6:
return "Motorcycles";
case 7:
return "Entertainment";
case 8:
return "C & I";
case 9:
return "S. Piyasa";
case 10:
return "Elakiri Magic";
case 11:
return "Games";
case 12:
return "Mobile";
}
}else{
return "Bitch Me";
}
return null;
}
#Override
public int getItemPosition(Object obj){
return POSITION_NONE;
}
}
class GetSubForumList extends AsyncTask<Void, Integer, String>
{
String TAG = getClass().getSimpleName();
ProgressDialog dialog;
protected void onPreExecute (){
Log.d(TAG + " PreExceute","On pre Exceute......");
dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle("Loading...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
protected String doInBackground(Void...arg0){
Log.d(TAG + " DoINBackGround","On doInBackground...");
try {
Connection.Response response = Jsoup.connect("http://www.elakiri.com/forum/")
.execute();
Document parsedDoc = response.parse();
Element doc;
Elements doce;
for(int i = 0; i < forumNumbers.length; i++){
doc = parsedDoc.select("tbody#collapseobj_forumbit_" + forumNumbers[i]).first();
doce = doc.select("a[href] strong");
forumListSubForumsList[i] = new String[(doce.size()+1)/2];
forumListSubForumListLinks[i] = new String[(doce.size()+1)/2];
for(int q = 0; q < (doce.size()+1)/2; q++){
forumListSubForumsList[i][q] = doce.get(q*2).text();
forumListSubForumListLinks[i][q] = doce.get(q*2).parent().absUrl("href");
}
}
} catch (IOException e) {
e.printStackTrace();
}
return "Shot";
}
protected void onProgressUpdate(Integer...a){
Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
}
protected void onPostExecute(String result) {
Log.d(TAG + " onPostExecute", "" + result);
loaded = true;
mViewPager.invalidate();
mSectionsPagerAdapter.notifyDataSetChanged();
dialog.dismiss();
}
}
static class GetThreadList extends AsyncTask<Void, Integer, String>
{
String TAG = getClass().getSimpleName();
ProgressDialog dialog;
protected void onPreExecute (){
Log.d(TAG + " PreExceute","On pre Exceute......");
dialog = new ProgressDialog(context);
dialog.setTitle("Loading...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
// dialog.show();
}
protected String doInBackground(Void...arg0){
Log.d(TAG + " DoINBackGround","On doInBackground...");
try {
Connection.Response response = Jsoup.connect(subforumLink)
.execute();
Element doc = response.parse().select("tbody#threadbits_forum_2").first();
Elements doce = doc.select("a[id^=thread_title_]");
threadListLinks[0] = new String[doce.size()];
threadListLinks[1] = new String[doce.size()];
for(int i = 0; i < doce.size(); i++){
threadListLinks[0][i] = doce.get(i).text();
threadListLinks[1][i] = doce.get(i).absUrl("href");
}
} catch (IOException e) {
e.printStackTrace();
}
return "Shot";
}
protected void onProgressUpdate(Integer...a){
Log.d(TAG + " onProgressUpdate", "You are in progress update ... " + a[0]);
}
protected void onPostExecute(String result) {
Log.d(TAG + " onPostExecute", "" + result);
loadedSub = true;
mViewPager.invalidate();
mSectionsPagerAdapter.notifyDataSetChanged();
}
}
}
ForumListAdapter.java
public class ForumListAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public ForumListAdapter(Context context, String[] values) {
super(context, R.layout.main_adapter ,values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.main_adapter, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.firstLine);
textView.setText(values[position]);
return rowView;
}
}

Alright, I got it solved using FragmentStatePageAdapter instead of using FragmentPageAdapter

Related

How do I extablish context for an Activity within a recyclerview adapter

I have buttons within the rows of a recyclerview within a fragment within an activity. When the user clicks one of the buttons, I want to switch to a different activity. How do I establish context for the Intent to switch to the new activity.
OR, should I move the onClickListener back to the fragment or activity (is it incorrect to place onClickListener within the recyclerview adapter code). If so, how do I obtain reference to the button clicked from outside the recyclerview adapter.
Here is the fragment code (CheckInRecentList.java)
package com.example.checkingin;
import android.app.Application;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.google.android.material.snackbar.Snackbar;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
/**
* A simple {#link Fragment} subclass.
* Activities that contain this fragment must implement the
* {#link CheckInRecentList.OnFragmentInteractionListener} interface
* to handle interaction events.
* Use the {#link CheckInRecentList#newInstance} factory method to
* create an instance of this fragment.
*/
public class CheckInRecentList 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";
private RecyclerView recyclerView;
private RecyclerView.Adapter checkInListAdapter;
//private RecyclerView.LayoutManager layoutManager;
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
private MainViewModel mViewModel;
private CheckInListAdapter mAdapter;
private MainViewModelProviderFactory viewModelFactory;
private TextView checkInLastDateTime;
private TextView checkInTitle;
private TextView checkInDestinationName;
private TextView checkInComments;
private Context context;
private OnFragmentInteractionListener mListener;
public CheckInRecentList() {
// 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 CheckInRecentList.
*/
// TODO: Rename and change types and number of parameters
public static CheckInRecentList newInstance(String param1, String param2) {
CheckInRecentList fragment = new CheckInRecentList();
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);
Log.i(TAG, "onCreate: On Create");
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
Log.i(TAG, "onCreateView: On Create View");
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_check_in_recent_list, container, false);
}
// TODO: Rename method, update argument and hook method into UI event
public void onButtonPressed(Uri uri) {
Log.i(TAG, "onButtonPressed: ");
if (mListener != null) {
mListener.onFragmentInteraction(uri);
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
Log.i(TAG, "onAttach: OnAttach");
viewModelFactory = new MainViewModelProviderFactory(context.getApplicationContext());
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
Log.i(TAG,"OnAttach completed");
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Log.i(TAG, "onActivityCreated: On Activity Created");
mViewModel = new ViewModelProvider(this, viewModelFactory).get(MainViewModel.class);
mAdapter = new CheckInListAdapter(R.layout.fragment_check_in_recent_list);
RecyclerView recyclerView = getView().findViewById(R.id.check_in_recent_recycler_view);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
recyclerView.setAdapter(mAdapter);
recyclerView.addItemDecoration(new DividerItemDecoration(getContext(),
LinearLayoutManager.VERTICAL));
observerSetup();
Log.i(TAG, "onActivityCreated: Observer SetUp");
ItemTouchHelper.SimpleCallback callback = new
ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT | ItemTouchHelper.LEFT) {
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
return false;
}
#Override
public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
int position = viewHolder.getAdapterPosition();
mAdapter.deleteItem(position);
Snackbar snackbar = Snackbar.make(viewHolder.itemView, "Item " + (direction == ItemTouchHelper.RIGHT ? "deleted" : "archived") + ".", Snackbar.LENGTH_LONG);
snackbar.setAction(android.R.string.cancel, new View.OnClickListener() {
#Override
public void onClick(View view) {
mAdapter.undoDelete();
}
});
snackbar.show();
}
#Override
public void onChildDraw (Canvas c, RecyclerView
recyclerView, RecyclerView.ViewHolder viewHolder,float dX, float dY,
int actionState, boolean isCurrentlyActive){
new RecyclerViewSwipeDecorator.Builder(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive)
.addSwipeLeftBackgroundColor(ContextCompat.getColor(getContext(), R.color.recycler_view_item_swipe_left_background))
.addSwipeLeftActionIcon(R.drawable.ic_archive_white_24dp)
.addSwipeRightBackgroundColor(ContextCompat.getColor(getContext(), R.color.recycler_view_item_swipe_right_background))
.addSwipeRightActionIcon(R.drawable.ic_delete_white_24dp)
.addSwipeRightLabel(getString(R.string.action_delete))
.setSwipeRightLabelColor(Color.WHITE)
.addSwipeLeftLabel(getString(R.string.action_archive))
.setSwipeLeftLabelColor(Color.WHITE)
.create()
.decorate();
super.onChildDraw(c, recyclerView, viewHolder, dX, dY, actionState, isCurrentlyActive);
}
};
ItemTouchHelper itemTouchHelper = new ItemTouchHelper(callback);
itemTouchHelper.attachToRecyclerView(recyclerView);
CustomToast newtoast = new CustomToast(getContext(),"you clicked on this" );
newtoast.show();
}
#Override
public void onDetach() {
super.onDetach();
Log.i(TAG, "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);
}
private void clearFields() {
checkInLastDateTime.setText("");
checkInDestinationName.setText("");
checkInTitle.setText("");
checkInComments.setText("");
}
private void observerSetup() {
Log.i(TAG, "observerSetup:");
checkInLastDateTime = getView().findViewById(R.id.checkInLastDateTime);
checkInTitle = getView().findViewById(R.id.checkInTitle);
checkInDestinationName = getView().findViewById(R.id.checkInDestinationName);
checkInComments = getView().findViewById(R.id.checkInComments);
if(mViewModel.getAllCheckIn() != null)
mViewModel.getAllCheckIn().observe(getViewLifecycleOwner(), new Observer<List<CheckInTable>>(){
#Override
public void onChanged(#Nullable final List<CheckInTable> allCheckIn) {
mAdapter.setCheckInList(allCheckIn);
}
});
}
}
Here is the recyclerview adapter code
package com.example.checkingin;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;
import static androidx.constraintlayout.widget.Constraints.TAG;
public class CheckInListAdapter extends RecyclerView.Adapter<CheckInListAdapter.ViewHolder>{
private int checkInListLayout;
private List<CheckInTable> checkInList;
private CoordinatorLayout coordinatorLayout;
private RecyclerView recyclerView;
private CheckInTable mRecentlyDeletedItem;
private int mCheckInTablePrimaryKey;
private int mRecentlyDeletedItemPosition;
private Context context;
public CheckInListAdapter(int layoutId) {
Log.i(TAG, "CheckInListAdapter: ");
checkInListLayout = layoutId;
}
public void setCheckInList(List<CheckInTable> allCheckIn) {
checkInList = allCheckIn;
Log.i(TAG, "setCheckInList: ");
notifyDataSetChanged();
}
public void deleteItem(int position) {
mRecentlyDeletedItem = checkInList.get(position);
mRecentlyDeletedItemPosition = position;
checkInList.remove(position);
notifyItemRemoved(position);
}
public void undoDelete() {
checkInList.add(mRecentlyDeletedItemPosition,
mRecentlyDeletedItem);
notifyItemInserted(mRecentlyDeletedItemPosition);
}
#Override
public int getItemCount() {
return checkInList == null ? 0 : checkInList.size();
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Log.i(TAG, "onCreateViewHolder: ");
View view = LayoutInflater.from(
parent.getContext()).inflate(R.layout.recycler_view_item, parent, false);
ViewHolder checkInListViewHolder = new ViewHolder(view);
return checkInListViewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int listPosition) {
TextView checkInTablePrimaryKey = holder.checkInTablePrimaryKey;
TextView checkInLastDateTime = holder.checkInLastDateTime;
TextView checkInTitle = holder.checkInTitle;
TextView checkInDestinationName = holder.checkInDestinationName;
TextView checkInComments = holder.checkInComments;
holder.checkInEditButton.setImageResource(R.drawable.ic_menu_edit);
holder.checkInResendButton.setImageResource(R.drawable.ic_menu_share);
Log.i(TAG, "onBindViewHolder: ");
//checkInTablePrimaryKey.setText(checkInList.get(listPosition).getCheckInTablePrimaryKey());
checkInLastDateTime.setText(checkInList.get(listPosition).getCheckInLastDateTime());
checkInTitle.setText(checkInList.get(listPosition).getCheckInTitle());
checkInDestinationName.setText(checkInList.get(listPosition).getCheckInDestinationName());
checkInComments.setText(checkInList.get(listPosition).getCheckInComments());
ImageView checkInEditButton = holder.checkInEditButton;
ImageView checkInResendButton = holder.checkInResendButton;
ImageButton editCheckInButton = checkInEditButton.findViewById(R.id.checkInEditButton);
ImageButton resendCheckInButton = checkInResendButton.findViewById(R.id.checkInResendButton);
editCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in edit check in logic
Integer value = (checkInList.get(listPosition).getCheckInTablePrimaryKey());
Intent intent = new Intent(context, CheckInNew.class);
intent.putExtra("checkInTablePrimaryKey",value);
context.startActivity(intent);
//Bundle extras = getIntent().getExtras();
//if (extras != null) {
// String value = extras.getInt("checkInTablePrimaryKey");
//The key argument here must match that used in the other activity
//}
}
});
resendCheckInButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//put in resend logic
}
});
}
static class ViewHolder extends RecyclerView.ViewHolder {
TextView checkInTablePrimaryKey;
TextView checkInLastDateTime;
TextView checkInTitle;
TextView checkInDestinationName;
TextView checkInComments;
ImageView checkInEditButton;
ImageView checkInResendButton;
ViewHolder(View itemView) {
super(itemView);
Log.i(TAG, "ViewHolder: ");
checkInTablePrimaryKey = itemView.findViewById(R.id.checkInTablePrimaryKey);
checkInLastDateTime = itemView.findViewById(R.id.checkInLastDateTime);
checkInTitle = itemView.findViewById(R.id.checkInTitle);
checkInDestinationName = itemView.findViewById(R.id.checkInDestinationName);
checkInComments = itemView.findViewById(R.id.checkInComments);
checkInEditButton = itemView.findViewById(R.id.checkInEditButton);
checkInResendButton = itemView.findViewById(R.id.checkInResendButton);
}
}
}
Here is the Activity code CheckIn.java
package com.example.checkingin;
import android.net.Uri;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.android.material.snackbar.Snackbar;
import android.view.View;
import android.view.Menu;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;
import com.google.android.material.tabs.TabLayout;
public class CheckIn extends AppCompatActivity implements
CheckInRecentList.OnFragmentInteractionListener,
CheckInApproveRequested.OnFragmentInteractionListener,
CheckInSearch.OnFragmentInteractionListener {
//private AdView mAdView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_in);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = findViewById(R.id.fab);
//MobileAds.initialize(this, new OnInitializationCompleteListener() {
// #Override
// public void onInitializationComplete(InitializationStatus initializationStatus) {
// }
//});
//mAdView = findViewById(R.id.adView);
//AdRequest adRequest = new AdRequest.Builder().build();
//mAdView.loadAd(adRequest);
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();
}
});
DrawerUtil.getDrawer(this,toolbar);
configureTabLayout();
}
private void configureTabLayout() {
TabLayout tabLayout = findViewById(R.id.check_in_main_tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Recent"));
tabLayout.addTab(tabLayout.newTab().setText("Approve Requested"));
tabLayout.addTab(tabLayout.newTab().setText("Search"));
final ViewPager viewPager = findViewById(R.id.check_in_main_pager);
final PagerAdapter adapter = new CheckInMainPagerAdapter
(getSupportFragmentManager(),
tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new
TabLayout.TabLayoutOnPageChangeListener(tabLayout));
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) {
}
});
}
#Override
public void onFragmentInteraction(Uri uri) {
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.check_in, menu);
return true;
}
}
In the constructor of CheckInListAdapter pass another argument as context
public CheckInListAdapter(int layoutId, Context context) {
Log.i(TAG, "CheckInListAdapter: ");
checkInListLayout = layoutId;
this.context = context
}

What should the container be when FragmentPagerAdapter is used

So in NameList where it says "fragmentTransaction.add(android.R.id.content, fragment2, "login").commit();" I need to find the container of NameList when I try R.id.container a blank white screen appears. What should I put instead of android.R.id.content in this case?
NameList.java
package com.drdc1.medic;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* A simple {#link Fragment} subclass.
*/
public class NameList extends Fragment implements DataObserver {
private SoldierListAdapter adapter;
private HomeActivity homeActivity;
private ArrayList<Soldier> soldiers = new ArrayList<>();
public NameList() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_name_list, container, false);
homeActivity = (HomeActivity) getActivity();
homeActivity.registerFragment(this);
final ListView listView = (ListView) rootView.findViewById(R.id.soldierList);
addListHeader(listView);
DataManager dbManager = ((AppContext) getActivity().getApplication()).getDataManager();
soldiers = dbManager.getActiveSoldier();
adapter = new SoldierListAdapter(getContext(), soldiers);
listView.setAdapter(adapter);
TextView nameHeader = (TextView) rootView.findViewById(R.id.name_header);
nameHeader.setOnClickListener(new ClickToSort());
TextView hrHeader = (TextView) rootView.findViewById(R.id.hr_header);
hrHeader.setOnClickListener(new ClickToSort());
TextView brHeader = (TextView) rootView.findViewById(R.id.br_header);
brHeader.setOnClickListener(new ClickToSort());
TextView skinTmpHeader = (TextView) rootView.findViewById(R.id.skin_tmp_header);
skinTmpHeader.setOnClickListener(new ClickToSort());
TextView core_tmp_header = (TextView) rootView.findViewById(R.id.core_tmp_header);
core_tmp_header.setOnClickListener(new ClickToSort());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//TODO When item clicked, write code here
String idsol = null;
if (((Soldier) listView.getAdapter().getItem(position)) != null) {
idsol = ((Soldier) listView.getAdapter().getItem(position)).getId();
}
android.support.v4.app.FragmentTransaction fragmentTransaction =
getFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
if (idsol != null){
bundle.putString("id", idsol); // Put anything what you want
}
IndividualSoldierTab fragment2 = new IndividualSoldierTab();
fragment2.setArguments(bundle);
fragmentTransaction.add(android.R.id.content, fragment2, "login").commit();
// getFragmentManager()
// .beginTransaction()
// .replace(R.id.container, fragment2)
// .commit();
}
});
return rootView;
}
#Override
public void onPause() {
super.onPause();
homeActivity.registerFragment(this);
}
#Override
public void onResume() {
super.onResume();
homeActivity.registerFragment(this);
}
#Override
public void onDestroyView() {
homeActivity.unregisterFragment(this);
super.onDestroyView();
}
#Override
public void update(Map data) {
Boolean soldierInTheList = false;
for (Soldier s : soldiers) {
if (data.get("ID").equals(s.getId())) {
s.setPhysioData(data);
soldierInTheList = true;
}
}
if (!soldierInTheList) {
Soldier newSol = new Soldier((String) data.get("name"), (String) data.get("ID"));
newSol.setPhysioData(data);
soldiers.add(newSol);
}
adapter.notifyDataSetChanged();
}
private void addListHeader(ListView lv) {
View headerView =
LayoutInflater.from(getContext()).inflate(R.layout.list_header, lv, false);
lv.addHeaderView(headerView);
}
private class SoldierListAdapter extends ArrayAdapter<Soldier> {
private final ArrayList<Soldier> soldiers;
private String sortedBy = "";
// the soldier list is only sorted by 1 attribute at a time. don't overthink about stable sorting
public SoldierListAdapter(Context context, ArrayList<Soldier> soldiers) {
super(context, R.layout.list_item, soldiers);
this.soldiers = soldiers;
}
public String getSortedBy() {
return sortedBy;
}
/***
* When the user click the header when soldiers are already sorted, reverse the order
*/
public void reverse() {
Collections.reverse(soldiers);
}
/***
* #param x "Sort by x" Sortby is an enum
*/
public void sort(SortBy x) {
switch (x) {
case NAME:
this.sort(new OrderByName());
sortedBy = "NAME";
break;
case HR:
this.sort(new OrderByHR());
sortedBy = "HR";
break;
case BR:
this.sort(new OrderByBR());
sortedBy = "BR";
break;
case SKINTMP:
this.sort(new OrderBySkinTmp());
sortedBy = "SKINTMP";
break;
case CORETMP:
this.sort(new OrderByCoreTmp());
sortedBy = "CORETMP";
break;
default:
}
}
#NonNull
#Override
public View getView(int position, View v, ViewGroup parent) {
// Get the data item for this position
Soldier soldier = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (v == null) {
v = LayoutInflater.from(getContext())
.inflate(R.layout.list_item, parent, false);
}
TextView name = (TextView) v.findViewById(R.id.name);
// name.setOnClickListener(new setFragmentTransition());
name.setText(soldier.getName());
ImageView overall = (ImageView) v.findViewById(R.id.overal_status);
switch (soldier.getOverallStatus()) {
case "RED":
overall.setImageResource(R.drawable.red);
break;
case "GREEN":
overall.setImageResource(R.drawable.green);
break;
case "YELLOW":
overall.setImageResource(R.drawable.yellow);
break;
default:
break;
}
if (soldier.getBodyOrientation() != null && !soldier.getBodyOrientation().isEmpty()) {
ImageView bodyPos = (ImageView) v.findViewById(R.id.body_position);
bodyPos.setImageResource(R.drawable.body);
switch (soldier.getBodyOrientation()) {
case "UP":
break;
case "DOWN":
bodyPos.setRotation(180);
break;
case "LEFT":
bodyPos.setRotation(270);
break;
case "RIGHT":
bodyPos.setRotation(90);
break;
default:
break;
}
}
String currentHR = soldier.getHeartRate();
String lastHR = soldier.getLastHeartRate();
if (!currentHR.equals("")) {
TextView heartRate = (TextView) v.findViewById(R.id.hr_text);
ImageView arrow = (ImageView) v.findViewById(R.id.hr_img);
if (!lastHR.equals("")) {
if (Integer.parseInt(currentHR) > Integer.parseInt(lastHR)) {
arrow.setImageResource(R.drawable.up_arrow);
heartRate.setTextColor(Color.RED);
} else if (Integer.parseInt(currentHR) < Integer.parseInt(lastHR)) {
arrow.setImageResource(R.drawable.down_arrow);
heartRate.setTextColor(Color.YELLOW);
} else {
arrow.setImageResource(0);
heartRate.setTextColor(Color.BLACK);
}
}
heartRate.setText(currentHR);
}
//TODO replace image for down_arrow color not right
String currentBR = soldier.getBreathingRate();
String lastBR = soldier.getLastBreathingRate();
if (!currentBR.equals("")) {
TextView breathingRate = (TextView) v.findViewById(R.id.br_text);
ImageView arrow = (ImageView) v.findViewById(R.id.br_img);
if (!lastBR.equals("")) {
if (Integer.parseInt(currentBR) > Integer.parseInt(lastBR)) {
arrow.setImageResource(R.drawable.up_arrow);
breathingRate.setTextColor(Color.RED);
} else if (Integer.parseInt(currentBR) < Integer.parseInt(lastBR)) {
arrow.setImageResource(R.drawable.down_arrow);
breathingRate.setTextColor(Color.YELLOW);
} else {
arrow.setImageResource(0);
breathingRate.setTextColor(Color.BLACK);
}
}
breathingRate.setText(currentBR);
}
String currentCoreTmp = soldier.getCoreTmp();
String lastCoreTmp = soldier.getLastCoreTmp();
if (!currentCoreTmp.equals("")) {
TextView coreTmp = (TextView) v.findViewById(R.id.core_tmp_text);
ImageView arrow = (ImageView) v.findViewById(R.id.core_tmp_img);
if (!lastCoreTmp.equals("")) {
if (Integer.parseInt(currentCoreTmp) > Integer.parseInt(lastCoreTmp)) {
arrow.setImageResource(R.drawable.up_arrow);
coreTmp.setTextColor(Color.RED);
} else if (Integer.parseInt(currentCoreTmp) < Integer.parseInt(lastCoreTmp)) {
arrow.setImageResource(R.drawable.down_arrow);
coreTmp.setTextColor(Color.YELLOW);
} else {
arrow.setImageResource(0);
coreTmp.setTextColor(Color.BLACK);
}
}
coreTmp.setText(currentCoreTmp);
}
String currentSkinTmp = soldier.getSkinTmp();
String lastSkinTmp = soldier.getLastSkinTmp();
if (!currentSkinTmp.equals("")) {
TextView skinTmp = (TextView) v.findViewById(R.id.skin_tmp_text);
ImageView arrow = (ImageView) v.findViewById(R.id.skin_tmp_img);
if (!lastSkinTmp.equals("")) {
if (Integer.parseInt(currentSkinTmp) > Integer.parseInt(lastSkinTmp)) {
arrow.setImageResource(R.drawable.up_arrow);
skinTmp.setTextColor(Color.RED);
} else if (Integer.parseInt(currentSkinTmp) < Integer.parseInt(lastSkinTmp)) {
arrow.setImageResource(R.drawable.down_arrow);
skinTmp.setTextColor(Color.YELLOW);
} else {
arrow.setImageResource(0);
skinTmp.setTextColor(Color.BLACK);
}
}
skinTmp.setText(currentSkinTmp);
}
//TextView tvHome = (TextView) v.findViewById(R.id.tvHome);
// Populate the data into the template view using the data object
// Return the completed view to render on screen
return v;
}
}
private class ClickToSort implements View.OnClickListener {
#Override
public void onClick(View v) {
String sortBy = (String) ((TextView) v).getText();
switch (sortBy.toLowerCase()) {
case "name":
if (adapter.getSortedBy().equals("NAME")) {
adapter.reverse();
} else {
adapter.sort(SortBy.NAME);
}
break;
case "hr":
if (adapter.getSortedBy().equals("HR")) {
adapter.reverse();
} else {
adapter.sort(SortBy.HR);
}
break;
case "br":
if (adapter.getSortedBy().equals("BR")) {
adapter.reverse();
} else {
adapter.sort(SortBy.BR);
}
break;
case "skintmp":
if (adapter.getSortedBy().equals("SKINTMP")) {
adapter.reverse();
} else {
adapter.sort(SortBy.SKINTMP);
}
break;
case "coretmp":
if (adapter.getSortedBy().equals("CORETMP")) {
adapter.reverse();
} else {
adapter.sort(SortBy.CORETMP);
}
break;
default:
}
adapter.notifyDataSetChanged();
}
}
/************************************************************************
* Comparator classes to support different ordering of soldiers
*************************************************************************/
private enum SortBy {
NAME, HR, BR, SKINTMP, CORETMP
}
private static class OrderByName implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return s1.getName().compareTo(s2.getName());
}
}
private static class OrderByHR implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return Integer.parseInt(s1.getHeartRate().equals("") ? "0" : s1.getHeartRate())
- Integer.parseInt(s2.getHeartRate().equals("") ? "0" : s2.getHeartRate());
}
}
private static class OrderByBR implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return Integer.valueOf(s1.getBreathingRate().equals("") ? "0" : s1.getBreathingRate())
.compareTo(Integer.valueOf(
s2.getBreathingRate().equals("") ? "0" : s2.getBreathingRate()));
}
}
private static class OrderBySkinTmp implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return Integer.valueOf(s1.getSkinTmp().equals("") ? "0" : s1.getSkinTmp())
.compareTo(Integer.valueOf(s2.getSkinTmp().equals("") ? "0" : s2.getSkinTmp()));
}
}
private static class OrderByCoreTmp implements Comparator<Soldier> {
#Override
public int compare(Soldier s1, Soldier s2) {
return Integer.valueOf(s1.getCoreTmp().equals("") ? "0" : s1.getCoreTmp())
.compareTo(Integer.valueOf(s2.getCoreTmp().equals("") ? "0" : s2.getCoreTmp()));
}
}
}
HomeActivity.java
package com.drdc1.medic;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
// This is the home page of the tab application.
public class HomeActivity extends AppCompatActivity implements FragmentDataManager {
private SectionsPagerAdapter mSectionsPagerAdapter;
private DataReceiver dataReceiver;
private ArrayList<DataObserver> fragmentlist;
static private HashMap data; //one data shared by all fragments
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startBackgroundServices();
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
//register intent filter for LocalBroadbast Manager
IntentFilter PDAMESSAGE = new IntentFilter("PDAMessage");
dataReceiver = new DataReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(dataReceiver, PDAMESSAGE);
data = new HashMap();
fragmentlist = new ArrayList<>();
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset,
int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
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, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public void registerFragment(DataObserver o) {
if (!fragmentlist.contains(o))
fragmentlist.add(o);
}
#Override
public void unregisterFragment(DataObserver o) {
if (fragmentlist.contains(o)) {
int observerIndex = fragmentlist.indexOf(o);
fragmentlist.remove(observerIndex);
}
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void notifyObserver(Map data) {
for (DataObserver observer : fragmentlist) {
observer.update(data);
}
}
class DataReceiver extends BroadcastReceiver {
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onReceive(Context context, Intent intent) {
data.put("bodypos", intent.getStringExtra("bodypos"));
data.put("overall", intent.getStringExtra("overall"));
data.put("coreTemp", intent.getStringExtra("coreTmp"));
data.put("skinTemp", intent.getStringExtra("skinTmp"));
data.put("br", intent.getStringExtra("br"));
data.put("hr", intent.getStringExtra("hr"));
data.put("ID",intent.getStringExtra("ID"));
data.put("name",intent.getStringExtra("name"));
notifyObserver(data);
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public PlaceholderFragment() {
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
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_home, 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;
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
SquadStatus tab1 = new SquadStatus();
return tab1;
case 1:
NameList tab2 = new NameList();
return tab2;
case 2:
IndividualSoldierTab tab3 = new IndividualSoldierTab();
return tab3;
case 3:
TreatmentScreenTab tab4 = new TreatmentScreenTab();
return tab4;
default:
return null;
}
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Squad Status";
case 1:
return "Name List";
case 2:
return "Individual Soldier";
case 3:
return "Treatment Screen";
}
return null;
}
}
private void startBackgroundServices() {
Intent Serviceintent = new Intent();
Serviceintent.setClass(this, BackgroundServer.class);
startService(Serviceintent);
Intent sleepAlgo = new Intent();
sleepAlgo.setClass(this, BackgroundSleepAlgo.class);
startService(sleepAlgo);
Intent wellnessAlgo = new Intent();
wellnessAlgo.setClass(this, BackgroundWellnessAlgo.class);
startService(wellnessAlgo);
}
public void callHelp(View v) {
Intent callhelp = new Intent(HomeActivity.this, HelpActivity.class);
startActivity(callhelp);
}
}
What should the container?
You can simply use a FrameLayout as the container layout and add fragments dynamically.

How to display other layouts?

I am new at android development and just trying to learn along the way!
I am creating an android app that I would like to show different views, one for weight, weather, and hydration (are what I have called them for now). Although when I run my app I only get my one view displayed.
What code do I have to add/modify in order to display the other two layouts in the tabbed view?
Here is my code in MainActivity.java
package com.oxinc.android.drate;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
int quantity = 0;
String outcome = "";
int required = 0;
int height = 0;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link FragmentPagerAdapter} derivative, which will keep every
* loaded fragment in memory. If this becomes too memory intensive, it
* may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
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);
// 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 = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
//Tabbed Layout
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
//Floating Action Button
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Are you hydrated?", Snackbar.LENGTH_LONG)
.setAction("Action", null).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.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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
public static PlaceholderFragment fragment_main() {
PlaceholderFragment fragment = new PlaceholderFragment();
return fragment;
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment weight(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 hydration = inflater.inflate(R.layout.hydration, container, false);
return hydration;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public 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.weight(position + 1);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Hydration";
case 1:
return "Weigh In";
case 2:
return "Weather";
}
return null;
}
}
public void eight(View view) {
quantity = quantity + 8;
displayQuantity(quantity);
}
public void twelve(View view) {
quantity = quantity + 12;
displayQuantity(quantity);
}
public void sixteen(View view) {
quantity = quantity + 16;
displayQuantity(quantity);
}
public void thirty_two(View view) {
quantity = quantity + 32;
displayQuantity(quantity);
}
public void sixty_four(View view) {
quantity = quantity + 64;
displayQuantity(quantity);
}
//Reset Button
public void reset(View view) {
quantity = 0;
displayQuantity(quantity);
outcome = "";
displayOutcome(outcome);
}
//Starts the basic formula for oz. per day
public int height(int value) {
EditText height = (EditText) findViewById(R.id.height);
String height_value = height.getText().toString();
int int_height = Integer.parseInt(height_value);
if (int_height >= 60) {
required = 64;
}
return required;
}
/**
* This method is called when the check button is clicked.
*/
public String check(View view) {
height((int) height);
if (quantity >= required) {
outcome = "You have met your goal!!";
} else {
outcome = "Keep trying you are almost there";
}
displayOutcome(outcome);
return outcome;
}
//Displays the Outcome to the outcome text view
public void displayOutcome(String n) {
TextView outcomeTextView = (TextView) findViewById(
R.id.outcome_text_view);
outcomeTextView.setText(outcome);
}
/**
* This method displays the given quantity value on the screen.
*/
public void displayQuantity(int quantity) {
TextView quantityTextView = (TextView) findViewById(
R.id.quantity_text_view);
quantityTextView.setText(quantity + "");
}
}
An once I run it I just get three screens that look like this...
Inside your public Fragment getItem(int position) {
which is inside your
public class SectionsPagerAdapter extends FragmentPagerAdapter {
Implement this:
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new fragment1();
case 1:
return new fragment2();
case 2:
return new fragment3();
default:
// this should never happen
return null;
//return new Fragment();
}
}
Where "fragment1-2 and 3" are the name of the java classes you've defined to run there.
I use my "getItem" exactly this way, with nothing more inside it. So I don't know if you have to maintain your return PlaceholderFragment.weight(position + 1); there. Try commenting it out and see what happens. I don't use createview either. Best.
The problem is here
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View hydration = inflater.inflate(R.layout.hydration, container, false);
return hydration;
}
You are always inflating the hydration layout, in every fragment

how to pass value from NavigationDrawerFragment.java to MainActivity.java then pass to AnotherFragment page

in my NavigationDrawerFragment.java
i have this code
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
String header = listDataHeader.get(groupPosition);
Category child = listDataChild.get(header).get(childPosition);
// child.name to get the name
// child.id to get the id
//Toast.makeText(getActivity(),"ChildNme: "+child.name+" ChildId: "+child.id, Toast.LENGTH_SHORT).show();
selectItem(1);
return false;
}
});
after i click the child, i set selectItem to 1
the selectItem(1) will go to MainActivity.java
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
// NEW STUFF
if(position == 1){
fragmentManager.beginTransaction()
.replace(R.id.container, CategoryFragment.newInstance())
.commit();
}
}
my question is how to pass the child.name and child.id from NavigationDrawerFragment.java to MainActivity.java then pass to CategoryFragment?
or any other solution to pass the child.name and child.id to CategoryFragment.
COMPLETE CODE
NavigationDrawerFragment.java
package com.example.administrator.mosbeau;
import android.app.FragmentManager;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.app.Activity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Fragment used for managing interactions for and presentation of a navigation drawer.
* See the <a href="https://developer.android.com/design/patterns/navigation-drawer.html#Interaction">
* design guidelines</a> for a complete explanation of the behaviors implemented here.
*/
public class NavigationDrawerFragment extends Fragment {
/**
* Remember the position of the selected item.
*/
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
/**
* Per the design guidelines, you should show the drawer on launch until the user manually
* expands it. This shared preference tracks this.
*/
private static final String PREF_USER_LEARNED_DRAWER = "navigation_drawer_learned";
/**
* A pointer to the current callbacks instance (the Activity).
*/
private NavigationDrawerCallbacks mCallbacks;
/**
* Helper component that ties the action bar to the navigation drawer.
*/
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private boolean mUserLearnedDrawer;
String myJSON;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "categories_id";
private static final String TAG_NAME = "categories_name";
JSONArray categories = null;
public NavigationDrawerFragment() {
}
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Read in the flag indicating whether or not the user has demonstrated awareness of the
// drawer. See PREF_USER_LEARNED_DRAWER for details.
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getActivity());
mUserLearnedDrawer = sp.getBoolean(PREF_USER_LEARNED_DRAWER, false);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
// Select either the default item (0) or the last selected item.
selectItem(mCurrentSelectedPosition);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Indicate that this fragment would like to influence the set of actions in the action bar.
setHasOptionsMenu(true);
}
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<Category>> listDataChild;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View fragmentView = inflater.inflate(
R.layout.fragment_navigation_drawer, container, false);
/*mDrawerListView = (ListView) fragmentView.findViewById(R.id.listView);
//mDrawerListView = (ListView) inflater.inflate(
//R.layout.fragment_navigation_drawer, container, false);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
new String[]{
getString(R.string.title_home),
getString(R.string.title_category),
getString(R.string.title_myaccount),
getString(R.string.title_referafriend),
getString(R.string.title_about),
getString(R.string.title_privacypocity),
getString(R.string.title_shippingterms),
getString(R.string.title_contactus),
}));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);*/
// get the listview
expListView = (ExpandableListView) fragmentView.findViewById(R.id.lvExp);
// preparing list data
//prepareListData();
detectconnection = new Seocnd(getActivity());
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
getData();
} else {
selectItem(100);
}
return fragmentView;
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://joehamirbalabadan.com/android/android/categories.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
} catch (Exception e) {
// Oops
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPostExecute(String result){
myJSON=result;
prepareListData();
listAdapter = new ExpandableListAdapter(getActivity(), listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// Listview Group click listener
expListView.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
/*Toast.makeText(getActivity(),
"Group Clicked " + listDataHeader.get(groupPosition),
Toast.LENGTH_SHORT).show();*/
if(groupPosition == 1){
return false;
} else {
selectItem(groupPosition);
return true;
}
}
});
// Listview on child click listener
expListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
String header = listDataHeader.get(groupPosition);
Category child = listDataChild.get(header).get(childPosition);
// child.name to get the name
// child.id to get the id
Toast.makeText(getActivity(),"ChildNme: "+child.name+" ChildId: "+child.id, Toast.LENGTH_SHORT).show();
//selectItem(1);
return false;
}
});
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
protected void prepareListData(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
categories = jsonObj.getJSONArray(TAG_RESULTS);
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<Category>>();
// Adding group data
listDataHeader.add("HOME");
listDataHeader.add("CATEGORY");
listDataHeader.add("MY ACCOUNT");
listDataHeader.add("REFER A FRIEND");
listDataHeader.add("ABOUT");
listDataHeader.add("PRIVACY POLICY");
listDataHeader.add("SHIPPING TERMS");
listDataHeader.add("CONTACT US");
List<Category> CATEGORY = new ArrayList<Category>();
for(int i=0;i<categories.length();i++){
JSONObject c = categories.getJSONObject(i);
Category category = new Category();
category.name = c.getString(TAG_NAME);
category.id = c.getString(TAG_ID);
CATEGORY.add(category);
}
listDataChild.put(listDataHeader.get(1), CATEGORY); // Header, Child data
} catch (JSONException e) {
e.printStackTrace();
}
}
/*
* Preparing the list data
*/
/*private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding group data
listDataHeader.add("HOME");
listDataHeader.add("CATEGORY");
listDataHeader.add("MY ACCOUNT");
listDataHeader.add("REFER A FRIEND");
listDataHeader.add("ABOUT");
listDataHeader.add("PRIVACY POLICY");
listDataHeader.add("SHIPPING TERMS");
listDataHeader.add("CONTACT US");
// Adding child data
List<String> CATEGORY = new ArrayList<String>();
CATEGORY.add("Category 1");
CATEGORY.add("Category 2");
CATEGORY.add("Category 3");
CATEGORY.add("Category 4");
CATEGORY.add("Category 5");
listDataChild.put(listDataHeader.get(1), CATEGORY); // Header, Child data
}*/
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Users of this fragment must call this method to set up the navigation drawer interactions.
*
* #param fragmentId The android:id of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUp(int fragmentId, DrawerLayout drawerLayout) {
mFragmentContainerView = getActivity().findViewById(fragmentId);
mDrawerLayout = drawerLayout;
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the navigation drawer and the action bar app icon.
mDrawerToggle = new ActionBarDrawerToggle(
getActivity(), /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.string.navigation_drawer_open, /* "open drawer" description for accessibility */
R.string.navigation_drawer_close /* "close drawer" description for accessibility */
) {
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
if (!isAdded()) {
return;
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
if (!isAdded()) {
return;
}
if (!mUserLearnedDrawer) {
// The user manually opened the drawer; store this flag to prevent auto-showing
// the navigation drawer automatically in the future.
mUserLearnedDrawer = true;
SharedPreferences sp = PreferenceManager
.getDefaultSharedPreferences(getActivity());
sp.edit().putBoolean(PREF_USER_LEARNED_DRAWER, true).apply();
}
getActivity().supportInvalidateOptionsMenu(); // calls onPrepareOptionsMenu()
}
};
// If the user hasn't 'learned' about the drawer, open it to introduce them to the drawer,
// per the navigation drawer design guidelines.
if (!mUserLearnedDrawer && !mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
// Defer code dependent on restoration of previous instance state.
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position);
}
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mCallbacks = (NavigationDrawerCallbacks) activity;
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement NavigationDrawerCallbacks.");
}
}
#Override
public void onDetach() {
super.onDetach();
mCallbacks = null;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Forward the new configuration the drawer toggle component.
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// If the drawer is open, show the global app actions in the action bar. See also
// showGlobalContextActionBar, which controls the top-left area of the action bar.
if (mDrawerLayout != null && isDrawerOpen()) {
inflater.inflate(R.menu.global, menu);
showGlobalContextActionBar();
}
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
if (item.getItemId() == R.id.action_example) {
Toast.makeText(getActivity(), "Example action.", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Per the navigation drawer design guidelines, updates the action bar to show the global app
* 'context', rather than just what's in the current screen.
*/
private void showGlobalContextActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setTitle(R.string.app_name);
}
private ActionBar getActionBar() {
return ((ActionBarActivity) getActivity()).getSupportActionBar();
}
/**
* Callbacks interface that all activities using this fragment must implement.
*/
public static interface NavigationDrawerCallbacks {
/**
* Called when an item in the navigation drawer is selected.
*/
void onNavigationDrawerItemSelected(int position);
}
}
MainActivity.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
public class MainActivity extends ActionBarActivity
implements NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
Boolean InternetAvailable = false;
Seocnd detectconnection;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
detectconnection = new Seocnd(this);
InternetAvailable = detectconnection.InternetConnecting();
if (InternetAvailable) {
} else {
NointernetFragment fragment = new NointernetFragment();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.commit();
}
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
// NEW STUFF
if(position == 0){
fragmentManager.beginTransaction()
.replace(R.id.container, HomeFragment.newInstance())
.commit();
}
else if (position == 1){
fragmentManager.beginTransaction()
.replace(R.id.container, CategoryFragment.newInstance())
.commit();
}
else if (position == 2){
fragmentManager.beginTransaction()
.replace(R.id.container, AccountFragment.newInstance())
.commit();
}
else if (position == 3){
fragmentManager.beginTransaction()
.replace(R.id.container, ReferFragment.newInstance())
.commit();
}
else if (position == 4){
fragmentManager.beginTransaction()
.replace(R.id.container, AboutFragment.newInstance())
.commit();
}
else if (position == 5){
fragmentManager.beginTransaction()
.replace(R.id.container, PolicyFragment.newInstance())
.commit();
}
else if (position == 6){
fragmentManager.beginTransaction()
.replace(R.id.container, TermsFragment.newInstance())
.commit();
}
else if (position == 7){
fragmentManager.beginTransaction()
.replace(R.id.container, ContactusFragment.newInstance())
.commit();
}
else if (position == 100){
fragmentManager.beginTransaction()
.replace(R.id.container, NointernetFragment.newInstance())
.commit();
}
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_home);
break;
case 2:
mTitle = getString(R.string.title_category);
break;
case 3:
mTitle = getString(R.string.title_login);
break;
case 4:
mTitle = getString(R.string.title_register);
break;
case 5:
mTitle = getString(R.string.title_myaccount);
break;
case 6:
mTitle = getString(R.string.title_referafriend);
break;
case 7:
mTitle = getString(R.string.title_about);
break;
case 8:
mTitle = getString(R.string.title_privacypocity);
break;
case 9:
mTitle = getString(R.string.title_shippingterms);
break;
case 10:
mTitle = getString(R.string.title_contactus);
break;
case 100:
mTitle = getString(R.string.title_nointernet);
break;
}
}
#SuppressWarnings("deprecation")
public void restoreActionBar() {
ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
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;
}
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
CategoryFragment.java
package com.example.administrator.mosbeau;
import android.app.Activity;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
/**
* Created by Administrator on 9/18/2015.
*/
public class CategoryFragment extends Fragment {
public static CategoryFragment newInstance() {
CategoryFragment fragment = new CategoryFragment();
return fragment;
}
public CategoryFragment () {
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.categorylayout, container, false);
getActivity().invalidateOptionsMenu();
return rootView;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((MainActivity) activity).onSectionAttached(2);
}
}
update your selectitem() and onNavigationDrawerItemSelected methods to accept two more arguments i.e child.id and child.name
private void selectItem(int position,String id,String name) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
if (mCallbacks != null) {
mCallbacks.onNavigationDrawerItemSelected(position,id,name);
}
}
pass child.id and child.name in selectItem() method so which in turn will call onNavigationDrawerItemSelected() method implemented in MainActivity.
Now in MainActivity, pass the values to the fragment using Bundle
here
fragmentManager.beginTransaction()
.replace(R.id.container, CategoryFragment.newInstance(id,name))
.commit();
you will also need to update to CategoryFragment.newInstance(String,String) to accept the arguments
Updating code to 'setText' in 'edittext'
In your 'CategoryFragment' 'newInstance' method pass data in bundle like below
CategoryFragment categoryfragment = new CategoryFragment()
Bundle bundle = new Bundle()
bundle.putStringExtra("id",id)
bundle.putStringExtra("name",name)
categoryfragment.setArguements(bundle)
return categoryfragment
Now in onCreateView of Categoryfragment get this data like below
if(getArguments().getExtras != null) {
String catid = getArguments.getStringExtra("id");
String catname = getArguments.getStringExtra("name");
yourEditText.setText(catname);
}
Hope you got my point

Can't access outer class from fragment class android

When I try to access outer class with this code:
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
it says:
The method getActivity() is undefined for the tyoe Logger
No enclosing instance of the type Logger is accessible in scope
Here is my Logger.java:
import java.util.Locale;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageSwitcher;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ViewSwitcher.ViewFactory;
public class Logger extends FragmentActivity implements ActionBar.TabListener {
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a
* {#link android.support.v4.app.FragmentPagerAdapter} derivative, which
* will keep every loaded fragment in memory. If this becomes too memory
* intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
ViewPager mViewPager;
static boolean isBoxOpen = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logger);
// Set up the action bar.
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setTitle("Sosyaaal");
actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.action_bar));
Thread connectivity = new Thread(){
public void run(){
try {
while(true)
{
while(!isBoxOpen)
{
if( !isOnline() )
{
isBoxOpen = true;
// display error
runOnUiThread(new Runnable() {
public void run() {
new AlertDialog.Builder(Logger.this)
.setTitle("Bağlantı Sorunu")
.setMessage("İnternet bağlantısını kontrol edip tekrar deneyin")
.setCancelable(false)
.setPositiveButton(R.string.yeniden, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Logger.isBoxOpen = false;// Try Again
}
})
.show();
}
});
}
}
}
} catch (Exception e) {
}
}
};
connectivity.start();
// Create the adapter that will return a fragment for each of the three
// primary sections of the app.
mSectionsPagerAdapter = new SectionsPagerAdapter(
getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager
.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.logger, menu);
return true;
}
public boolean isOnline() {
ConnectivityManager cm =
(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting()) {
return true;
}
return false;
}
#Override
public void onTabSelected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab,
FragmentTransaction fragmentTransaction) {
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
// Giriş fragment activity
return new GirisFragment();
case 1:
// Kayıt fragment activity
return new KayitFragment();
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class GirisFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
public GirisFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_giris,
container, false);
return rootView;
}
}
public static class KayitFragment extends Fragment {
public static final String ARG_SECTION_NUMBER = "section_number";
private ImageSwitcher cinsiyetSwitcher;
public KayitFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_kayit,
container, false);
cinsiyetSwitcher = (ImageSwitcher) getView().findViewById(R.id.cinsiyetSwitcher);
cinsiyetSwitcher.setFactory(new ViewFactory() {
#Override
public View makeView() {
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
return myView;
}
});
return rootView;
}
}
}
*EDIT*
Changing this line:
ImageView myView = new ImageView(Logger.this.getActivity().getApplicationContext());
to this:
ImageView myView = new ImageView((Logger)getActivity().getApplicationContext());
solved the problem, but that was not what I was looking for. Thanks to Kapil Vij for correct Answer!
Do this
ImageView myView = new ImageView(getActivity());
getActivity() method is accessible in fragment class, and u r trying to access it using FragmentActivity class instance.
change to:
Logger.this.getApplicationContext()
Logger it-self is activity you call getActivity to get the reference of the activity inside a Fragment
EDIT
Saw that you are calling it inside a fragment change you code to:
ImageView myView = new ImageView(KayitFragment.this.getActivity().getApplicationContext());

Categories

Resources