I have an action bar activity with 3 tabs.
I have a main activity, where I post an xml to a webservice and get back an xml in an AsyncTaskj. I'm initializing a static variable of the main activity in AsncTask. From main activity another activity is called, where Action Bar is initialized. Each action bar has a ListFragment, where I use the static variable. I have no issue accessing a Static variable from 2 List activities but in first ListFragment m not able to access the initialized static variable.
Edit 1
My Main Activity
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
GenerateXml gx=new GenerateXml();
String requestXml=gx.generateXml(tv1.getText().toString(),tv2.getText().toString(),tv3.getText().toString(),tv4.getText().toString());
myNewTask = new MyTask(requestXml);
myNewTask.execute();
Intent intent=new Intent(getApplicationContext(),TabActivity.class);
startActivity(intent);
}
});
In my AsyncTask doInBackground
MainActivity.responseXml=responseXML;
The Activity where tabs are created
public class TabActivity extends Activity {
MyTask myNewTask;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.setDisplayShowTitleEnabled(true);
/** Creating All Tab */
Tab tab = actionBar.newTab()
.setText("All")
.setTabListener(new CustomTabListener<AllMsgFragment>(this, "All", AllMsgFragment.class));
//.setIcon(R.drawable.android);
actionBar.addTab(tab);
/** Creating Success Tab */
tab = actionBar.newTab()
.setText("Success")
.setTabListener(new CustomTabListener<SuccessMsgFragment>(this, "Success", SuccessMsgFragment.class));
//.setIcon(R.drawable.apple);
actionBar.addTab(tab);
/** Creating Error Tab */
tab = actionBar.newTab()
.setText("Error")
.setTabListener(new CustomTabListener<ErrorMsgFragment>(this, "error", ErrorMsgFragment.class));
//.setIcon(R.drawable.apple);
actionBar.addTab(tab);
}
}
My first ListFragment:
public class AllMsgFragment extends ListFragment {
public static String response;
public ArrayList<HashMap<String, String>> msgDetails;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
response=MainActivity.responseXml;
XmlToArrayList xmlArray=new XmlToArrayList();
try {
msgDetails=xmlArray.arrayListXml(response);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(getActivity(), msgDetails,
R.layout.msg_preview,
new String[] { "ObSystem", "ObName", "Msgstate"}, new int[] {
R.id.bs, R.id.si, R.id.msgStatus});
setListAdapter(adapter);
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onStart() {
super.onStart();
Log.e("first","1");
/** Setting the multiselect choice mode for the listview */
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
}
Related
I am a newbie in android programming.I added three fragments in my main activity as follows.Each fragment contains a list view.The items in list view is added from json output.Now i need to call same json request from each fragments.Can i set listview items from my main activity ? and avoid 2 json requests ?
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MainActivity extends ActionBarActivity implements
android.support.v7.app.ActionBar.TabListener {
ViewPager viewPager;
// Using appcompat action bar
private android.support.v7.app.ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
FragmentManager fragmnetManager = getSupportFragmentManager();
viewPager.setAdapter(new MyAdapter(fragmnetManager));
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageSelected(int pos)
{
actionBar.setSelectedNavigationItem(pos);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2)
{
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
// Getting actionbar
actionBar = getSupportActionBar();
// Setting navigation mode to actionbar
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Now adding a new tab to action bar and setting title, icon and
// implementing listener
android.support.v7.app.ActionBar.Tab tab1 = actionBar.newTab();
tab1.setText("TAB1");
// tab1.setIcon(R.drawable.ic_launcher);
tab1.setTabListener(this);
android.support.v7.app.ActionBar.Tab tab2 = actionBar.newTab();
tab2.setText("TAB2");
tab2.setTabListener(this);
android.support.v7.app.ActionBar.Tab tab3 = actionBar.newTab();
tab3.setText("TAB3");
tab3.setTabListener(this);
// Now finally adding all tabs to actionbar
actionBar.addTab(tab1);
actionBar.addTab(tab2);
actionBar.addTab(tab3);
}
#Override
public void onTabReselected(android.support.v7.app.ActionBar.Tab arg0,
FragmentTransaction arg1)
{
}
#Override
public void onTabSelected(android.support.v7.app.ActionBar.Tab tab,
FragmentTransaction arg1)
{
// Setting current position of tab to view pager
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(android.support.v7.app.ActionBar.Tab arg0,
FragmentTransaction arg1) {
}
}
// My adapter i.e. custom adapter for displaying fragments over view pager
class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
// Getting fragments according to selected position
Fragment fragment = null;
if (i == 0) {
fragment = new FragmentA();
}
if (i == 1) {
fragment = new FragmentB();
}
if (i == 2) {
fragment = new FragmentC();
}
// and finally returning fragments
return fragment;
}
#Override
public int getCount() {
// Returning no. of counts of fragments
return 3;
}
}
You can also try this if you don't want to implement interface (because you are having only three fragment) - To avoid two json request on different fragment, just send one json request and after getting data in two different list, you can call a method in second fragment to set listview's data in second fragment from first fragment.
Let's say you got two list(firstList, secondList) of data from jsonResponse then set first arraylist in currentFragment and to set data in second fragment try like below method-
Define fragment's instances in Activity like -
FirstFragment firstFragment;
SecondFragment secondFragment;
initialize them where you add fragment like -
secondFragment = new SecondFragment();
in SecondFragment -
public void updateListView(ArrayList list){
secondArrayList.addAll(list);
secondAdapter = new Adapter(superContext, R.layout.single_item, secondArrayList);
listView.setAdapter(secondAdapter);
}
call this method from activity -
secondFragment.updateListView(secondList);
This solution is better if you have number of fragments small.
Yes you can. Create a interface in your mainActivity as follows
public interface Communicator{
void onDataLoaded(<Whatever data you want to send to fragment>)
}
now create an instance of this interface in your main activity
Communicator mCommunicator;
In your getItem method, for which fragment you want to send data to initialize the communicator as follows
mCommunicator=(Communicator)fragment;
Then in your main activity once your JSON is loaded just call mCommunicator.onDataLoaded();
Make sure your fragment implements this interface. Once you implement it you will get data there and you can update your listview.
I would like to access methods (or global variables) of a fragment created for an action bar but unfortunately I cannot find any ID for it and cannot access it. Does someone know how to do this?
trainingFragment.somemethode(aParameter) does not work.
NB: For information I didn't touched the Manifest File, I don't know if I should have. And I'm NOT using Android.Support.V4.App or Android.Support.V7.AppCompat, I'm simply using Android.App. And the target Framework is Android 4.4 (Kit Kat).
Here is the code:
Main Activity:
public class MainActivity : Activity
{
static readonly string Tag = "ActionBarTabsSupport";
Fragment[] _fragments;
// Layout Views
public TextView title;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.mainactivity);
ActionBar.NavigationMode = ActionBarNavigationMode.Tabs;
SetContentView(Resource.Layout.mainactivity);
Fragment trainingFragment = new TrainingFragment ();
Fragment bluetoothChatFragment = new TestFragment();
_fragments = new Fragment[]
{
trainingFragment,
bluetoothChatFragment
};
AddTabToActionBar(Resource.String.training_label, Resource.Drawable.ic_action_speakers);
AddTabToActionBar(Resource.String.btchat_label, Resource.Drawable.ic_action_sessions);}
void AddTabToActionBar(int labelResourceId, int iconResourceId)
{
ActionBar.Tab tab = ActionBar.NewTab()
.SetText(labelResourceId)
.SetIcon(iconResourceId);
tab.TabSelected += TabOnTabSelected;
ActionBar.AddTab(tab);
}
void TabOnTabSelected(object sender, ActionBar.TabEventArgs tabEventArgs)
{
ActionBar.Tab tab = (ActionBar.Tab)sender;
Log.Debug(Tag, "The tab {0} has been selected.", tab.Text);
Fragment frag = _fragments[tab.Position];
tabEventArgs.FragmentTransaction.Replace(Resource.Id.frameLayout1, frag);
}
One of the fragments:
public class TrainingFragment : Fragment
{
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate(Resource.Layout.training_layout, null);
return view;
}
public void somemethod(int aParameter)
{
//Do something
}
}
Thanks in advance
try that
void TabOnTabSelected(object sender, ActionBar.TabEventArgs tabEventArgs)
{
ActionBar.Tab tab = (ActionBar.Tab)sender;
Log.Debug(Tag, "The tab {0} has been selected.", tab.Text);
Fragment frag = _fragments[tab.Position];
if(frag instanceof TrainingFragment ){
((TrainingFragment)frag).somemethod(0);
}
tabEventArgs.FragmentTransaction.Replace(Resource.Id.frameLayout1, frag);
}
I am building an app that uses three tab fragments and I want to create a function in one place that I can call from all three tabs. I would assume that I need to create the new function in the activity that contains the tabs, but I'm not sure how to declare it or how to call it from one of the tab fragments.
This is how i create my tabs in the main activity:
public class MainActivity extends FragmentActivity implements TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Search", "History", "Saved" };
#Override
protected void onCreate(Bundle savedInstanceState) {
//Initialise the Database connection
DBAdapter.init(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setup tab bar
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
//Add the tabs to the action bar
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name).setTabListener(this));
}
//Tab Swipe change listener
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
}
Create the function you need to call in the parent Activity and it must be a public method
and you can call that function like this:
((YourActivityClassName)getActivity()).yourPublicMethod();
I am trying to add tabs to the action bar in my android application. Using FragmentPagerAdapter seems a nice idea but when I try to set the adapter to the ViewPager object, it returns a nullpointerexception. Cannot figure out th problem, please help... Here is the partial code segment:
public class Aps_MainActivity extends FragmentActivity implements ActionBar.TabListener {
ViewPager vPager;
PackagePagerAdapter pPAdapter;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aps__main);
setTabs();
}
void setTabs() {
// Creating the adapter that will return a fragment for each sections
// of the app.
pPAdapter = new PackagePagerAdapter(getSupportFragmentManager());
actionBar = getActionBar();
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
vPager = (ViewPager) findViewById(R.id.pager);
try{
vPager.setAdapter(pPAdapter);
}
catch(Exception e){
Log.e("ADAPTER", e.toString());
}
vPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < pPAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(pPAdapter.getPageTitle(i))
.setTabListener(this));
}
}
I'm wondering how can I work with a listfragment, and at the same time, using an static linearlayout with 4 filter buttons at the top of the list. Here is the problem:
First of all, I use an Action Bar + Tab Navigation from ActionBarSherlock :
QuestList extends FragmentMapActivity implements ActionBar.TabListener
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getTabs();
}
private void getTabs() {
getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab1 = getSupportActionBar().newTab();
tab1.setText("Geo");
tab1.setTabListener(this);
getSupportActionBar().addTab(tab1);
ActionBar.Tab tab2 = getSupportActionBar().newTab();
tab2.setText("No Geo");
tab2.setTabListener(this);
getSupportActionBar().addTab(tab2);
}
...
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (tab.getText().toString().compareTo("Geo") == 0) {
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, Map.getInstance()).commit();
}
else {
getSupportFragmentManager().beginTransaction().replace(android.R.id.content, List.newInstance(0)).commit();
}
}
I got some problems with the MapView, but I finally fixed all of them. Now the problem is that I want something like this:
Static LinearLayout + ListFragment
List extends ListFragment
...
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initializations();
getQuests();
if (gigHash.isEmpty()) {
TextView eList = new TextView(getActivity());
eList.setText(R.string.no_loc_gig_no_items);
eList.setWidth(Gravity.CENTER);
}
else {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
mAdapter = new NoLocGigAdapter(getActivity(),R.layout.gig_noloc_row_land,gigList);
}
else {
mAdapter = new NoLocGigAdapter(getActivity(),R.layout.gig_noloc_row,gigList);
}
setListAdapter(mAdapter);
}
}
...
So I'm using my own adapter and I get all my items from a service.
The problem is, doing the transaction, I can only use a fragment, and I have to show the items dinamically with my own ArrayAdapter, so I don't know how to include a part of static code into that view...
Any suggestion? I think that handle with fragments it's a little weird!
PS: At first, I thought that I could call a fragment, and this, calling a static xml within the linearlayout and a ListFragment inside, but I think I can't do this, right?