[Q] Changing to another Activity when pressing on a Gridviewpager - Wear OS Q&A, Help & Troubleshooting

I am trying to start a new certain Activity based on which page I am clicking on in a Gridview.
I tried to understand the Sample GridViewPager which is coming along with the sdk and trying to adapt the given explanation on stackoverflow (question # 26343337). But I really don't know how to bring these two things together and even where to start.
The first java.file Selection
Code:
public class Selection extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.selection_grid);
final GridViewPager pager = (GridViewPager) findViewById(R.id.pager);
pager.setAdapter(new Workers(this, getFragmentManager()));
DotsPageIndicator dotsPageIndicator = (DotsPageIndicator) findViewById(R.id.page_indicator);
dotsPageIndicator.setPager(pager);
}
}
and the second java.file Users (thats the Adapter):
Code:
public class Users extends FragmentGridPagerAdapter {
private static final int TRANSITION_DURATION_MILLIS = 100;
private final Context mContext;
private List<Row> mRows;
private ColorDrawable mDefaultBg;
private ColorDrawable mClearBg;
public Users (Context ctx, FragmentManager fm) {
super(fm);
mContext = ctx;
mRows = new ArrayList<Workers.Row>();
mRows.add(new Row(cardFragment(R.string.title, R.string.user1)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user2)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user3)));
mRows.add(new Row(cardFragment(R.string.title, R.string.user4)));
// In case in one row several cardFragments are needed
// mRows.add(new Row(
// cardFragment(R.string.cards_title, R.string.cards_text),
// cardFragment(R.string.expansion_title, R.string.expansion_text)));
mDefaultBg = new ColorDrawable(R.color.dark_grey);
mClearBg = new ColorDrawable(android.R.color.transparent);
}
LruCache<Integer, Drawable> mRowBackgrounds = new LruCache<Integer, Drawable>(3) {
@Override
protected Drawable create(final Integer row) {
int resid = BG_IMAGES[row % BG_IMAGES.length];
new DrawableLoadingTask(mContext) {
@Override
protected void onPostExecute(Drawable result) {
TransitionDrawable background = new TransitionDrawable(new Drawable[] {
mDefaultBg,
result
});
mRowBackgrounds.put(row, background);
notifyRowBackgroundChanged(row);
background.startTransition(TRANSITION_DURATION_MILLIS);
}
}.execute(resid);
return mDefaultBg;
}
};
private Fragment cardFragment(int titleRes, int textRes) {
Resources res = mContext.getResources();
CardFragment fragment =
CardFragment.create(res.getText(titleRes), res.getText(textRes));
// Add some extra bottom margin to leave room for the page indicator
fragment.setCardMarginBottom(
res.getDimensionPixelSize(R.dimen.card_margin_bottom));
return fragment;
}
static final int[] BG_IMAGES = new int[] {
R.drawable.user1,
R.drawable.user2,
R.drawable.user3,
R.drawable.user4
};
/** A convenient container for a row of fragments. */
private class Row {
final List<Fragment> columns = new ArrayList<Fragment>();
public Row(Fragment... fragments) {
for (Fragment f : fragments) {
add(f);
}
}
public void add(Fragment f) {
columns.add(f);
}
Fragment getColumn(int i) {
return columns.get(i);
}
public int getColumnCount() {
return columns.size();
}
}
@Override
public Fragment getFragment(int row, int col) {
Row adapterRow = mRows.get(row);
return adapterRow.getColumn(col);
}
@Override
public Drawable getBackgroundForRow(final int row) {
return mRowBackgrounds.get(row);
}
@Override
public int getRowCount() {
return mRows.size();
}
@Override
public int getColumnCount(int rowNum) {
return mRows.get(rowNum).getColumnCount();
}
class DrawableLoadingTask extends AsyncTask<Integer, Void, Drawable> {
private static final String TAG = "Loader";
private Context context;
DrawableLoadingTask(Context context) {
this.context = context;
}
@Override
protected Drawable doInBackground(Integer... params) {
Log.d(TAG, "Loading asset 0x" + Integer.toHexString(params[0]));
return context.getResources().getDrawable(params[0]);
}
}
}

Related

[q][solved]View Pager doesnt adds fragments to backstack

