How to generate random fragments in Android? - java

I have this project, a quiz app to be specific. I have 10 questions to be asked and I want it to be randomly appear in my app. As of now, I put those questions on Fragments using Tabbed Activity. I have no idea how to randomize it.
Should I use Activity rather than fragments?
This is the code where I call those fragments:
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0: return new FirstFragment();
case 1: return new SecondFragment();
case 2: return new ThirdFragment();
}
return null;
}
}
Any recommendations/suggestions? I really need this app to be done. Thanks!

Try to create an array for those Fragments:
Class[] classes=new Class[numberOfDirrefentFragmenTypes];
Class c1 = FirstFragment.class;
Class c2 = SecondFragment.class;
classes[0]=c1;
classes[1]=c2;
Then you can pick a random class and instantiate it:
Random random=new Random();
Class randomClass=classes[random.nextInt(classes.size())];
So you can create a random fragment at any time:
Constructor<?> ctor = randomClass.getConstructor();
Object object = ctor.newInstance(new Object[] { ctorArgument });
It might not be the optimal solution, but it should work.
I hope it helps (I did not compile the code).

Sorry for the late answer, I hope to help others who have the same needs
Fragments have a special (static) method called instantiate(Context, String) that you can use like this:
CustomFragment cf = Fragment.instantiate(getApplicationContext(), CustomFragment.class.getName())
So if you need to generate a random fragment from a list of fragments, you can do it like this:
ArrayList<String> fragList = new ArrayList<>();
fragList.add(FirstCustomFragment.class.getName());
fragList.add(SecondCustomFragment.class.getName());
fragList.add(ThirdCustomFragment.class.getName());
int r = new Random().nextInt(fragList.size());
Fragment cf = Fragment.instantiate(getApplicationContext(), fragList.get(r));
You can also pass a series of params with the bundle argument (Fragment.instantiate(Context, String, Bundle)) . Its an option args that you can use in the fragment's onCreate method like this:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
customData = getArguments().getString("data");
}
}
if you want to see how it works under the hood take a look here, you'll see that is not heavier for the device and its a good way to not use the reflection by yourself

Related

Past value from child fragment -> mainactivity cannot cast fragment_fr_event_Birthday to fragment_fr_event_wedding android studio

I have a Fragment inside the mainActivity, the fragment contains fragmentcontainerView which can be replaced by multiple child fragments with spinner onselectedListener. I want to able to pass those values from the child fragment via eg: Do something with: fragmentevent.TogetFName(); with a button in Mainactivity. In the parent fragment , I get the value from the child fragment(fragment_Birthday) with fragment_fr_event_birthday = (fragment_fr_event_Birthday) getChildFragmentManager().findFragmentById(R.id.fragment_event_child_fragment); and other value from other childfragment with frag_fr_event_wed = (fragment_fr_event_wedding) getChildFragmentManager().findFragmentById(R.id.fragment_event_child_fragment);, I know that they cannot be assigned with the different fragment class at once, but is there a clever way to do this or is there any other way I can pass value from child -> parent fragment->mainActivity
MainActivity:
public void onClick(View view){
case "Event":
Fragment_fr_Event fragment_fr_event = (Fragment_fr_Event) getSupportFragmentManager().findFragmentById(R.id.fragment_generated_mainView);
if(fragment_fr_event.TogetWedChildFcoupleName() !=null && fragment_fr_event.TogetEventType().equals("Wedding")){
testThis.setText(fragment_fr_event.TogetWedChildFcoupleName());
}if( fragment_fr_event.TogetEventType().equals("Birthday") && fragment_fr_event.TogetBirthdayFName() !=null){
testTat.setText(fragment_fr_event.TogetBirthdayFName());
}
}
ChildFragment(BirthdayFragment):
public String TogetEventBirthdayFName (){
EditText FBirthdayName = rootView.findViewById(R.id.Edittext_birthDay_FirstName);
return FBirthdayName.getText().toString();
}
ChildFragment(Wedding fragment):
public String toGetFcoupleName(){
EditText FCoupleName = rootView.findViewById(R.id.textView_wedding_Name);
return FCoupleName.getText().toString();
}
ParentFragment(EventFragment):
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Spinner TypeEventSpinner = rootview.findViewById(R.id.type_event);
TypeEventSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String tag_items = parent.getItemAtPosition(position).toString();
switch (tag_items){
case "Wedding":
frag_fr_event_wed = new fragment_fr_event_wedding();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_event_child_fragment, frag_fr_event_wed).disallowAddToBackStack().commit();
break;
case "Birthday":
fragment_fr_event_birthday = new fragment_fr_event_Birthday();
transaction = getChildFragmentManager().beginTransaction();
transaction.replace(R.id.fragment_event_child_fragment , fragment_fr_event_birthday).disallowAddToBackStack().commit();
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public String TogetWedChildFcoupleName(){
if(frag_fr_event_wed !=null){
frag_fr_event_wed = (fragment_fr_event_wedding) getChildFragmentManager().findFragmentById(R.id.fragment_event_child_fragment);
return frag_fr_event_wed.toGetFcoupleName();
}return "Empty";
}
public String TogetBirthdayFName(){
if(fragment_fr_event_birthday != null){
fragment_fr_event_birthday = (fragment_fr_event_Birthday) getChildFragmentManager().findFragmentById(R.id.fragment_event_child_fragment);
return fragment_fr_event_birthday.TogetEventBirthdayFName();
}
return "Empty";
}
To be honest , I couldn't understand what you did there , but i got what you want , you want to communicate with parent's parent class , the way you are doing it made it so complicated even it's not readable , BUT of course there are always a good way to do something , in your case there are Android Navigation Component , which give you the simplicity and power to do make it much more easy to handle , You can put all your fragment in one graph and from within the destinations "fragment are called destinations here" you can communicate with other fragment and the parent using actions and global actions "going from one fragment to another is called action here" parameters, but there are no need to a parent's parent here , all destinations and its parent can share one ViewModel which will allow you to share data all around your app .
You can read more if it sound good to you here