i have made a fragment which contains view pager.it uses list of fragments so that fragments can be added or removed dynamically.
each child fragment of viewpager is a listfragment and loads list using asynctask
now my problem is when i have 3-4 child fragments in view pager,after switching to other pages(tabs),the earlier ones in which list is already loaded are reset automatically when i swipe back to them.so i want that they must be added to backstact so that they can be resumed.
Code:
public class TabFragment extends android.support.v4.app.Fragment {
List fragments = new ArrayList();
public PagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
String home;
ActionBar actionBar;
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.tabfragment,
container, false);
mSectionsPagerAdapter = new ScreenSlidePagerAdapter(getChildFragmentManager());
mViewPager = (ViewPager) rootView.findViewById(R.id.pager);
actionBar = getActivity().getActionBar();
mViewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrolled(int p1, float p2, int p3) {
// TODO: Implement this method
}
public void onPageSelected(int p1) { // TODO: Implement this// method
Main ma = ((Main) fragments.get(p1));
if (ma.current != null) {
ma.bbar(ma.current);
}
}
public void onPageScrollStateChanged(int p1) {
// TODO: Implement this method
}
});
mViewPager.setAdapter(mSectionsPagerAdapter);
return rootView;
}
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
[user=439709]@override[/user]
public CharSequence getPageTitle(int position) {
//Toast.makeText(getActivity(),""+position,Toast.LENGTH_SHORT).show();
Main ma = ((Main) fragments.get(position));
return new File(ma.current).getName();
}
public int getCount() {
// TODO: Implement this method
return fragments.size();
}
public ScreenSlidePagerAdapter(android.support.v4.app.FragmentManager fm) {
super(fm);
}
[user=439709]@override[/user]
public android.support.v4.app.Fragment getItem(int position) {
android.support.v4.app.Fragment f;
f = fragments.get(position);
return f;
}
}
public void removePage(int position) {
if(position==0){Toast.makeText(getActivity(),"Main Screen Cant be removed",Toast.LENGTH_LONG).show();}else{
fragments.remove(position);
mSectionsPagerAdapter.notifyDataSetChanged();
mViewPager.setCurrentItem(position-1);
}
}
public void add(String text) {
android.support.v4.app.Fragment main = new Main();
Bundle b = new Bundle();
int p = fragments.size();
b.putString("path", text);
b.putInt("pos", p);
main.setArguments(b);
fragments.add(main);
mSectionsPagerAdapter.notifyDataSetChanged();
mViewPager.setCurrentItem(p);
}

[Q] GPS with Fragment

Good day. I start learn Fragment and I want use GPS in my Application. and I use Fragment. in fragment who view coordinate i writed next code
Code:
public class MyFragment2 extends Fragment {
public static final String BUTTON_INDEX = "button_index";
private static final int BUTTON_INDEX_DEFAULT = -1;
static TextView txt;
static TextView txt2;
String[] mCatDescription;
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle saveInstanceState){
View viewHier = inflater.inflate(R.layout.fragment2, container, false);
txt = (TextView)viewHier.findViewById(R.id.textView1);
txt2 = (TextView)viewHier.findViewById(R.id.textView2);
mCatDescription =getResources().getStringArray(R.array.cats);
Bundle args = getArguments();
int buttonIndex = args != null ? args.getInt(BUTTON_INDEX, BUTTON_INDEX_DEFAULT):BUTTON_INDEX_DEFAULT;
if(buttonIndex != BUTTON_INDEX_DEFAULT){
setDiscription(buttonIndex);
}
return viewHier;
}
public void setDiscription(int buttonIndex){
GPSWork gpsWork = new GPSWork();
switch(buttonIndex){
case 1:
txt2.setText("one");
break;
case 2:
gpsWork.GetCoordinates();
break;
case 3:
txt2.setText("therd");
break;
}
}
}
Ok. when we click on button 2 we call method GetCoordinates(). this class have next code
Code:
public class GPSWork{
LocationManager locationManager;
public GPSWork(){
locationManager = (LocationManager)MainActivity.mContext.getSystemService(Context.LOCATION_SERVICE);
}
public void GetCoordinates(){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
5000, 5, locationListener);
}
private LocationListener locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onProviderDisabled(String provider) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onProviderEnabled(String provider) {
MyFragment2.txt2.setText("OK");
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
MyFragment2.txt2.setText("OK");
}
};
}
how we see, we should get text OK on TextView on MainActivity. but we don't have text, whats wrong? and if I change code in method GetCoordinates() on
Code:
public void GetCoordinates(){
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
1000, 10, locationListener);
}
all work fine, i see text in TextView (OK )

Passing data between two fragments

Hello guys,
I have a list of fragments created and I want to delete these fragment by long pressing on them. However, before doing so I want dialog fragment to pop up and offer the user the choice to delete or not. I have created the two fragments but I can't get the data across each other. I can't give functionality to the 'OK' button. Here is my code:
Code:
public class CourseListFragment extends Fragment implements
OnItemClickListener, OnItemLongClickListener {
public static final String ARG_ITEM_ID = "course_list";
public static final String YES_NO = "modify";
Activity activity;
ListView courseListView;
ArrayList<Course> courses;
CourseListAdapter courseListAdapter;
CourseDAO courseDAO;
private GetEmpTask task;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activity = getActivity();
courseDAO = new CourseDAO(activity);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.schedule_fragment_course_list,
container, false);
findViewsById(view);
task = new GetEmpTask(activity);
task.execute((Void) null);
courseListView.setOnItemClickListener(this);
courseListView.setOnItemLongClickListener(this);
return view;
}
private void findViewsById(View view) {
courseListView = (ListView) view.findViewById(R.id.list_course);
}
@Override
public void onItemClick(AdapterView<?> list, View view, int position,
long id) {
Course course = (Course) list.getItemAtPosition(position);
if (course != null) {
Bundle arguments = new Bundle();
arguments.putParcelable("selectedCourse", course);
CustomCourseDialogFragment customEmpDialogFragment = new CustomCourseDialogFragment();
customEmpDialogFragment.setArguments(arguments);
customEmpDialogFragment.show(getFragmentManager(),
CustomCourseDialogFragment.ARG_ITEM_ID);
}
}
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
// Show dialogFragment
FragmentManager fm = getActivity().getSupportFragmentManager();
CheckDialogFragment dialog = new CheckDialogFragment();
dialog.show(fm, YES_NO);
Course employee = (Course) parent.getItemAtPosition(position);
// Use AsyncTask to delete from database
courseDAO.deleteEmployee(employee);
courseListAdapter.remove(employee);
return true;
}
public class GetEmpTask extends AsyncTask<Void, Void, ArrayList<Course>> {
private final WeakReference<Activity> activityWeakRef;
public GetEmpTask(Activity context) {
this.activityWeakRef = new WeakReference<Activity>(context);
}
@Override
protected ArrayList<Course> doInBackground(Void... arg0) {
ArrayList<Course> courseList = courseDAO.getCourses();
return courseList;
}
@Override
protected void onPostExecute(ArrayList<Course> empList) {
if (activityWeakRef.get() != null
&& !activityWeakRef.get().isFinishing()) {
courses = empList;
if (empList != null) {
if (empList.size() != 0) {
courseListAdapter = new CourseListAdapter(activity,
empList);
courseListView.setAdapter(courseListAdapter);
} else {
Toast.makeText(activity, "No Course Records",
Toast.LENGTH_LONG).show();
}
}
}
}
}
/*
* This method is invoked from MainActivity onFinishDialog() method. It is
* called from CustomEmpDialogFragment when an employee record is updated.
* This is used for communicating between fragments.
*/
public void updateView() {
task = new GetEmpTask(activity);
task.execute((Void) null);
}
@Override
public void onResume() {
getActivity().setTitle("Course Schedule");
getActivity().getActionBar().setTitle("Course Schedule");
super.onResume();
}
}
//Dialog Fragment
Code:
public class CheckDialogFragment extends DialogFragment {
CourseListAdapter courseListAdapter;
CourseDAO courseDAO;
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// TODO Auto-generated method stub
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setTitle("Do you want to delete?")
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
}
})
.setNegativeButton(android.R.string.cancel,
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
return builder.create();
}
}
I have problems trying to get the data from onItemLongClick() of CourseListFragment to CourseListFragment. Any help would be greatly appreciated.

[Q] CustomAdapter Help!

For my App I want when you click into the autocompletetextview it will bring up a list of chemicals and then when you choose your chemical it will put the chemical name in the autocomplete field and also put the corresponding weight into an edittext field.
The approach I went with this was using a customadapter so when you pick one it will give the other. It is my first time making one so I'm not sure if it's 100% correct. It would be great if you guys had any suggestions. Thanks
Currently this is the code that I have.
editText4 is the autocompletetextview field I want the chemical name to appear in.
editText is the editText field i want the number to appear in.
MainActivity .java
Code:
public void Chem() {
Chemical chemical_data[] = new Chemical[]
{
new Chemical("Acid", 125.33),
new Chemical("Blue", 145.3356),
};
ChemicalAdapter adapter = new ChemicalAdapter(this, R.layout.sollayout, chemical_data);
chemname = (AutoCompleteTextView) findViewById(R.id.editText4);
weightval = (EditText) findViewById(R.id.editText);
//ChemicalAdapter header = new ChemicalAdapter(this, R.layout.sollayout, null);
//weightval.addHeaderView(header);
chemname.setAdapter(adapter);
}
public void Chemname()
{
chemname = (AutoCompleteTextView) findViewById(R.id.editText4);
AutoCompleteTextView b = (AutoCompleteTextView) findViewById(R.id.editText4);
b.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Chem();
}
});
}
Chemical.java
Code:
public class Chemical {
String chemicalValue;
double weight;
public Chemical(String chemicalValue, double weight) {
this.chemicalValue = chemicalValue;
this.weight = weight;
}
public String getChemicalValue() {
return chemicalValue;
}
public double getWeight() {
return weight;
}
}
ChemicalAdapter.java
Code:
public class ChemicalAdapter extends ArrayAdapter<Chemical> {
Context context;
int layoutResourceId;
Chemical data[] = null;
public ChemicalAdapter(Context context, int layoutResourceId, Chemical[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ChemicalHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ChemicalHolder();
holder.chemname = (AutoCompleteTextView)row.findViewById(R.id.editText4);
holder.weightval = (EditText)row.findViewById(R.id.editText);
row.setTag(holder);
}
else
{
holder = (ChemicalHolder)row.getTag();
}
Chemical chemical = data[position];
holder.weightval.setText(String.valueOf(chemical.weight));
holder.chemname.setText(chemical.chemicalValue);
return row;
}
static class ChemicalHolder
{
AutoCompleteTextView chemname;
EditText weightval;
}
}