How to refresh Fragment and pass info based on its position?

I`ve got an activity with ViewPager. There is 1 Fragment class - ScheduleFragment and a BroadcastReceiver in it. What I need is to get info and fill up the list in the fragment, based on its position.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
ScheduleFragment scheduleFragment = new ScheduleFragment();
return scheduleFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 5 total pages.
return 5;
}
#Override
public int getItemPosition(Object object) {
return super.getItemPosition(object);
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.descr_monday);
case 1:
return getString(R.string.descr_tuesday);
case 2:
return getString(R.string.descr_wednesday);
case 3:
return getString(R.string.descr_thursday);
case 4:
return getString(R.string.descr_friday);
}
return null;
}
And here the ScheduleFragment`s methods:
public ScheduleFragment newInstance(Integer day) {
ScheduleFragment fragment = new ScheduleFragment();
Bundle args = new Bundle();
args.putInt("day", day);
fragment.setArguments(args);
return fragment;
}
private class ScheduleBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ArrayList<Lesson> result = (ArrayList<Lesson>) intent.getSerializableExtra("schedule");
ArrayList<Lesson> dataToInsert = new ArrayList<>();
Log.i("ASSSSSSSSSSSS", day.toString());
for (Lesson lesson : result) {
if (Objects.equals(lesson.getDay(), day)) {
dataToInsert.add(lesson);
}
}
adapter = new ScheduleListAdapter(context, result);
SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(adapter);
swingBottomInAnimationAdapter.setAbsListView(schedule_listView);
schedule_listView.setAdapter(swingBottomInAnimationAdapter);
adapter.notifyDataSetChanged();
}
}
I also have a Spinner in Toolbar with weeks. So also I want to update the fragment when I pick another week.
Please, guys. Help me. I`ve tried some solutions, but none of them helped me!
Hope for you assistance
I'm probably not an expert on this, but I just completed a project full of fragments. The 'dirty' way I passed data between them was accomplished by using a singleton class in my project. This probably isn't the best solution, though.
For instance, my project included a fragment which I updated based on options in a settings activity. The FamilyMap (familyMap) class is my singleton, and I kept a settings model containing maps of needing information within that object. The code shown here is updating that settings model based on user interaction.
public void mapTypeSelection(String selection)
{
Log.d("Map Selection", selection);
switch(selection)
{
case "Normal":
familyMap.getMapFrag().getmMap().setMapType(GoogleMap.MAP_TYPE_NORMAL);
familyMap.getSettings().setMapType(new Pair<String, Integer>("Normal", GoogleMap.MAP_TYPE_NORMAL));
break;
case "Satellite":
familyMap.getMapFrag().getmMap().setMapType(GoogleMap.MAP_TYPE_SATELLITE);
familyMap.getSettings().setMapType(new Pair<String, Integer>("Satellite", GoogleMap.MAP_TYPE_SATELLITE));
break;
case "Hybrid":
familyMap.getMapFrag().getmMap().setMapType(GoogleMap.MAP_TYPE_HYBRID);
familyMap.getSettings().setMapType(new Pair<String, Integer>("Hybrid", GoogleMap.MAP_TYPE_HYBRID));
break;
case "Terrain":
familyMap.getMapFrag().getmMap().setMapType(GoogleMap.MAP_TYPE_TERRAIN);
familyMap.getSettings().setMapType(new Pair<String, Integer>("Terrain", GoogleMap.MAP_TYPE_TERRAIN));
break;
default:
break;
}
}
//private method of your class
private int getIndex(Spinner spinner, String myString)
{
int index = 0;
for (int i=0;i<spinner.getCount();i++){
if (spinner.getItemAtPosition(i).toString().equalsIgnoreCase(myString)){
index = i;
break;
}
}
return index;
}
public Pair<String, Integer> colorLineSelection(String selection)
{
Log.d("Map Selection", selection);
switch(selection)
{
case "Red":
return new Pair<String, Integer>("Red", Color.RED);
case "Blue":
return new Pair<String, Integer>("Blue", Color.BLUE);
case "Green":
return new Pair<String, Integer>("Green", Color.GREEN);
default:
return null;
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch(parent.getId()){
case R.id.mapTypeSpinner:
mapTypeSelection((String)parent.getItemAtPosition(position));
break;
case R.id.lifeLineSpinner:
FamilyMap.getInstance().getSettings().setLifeColor(colorLineSelection((String)parent.getItemAtPosition(position)));
familyMap.getMapFrag().drawLines();
break;
case R.id.spouseLineSpinner:
FamilyMap.getInstance().getSettings().setSpouseColor(colorLineSelection((String) parent.getItemAtPosition(position)));
familyMap.getMapFrag().drawLines();
break;
case R.id.familyLineSpinner:
FamilyMap.getInstance().getSettings().setFamilyColor(colorLineSelection((String) parent.getItemAtPosition(position)));
familyMap.getMapFrag().drawLines();
break;
default:
break;
}
}
The other thing I did was I retained the instance of my fragment - it was the main portion of my app, so it made sense for my situation. That allowed me to be able to update the original fragment when an option was selected. I also set the fragment to update when a certain result was reached by using startActivityForResult().
I think a better (cleaner, more acceptable) option for sending the data to your fragment would be object serialization, but at least in my case, that proved to be more work than I could afford at the time.
Hopefully this at least helps to point you in the right direction!
So, after trying, trying and a lot of trying I figured it out!
In newInstance method, where I create new instance of Fragment I`ve added a bundle with day, according to fragments position
public ScheduleFragment newInstance(Integer day) {
ScheduleFragment fragment = new ScheduleFragment();
Bundle args = new Bundle();
args.putInt("day", day);
fragment.setArguments(args);
return fragment;
}
Then, in fragment's onCreateView I get this argument with getArguments().getInt("day"); and put it into private Integer dayglob; field, which means, that its different for every fragment.
Now, when I have 'day' variable in my fragment I can put info into list according to provided day:
private class ScheduleBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
ArrayList<Lesson> result = (ArrayList<Lesson>) intent.getSerializableExtra("schedule");
ArrayList<Lesson> dataToInsert = new ArrayList<>();
for (Lesson lesson : result) {
if (Objects.equals(lesson.getDay(), dayglob)) {
dataToInsert.add(lesson);
}
}
adapter = new ScheduleListAdapter(context, dataToInsert);
SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(adapter);
swingBottomInAnimationAdapter.setAbsListView(schedule_listView);
schedule_listView.setAdapter(swingBottomInAnimationAdapter);
try {
getActivity().unregisterReceiver(mScheduleBroadcastReceiver);
} catch (IllegalArgumentException e) {
Log.i("Unregister", e.toString());
}
}
}
Every fragment got its own "onReceive" and wor on data from service for specific fragment.
Also, about the week spinner and updating the lists according to its value: I've made a static field public static Spinner week_spinner;, initialized it it onCreate method of my Activity and then, in fragment's "onCreateView" I made a request to my database like this:
requestQueue.add(connectionManager.getSchedule(this, savedUser.getGroup(), MainActivity.week_spinner.getSelectedItemPosition() + 1));
The only matter thing here is getting value by accessing spinner via static reference.
And, also, I've set Listener which says to fragments something like
Hey, guys! You are not up to date! Update yourself!
week_spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
mViewPager.getAdapter().notifyDataSetChanged();
}
});
And a little trick which make it possible is to change getItemPositionin FragmentPagerAdapter class (SectionsPagerAdapter in my case)
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
It`s kinda tricky, I guess, but its the only way i can figure it out
I hope, this will help someone!

Fragment listview update from activity

I am pretty new to Android (3 days), but I have a pretty good background in PHP (which may be the cause of my confusion in a Java based environment). I started building an Android app using Android Studio (Beta). I created the default Android Studio activity with the Navigation Drawer Activity. I edited the activity fragment part to look like this:
#Override
public void onNavigationDrawerItemSelected(int position) {
Bundle bundle = new Bundle();
bundle.putStringArrayList("contacts", arr);
bundle.putStringArrayList("messages", messages);
Fragment fragment = null;
switch (position) {
case 0:
fragment = new FriendsFragment();
break;
case 1:
fragment = new ChatsFragment();
break;
case 2:
fragment = new GroupsFragment();
break;
case 3:
fragment = new LogoutFragment();
break;
default:
break;
}
if (fragment != null) {
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment).addToBackStack(null).commit();
}
}
As you can see I am passing a Bundle to my Fragments called "messages" and "contacts" when an item is selected in the Navigation Drawer. The "messages" bundle are XMPP messages received by the aSmack library from an OpenFire server. So basically I'm trying to create a XMPP client. When I run the app I can receive the messages in the "ChatsFragment".
Now my problem:
I have to press the "ChatsFragment" item on the drawer to have my messages updated (re-receive the bundle) everytime I feel like there are new messages received from the server. But I want this to be done automatically by the fragment.
First I would like to know if my procedure is correct (Activity listens to server, creates bundle, send bundle to fragment, bundle updates messages on receive**)
** = This part I haven't been able to understand how to implement.
1- If the procedure is correct tell me how I should get the messages to be updated by the fragment through the activity?
2- If this is not the correct way to do things in Android, recommend me a way of doing it.
My code for displaying the messages in fragment:
private void displayListView() {
// Messages array list
List<String> contacts = getArguments().getStringArrayList("messages");
//System.out.println("arr: " + contacts);
//create an ArrayAdaptar from the String Array
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(getActivity(),
R.layout.url_list, contacts);
ListView listView = (ListView) getView().findViewById(R.id.listView);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
//enables filtering for the contents of the given ListView
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Send the URL to the host activity
//mListener.onURLSelected(((TextView) view).getText().toString());
}
});
}
Thanks in advance.
Typically for long running operations in the background, like listening to a server, incoming messages, etc, you need to use Services. You do so by subclassing the Service class in Android.
Now for your problem - the design approach should be that you have a background service listening to incoming messages. Anytime a message is received (an input stream in your socket operator) you should send a "broadcast" an intent that a message was received. A custom broadcast receiver that you create should wait for this broadcast. Within the onReceive() method of this receiver, you should trigger the creation of the bundle and updating your message.
Remember you should always delegate your long running operations in Android to services. That is exactly what they are for.
So basically if you're already listening for new messages to come in your activity, then you must have some kind of callback like onMessageRecieved() or something like that.
If you do, you can then notify your fragment in this way.
Create a field (goes under your class declaration) called curFrag, so something like this:
public class MyActivity extends Activity {
private Fragment curFrag;
//other code...
}
then in the code you posted you would initialize the curFrag there, but you also need to set a tag for the current fragment. This will be based on your case statement. Make some final string variables as tags.
i.e.
public static final String CHATSTAG = "chatstag";
#Override
public void onNavigationDrawerItemSelected(int position) {
Bundle bundle = new Bundle();
bundle.putStringArrayList("contacts", arr);
bundle.putStringArrayList("messages", messages);
Fragment fragment = null;
String tag = null;
switch (position) {
case 0:
tag = FRIENDSTAG;
fragment = new FriendsFragment();
break;
case 1:
tag = CHATSTAG;... and so on through the switch statement.
fragment = new ChatsFragment();
break;
case 2:
fragment = new GroupsFragment();
break;
case 3:
fragment = new LogoutFragment();
break;
default:
break;
}
if (fragment != null) {
fragment.setArguments(bundle);
FragmentManager fragmentManager = getSupportFragmentManager();
//remember to set the tag.
if(tag != null) {
fragmentManager.beginTransaction()
.replace(R.id.container, fragment, tag).addToBackStack(null).commit();
} else {
fragmentManager.beginTransaction()
.replace(R.id.container,fragment,DEFAULTTAG).addToBackStack(null).commit();
}
//new code
curFrag = fragment;
}
}
Now in your activity when a new message comes in, check the tag of the fragment and then if it matches a certain fragment, notify the fragment that new data has come in and retrieve it in the fragment.
public void onMessageRecieved() {
if(curFrag.getTag().equalsIgnoreCase(CHATSTAG)) {
ChatsFragment frag = (ChatsFragment) curFrag;
frag.notifyDataRecieved();
}
}
Once you have a reference to your fragment in the activity, you have access to any public methods in that fragment.
If your fragment cannot access the data on its own, then you'll need to get a reference to the activity and create a method in the activity that returns the new data.
So in your activity:
public String getMessageData() {
String newData = ...//get stuff from server;
return newData;
}
then in your fragment
public void notifyNewMessage() {
try {
MyActivity activity = (MyActivity) getActivity();
} catch (ClassCastException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
String message = activity.getMessageData();
//do something with the message.
}
It's not necessarily pretty but it works pretty well. You should also check to make sure your fragments are attached when you do this so that you avoid null exceptions.
Hope this helps!

Android : FragmentPagerAdapter don't saved the state of Fragment?

I have a problem with the FragmentPagerAdapter .
I can not save the state of the Fragment and then there is the view that within the Fragment . Whenever I use the swipe left and right , the Fragment is recreated by overriding the method getItem ( int position ) in the static class that extends the FragmentPagerAdapter .
public static class GraphicsCollectionPagerAdapter extends FragmentPagerAdapter {
final int NUM_ITEMS = 3; // number of tabs
public GraphicsCollectionPagerAdapter(FragmentManager fm) {
super(fm);
fragmentList = new AnalyzeFragmentPageListWithDate();
fragment1 = new AnalyzeFragmentPage1();
fragment2 = new AnalyzeFragmentPage2();
}
#Override
public Fragment getItem(int position) {
//Log.i(TAG, "getItem() -> New fragment at position " + position);
switch (position) {
case 0:
return fragmentList;
case 1:
return fragment1;
case 2:
return fragment2;
}
return null;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Fragm1";
case 1:
return "Fragm2";
case 2:
return "Fragm3";
}
return "OBJECT " + (position + 1);
}
}
Within the method OnCreateView of each instance of the Fragment there are several steps to the SQLite database and this causes a saturation of the Database Connection Pool.
The warning found whenever change dynamically fragment is: "W / SQLiteConnectionPool (1111 ) : A SQLiteConnection object for database ' / data / data / com.myapp / databases / mydb ' was leaked ! Please fix your application to end transactions in progress properly and to close the database When it is no longer needed . "
I already tried to use the FragmentStatePagerAdapter without success.
Could you kindly tell me how to proceed ? I do not want the Fragment is regenerated each time, causing problems to the database. Have you got an example for save Fragment/View sate?
I have not found any suggestion for now .
thank you very much
use setOffscreenPageLimit property for your ViewPager object.
ViewPager pager = (ViewPager) findViewById(R.id.viewPagerId);
pager.setOffscreenPageLimit(2);
First of all create a new instance of Fragment every time the getItem() is called
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
return new FragmentList();
case 1:
return new AnalyzeFragmentPage1();
case 2:
return new AnalyzeFragmentPage2();
}
return null;
}
Note that FragmentPagerAdapter does not work exactly like normal Adapter meaning it does NOT use an empty vessel Fragment and then refills it with different data.
Instead it creates a new Fragment whenever it is needed. So you should pass data (if any) when the Fragment is created. Please study the example in the Android docs.
In a real time projects instead of passing current position to a new Fragment you could pass the actual ID of the entry that a Fragment should refer to.

Android Fragment issue

i'm new to Android, (not programming, or even Java) so bear with me.
I'm trying to get a handle on the use of fragments.
I've got a project that I've created using the default swipe/actionbar. I've extended this further to handle the settings i want.... however i don't quite understand what's going on/how to fix this.
/**
* 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 DummySectionFragment (defined as a static inner class
// below) with the page number as its lone argument.
Fragment fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
// Show 8 total pages.
return 8;
}
#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);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
case 3:
return getString(R.string.title_section4).toUpperCase(l);
case 4:
return getString(R.string.title_section5).toUpperCase(l);
case 5:
return getString(R.string.title_section6).toUpperCase(l);
case 6:
return getString(R.string.title_section7).toUpperCase(l);
case 7:
return getString(R.string.title_section8).toUpperCase(l);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
int position;
position = getArguments().getInt(ARG_SECTION_NUMBER)-1;
View rootView;
TextView dummyTextView;
I don't really want anything static or final here, and I've got it mostly worked out but I don't understand the following line or how to fix it. I kinda get what it's doing.
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
The error is: cannot make a static reference to the non-static field DummySectionFragment.ARG_SECTION_NUMBER
There is probably a simple fix for this, i just am unfamiliar enough with Android and Java, as my current job i spend all my time in SQL Server.
-- EDITED ADDITIONS
i'm not opposed to anything static or final etc. the problem i'm not quite understanding is when i want to DO something in each of those fragments. I have a textview on each of those layouts and i want to be able to manipulate them say in a loop. I think i'm stuck in a circle and can't figure my way out... lol.
For example below the code I put above is
case 4:
rootView = inflater.inflate(R.layout.fragment_main_location,container, false);
dummyTextView= (TextView) rootView .findViewById(R.id.section_label);
// location
Button btnShowLocation = (Button) rootView.findViewById(R.id.btnShowLocation);
Button btnShowDBLocList = (Button) rootView.findViewById(R.id.btnShowDBLocList);
Button btnLocationsCount = (Button) rootView.findViewById(R.id.btnLocationsCount);
Button btnTruncateDBLocationsTable = (Button) rootView.findViewById(R.id.btnTruncateDBLocationsTable);
btnTruncateDBLocationsTable.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Activity activity = getActivity();
int intCount = 0;
/*if (activity != null) {
//dummyTextView.setText("");
try {
locationDatabaseHandler.truncateLocationTable();
intCount = locationDatabaseHandler.getLocationCount();
} catch (Exception e){
//dummyTextView.append(e.toString());
}
//dummyTextView.append("Count:" + intCount + "\n\n");
Toast.makeText(activity, "toast_you_just_clicked_a_fragment btnTruncateDBLocationsTable button", Toast.LENGTH_LONG).show();
}*/
}
});
dummyTextView = (TextView) rootView .findViewById(R.id.section_label);
dummyTextView.append("\nLocation Stuff\n");
break;
//dummyTextView.append("Count:" + intCount + "\n\n");
I run into a circle where if I dummyTextView try to use the dummmyText w/in the onClick event, it says that i need to make it static (quick fix) with a complaining error of : cannot refer to a non-final variable dummy7Text inside an indder class defined in a different method.
I've added a variables to handle this inside the onCreate that get filled for (LayoutInflater and Viewgroup, and then reference them w/in the onclick (not shown), but when i go in and instansiate ... nothing happens with the textviews...
There is something i'm not quite getting here, and once i get by that hurdle, i'll have this by the balls, and will be able to make it do what i want.
I don't really want anything static or final here
Why? They will not negatively impact performance, nor are they a sign of poor coding practices.
I don't understand the following line
Every Fragment can be created with a Bundle containing any number of key-value pairs. DummySectionFragment.ARG_SECTION_NUMBER is a the key (a String), and position + 1 is the value. Thus this code is telling the new DummySectionFragment which section of content the Fragment should show.
This method is preferable to putting these arguments in a constructor because your custom constructor for a Fragment isn't guaranteed to be called. There are many ways for Android to generate Fragments, so this lowers the possibility of problems such as NullPointerExceptions.
the error is: cannot make a static reference to the non-static field DummySectionFragment.ARG_SECTION_NUMBER
As you seem to know, DummySectionFragment.ARG_SECTION_NUMBER is referring to a static field within the DummySectionFragment class called ARG_SECTION_NUMBER. By making this field non-static, you can no longer reference this constant value without a DummySectionFragment instance.
Another option (if you really don't want a static field) would be to hardcode the String. Thus your code would be:
args.putInt("section_number", position + 1);
However, a public static field is a much better coding practice and will prevent silly mistakes with typos in your Strings.
I run into a cirle where if i dummyTextView try to use the dummmyText w/in the onClick event, it says that i need to make it static (quick fix) with a complaining error of : cannot refer to a non-final variable dummy7Text inside an indder class defined in a different method.
Instead of using an anonymous inner class, I would let your Fragment implement OnClickListener.
For example:
public class MyFragment extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// ...
Button btnTruncateDBLocationsTable = (Button) rootView.findViewById(R.id.btnTruncateDBLocationsTable);
btnTruncateDBLocationsTable.setOnClickListener(this);
// ...
}
#Override
public void onClick(View v) {
// You can reference dummyTextView here without any problems
}
}
that means that ARG_SECTION_NUMBER should be declared as public static. Better if it declared as public static final

Categories

Resources