[SOLVED] Android getParentFragment() returns null in ViewPager within a Fragment

I have an Activity that contains a Fragment with a ViewPager. Then I call a method of a Fragment within the ViewPager. But if that Fragment then calls getParentFragment(), it returns null.
Why is getParentFragment() null?
The main Fragment that contains a ViewPager:
Code:
public class MyFragment extends Fragment {
private TabLayout mTabLayout;
private ViewPager mViewPager;
private ViewPagerAdapter mAdapter;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View view = getView();
// Setup the ViewPager
mViewPager = (ViewPager) view.findViewById(R.id.container);
setupViewPager(mViewPager);
// Setup the TabLayout
mTabLayout = (TabLayout) view.findViewById(R.id.tabs);
mTabLayout.setupWithViewPager(mViewPager);
}
// This method is called from Activity
public void callNestedFragment() {
if (isDetached()) {
return;
}
((Fragment0) mViewPager.getItem(0)).testMethod();
}
}
The nested Fragment (inside mViewPager):
Code:
public class Fragment0 extends Fragment {
...
public void testMethod() {
if (isDetached()) {
return;
}
// Why is getParentFragment() null?
Log.i(TAG, "Parent fragment:" + getParentFragment());
return;
}
}
The ViewPagerAdapter:
Code:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private Context mContext;
public ViewPagerAdapter(FragmentManager manager, Context context) {
super(manager);
mContext = context;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment0();
case 1:
return new Fragment1();
case 2:
return new Fragment2();
case 3:
return new Fragment3();
case 4:
return new Fragment4();
}
return null;
}
@Override
public int getCount() {
return 5;
}
}
If more code is needed, please let me know. Thanks for your help.
Info
SuperThomasLab said:
I have an Activity that contains a Fragment with a ViewPager. Then I call a method of a Fragment within the ViewPager. But if that Fragment then calls getParentFragment(), it returns null.
Why is getParentFragment() null?
The main Fragment that contains a ViewPager:
Code:
public class MyFragment extends Fragment {
private TabLayout mTabLayout;
private ViewPager mViewPager;
private ViewPagerAdapter mAdapter;
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
View view = getView();
// Setup the ViewPager
mViewPager = (ViewPager) view.findViewById(R.id.container);
setupViewPager(mViewPager);
// Setup the TabLayout
mTabLayout = (TabLayout) view.findViewById(R.id.tabs);
mTabLayout.setupWithViewPager(mViewPager);
}
// This method is called from Activity
public void callNestedFragment() {
if (isDetached()) {
return;
}
((Fragment0) mViewPager.getItem(0)).testMethod();
}
}
The nested Fragment (inside mViewPager):
Code:
public class Fragment0 extends Fragment {
...
public void testMethod() {
if (isDetached()) {
return;
}
// Why is getParentFragment() null?
Log.i(TAG, "Parent fragment:" + getParentFragment());
return;
}
}
The ViewPagerAdapter:
Code:
public class ViewPagerAdapter extends FragmentPagerAdapter {
private Context mContext;
public ViewPagerAdapter(FragmentManager manager, Context context) {
super(manager);
mContext = context;
}
@Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new Fragment0();
case 1:
return new Fragment1();
case 2:
return new Fragment2();
case 3:
return new Fragment3();
case 4:
return new Fragment4();
}
return null;
}
@Override
public int getCount() {
return 5;
}
}
If more code is needed, please let me know. Thanks for your help.
Click to expand...
Click to collapse
Post Full Logcat Error & Fragment Class
:good:
I found the answer. If isDetached() is true, it doesn't mean getParentFragment() is not null.
So instead of the previous check in testMethod(), this is the new code:
Code:
public void testMethod() {
if (isDetached() && getParentFragment() != null) {
return;
}
...
}
I also now call the same method again in the onStart() method within Fragment0, where getParentFragment() should not be null.

Categories

Resources