Having trouble setting dynamic content within Fragments - android

In my MainActivity I have a list, and when an item is clicked, I go into my ScreenSlideActivity. This activity will produce a Fragment from another class I have called ScreenSlidePageFragment, and will produce a handful of Fragments for me when I swipe. I need the content in these Fragments to be unique depending on whichever item in the list I selected. Unfortunately I haven't been successful at this.
I've tried creating a set_all_data(string_data){} function inside the ScreenSlidePageFragment and the calling it/updating the textView before I create the Fragment, but I think I'm either getting a race condition with the new text, or I'm just doing it wrong and don't understand Fragments well enough.
ScreenSlideActivity
package com.example.dgzl.corvegas;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
/**
* Demonstrates a "screen-slide" animation using a {#link ViewPager}. Because {#link ViewPager}
* automatically plays such an animation when calling {#link ViewPager#setCurrentItem(int)}, there
* isn't any animation-specific code in this sample.
*
* <p>This sample shows a "next" button that advances the user to the next step in a wizard,
* animating the current screen out (to the left) and the next screen in (from the right). The
* reverse animation is played when the user presses the "previous" button.</p>
*
* #see ScreenSlidePageFragment
*/
public class ScreenSlideActivity extends android.support.v4.app.FragmentActivity {
/* The number of pages (wizard steps) to show in this demo.*/
private static final int NUM_PAGES = 3;
/* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.*/
private ViewPager mPager;
/* The pager adapter, which provides the pages to the view pager widget.*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
final String biz_data[] = in.getStringArrayExtra("biz_data");
set_fragment_data(biz_data);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
mPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
invalidateOptionsMenu();
}
});
}
public void onFragClick (View view){
Toast.makeText(ScreenSlideActivity.this, "button", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_screen_slide, menu);
// enable 'prev' and 'next' when not on first node
menu.findItem(R.id.action_prev).setEnabled(mPager.getCurrentItem() > 0);
menu.findItem(R.id.action_next).setEnabled(mPager.getCurrentItem() < (NUM_PAGES-1));
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case 16908332:
// Navigate "up" the demo structure to the launchpad activity.
// See http://developer.android.com/design/patterns/navigation.html for more.
finish();
return true;
case R.id.action_prev:
// Go to the previous step in the wizard. If there is no previous step,
// setCurrentItem will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
return true;
case R.id.action_next:
// Advance to the next step in the wizard. If there is no next step, setCurrentItem
// will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A simple pager adapter that represents 5 {#link ScreenSlidePageFragment} objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
String test_data = "Soem data";
ScreenSlidePageFragment newFrag = new ScreenSlidePageFragment();
newFrag.set_all_data(test_data);
Fragment newFragment = newFrag.create(position);
return newFragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
public void set_fragment_data(String biz_data[]){
// title as business name
setTitle(biz_data[1]);
}
}
ScreenSlidePageFragment
package com.example.dgzl.corvegas;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
/**
* A fragment representing a single step in a wizard. The fragment shows a dummy title indicating
* the page number, along with some dummy text.
*
* <p>This class is used by the {#link } and {#link
* ScreenSlideActivity} samples.</p>
*/
public class ScreenSlidePageFragment extends android.support.v4.app.Fragment {
/**
* The argument key for the page number this fragment represents.
*/
public static final String ARG_PAGE = "page";
/**
* The fragment's page number, which is set to the argument value for {#link #ARG_PAGE}.
*/
private int mPageNumber;
public String[] todays_data, biz_data, special_data;
public String all_data = "hardcoded and not good";
/**
* Factory method for this fragment class. Constructs a new fragment for the given page number.
*/
public static ScreenSlidePageFragment create(int pageNumber) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
Log.d("OnCreateView: ", "2");
return fragment;
}
public ScreenSlidePageFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup rootView;
Log.d("OnCreateView: ", "1");
TextView tv;
switch(getPageNumber()){
case 0:
rootView = (ViewGroup) inflater.inflate(R.layout.fragment_today, container, false);
tv = (TextView)rootView.findViewById(R.id.today_frag_tv);
tv.setText(R.string.today_frag);
break;
case 1:
rootView = (ViewGroup) inflater.inflate(R.layout.fragment_business, container, false);
tv = (TextView)rootView.findViewById(R.id.biz_frag_tv);
tv.setText(all_data);
break;
case 2:
rootView = (ViewGroup) inflater.inflate(R.layout.fragment_specials, container, false);
tv = (TextView)rootView.findViewById(R.id.specials_frag_tv);
tv.setText(R.string.special_frag);
break;
default:
rootView = (ViewGroup) inflater.inflate(R.layout.fragment_today, container, false);
tv = (TextView)rootView.findViewById(R.id.today_frag_tv);
tv.setText(R.string.today_frag);
}
// Set the title view to show the page number.
// ((TextView) rootView.findViewById(android.R.id.text1)).setText(getString(R.string.title_template_step, mPageNumber + 1));
return rootView;
}
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber() {
return mPageNumber;
}
public void set_data(String[] todays_data, String[] biz_data, String[] special_data) {
this.todays_data = todays_data;
this.biz_data = biz_data;
this.special_data = special_data;
}
public void set_all_data(String all_data) {
this.all_data = all_data;
}
public void get_data() {
}
}

The problem is in getItem() method. You are creating a new ScreenSlidePageFragment, and after that, you call create() method that creates a new ScreenSlidePageFragment again. You need to call ScreenSlidePageFragment.create(position) in a static way.
#Override
public Fragment getItem(int position) {
String test_data = "Soem data";
ScreenSlidePageFragment newFrag = ScreenSlidePageFragment.create(position);
newFrag.set_all_data(test_data);
return newFragment;
}

Related

Unable to distinguish between two fragments with chart click events

I have implemented two pie charts in two different fragments. Whenever I click on a pie chart it will call the second fragments click events on both fragments.
Here is my MainActivity.java code.
package longitude.com.anychart;
import android.content.res.Resources;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentStatePagerAdapter;
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.SparseArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.dataentry.ValueDataEntry;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
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}.
*/
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private AccountDashboardAdapter mSectionsPagerAdapter;
#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.
mViewPager = (ViewPager) findViewById(R.id.container);
//mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
ArrayList<DataEntry> dateData = new ArrayList<>();
dateData.add(new ValueDataEntry("Apples", 123456));
dateData.add(new ValueDataEntry("Pears", 852465));
dateData.add(new ValueDataEntry("Bananas", 753159));
dateData.add(new ValueDataEntry("Grapes", 963215));
dateData.add(new ValueDataEntry("Oranges", 415263));
ArrayList<DataEntry> collectorData = new ArrayList<>();
collectorData.add(new ValueDataEntry("Applessssss", 6371664));
collectorData.add(new ValueDataEntry("Pearsssss", 789622));
collectorData.add(new ValueDataEntry("Bananasssss", 7216301));
collectorData.add(new ValueDataEntry("Grapesssss", 1486621));
collectorData.add(new ValueDataEntry("Orangesssss", 1200000));
HashMap<String, ArrayList<DataEntry>> childData=new LinkedHashMap<>();
childData.put("Apples",collectorData);
childData.put("Pears",collectorData);
childData.put("Bananas",collectorData);
childData.put("Grapes",collectorData);
childData.put("Oranges",collectorData);
childData.put("Applessssss",dateData);
childData.put("Pearsssss",dateData);
childData.put("Bananasssss",dateData);
childData.put("Grapesssss",dateData);
childData.put("Orangesssss",dateData);
mSectionsPagerAdapter = new AccountDashboardAdapter(getResources(), getSupportFragmentManager(), dateData, collectorData, childData);
mViewPager.setOffscreenPageLimit(5);
// Set up the ViewPager with the sections adapter.
mViewPager.setAdapter(mSectionsPagerAdapter);
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 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 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_main, 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;
}
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class AccountDashboardAdapter extends FragmentStatePagerAdapter {
private final List<DataEntry> collectorData;
private final HashMap<String, ArrayList<DataEntry>> childData;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
List<DataEntry> dateData;
/**
* Create pager adapter
*
* #param resources
* #param fm
* #param data
* #param childData
*/
public AccountDashboardAdapter(final Resources resources, FragmentManager fm, List<DataEntry> data, List<DataEntry> collectorData, HashMap<String, ArrayList<DataEntry>> childData) {
super(fm);
this.dateData = data;
this.collectorData = collectorData;
this.childData = childData;
}
#Override
public Fragment getItem(int position) {
final Fragment result;
switch (position) {
case 0:
// First Fragment of First Tab
//result = new DatewiseAccountDashboardFragment();
result = new fragment1();
Bundle bundle = new Bundle();
bundle.putSerializable("data", (Serializable) dateData);
bundle.putSerializable("childData", childData);
result.setArguments(bundle);
break;
case 1:
// First Fragment of Second Tab
//result = new CollectorwiseAccountDashboardFragment();
result = new fragment2();
Bundle bundle1 = new Bundle();
bundle1.putSerializable("data", (Serializable) collectorData);
bundle1.putSerializable("childData", childData);
result.setArguments(bundle1);
break;
case 2:
// First Fragment of Second Tab
//result = new CollectorwiseAccountDashboardFragment();
result = new fragment1();
Bundle bundle2 = new Bundle();
bundle2.putSerializable("data", (Serializable) dateData);
bundle2.putSerializable("childData", childData);
result.setArguments(bundle2);
break;
default:
result = null;
break;
}
return result;
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(final int position) {
switch (position) {
case 0:
return "DATEWISE";
case 1:
return "COLLECTORWISE";
default:
return null;
}
}
/**
* On each Fragment instantiation we are saving the reference of that Fragment in a Map
* It will help us to retrieve the Fragment by position
*
* #param container
* #param position
* #return
*/
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
/**
* Remove the saved reference from our Map on the Fragment destroy
*
* #param container
* #param position
* #param object
*/
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
/**
* Get the Fragment by position
*
* #param position tab position of the fragment
* #return
*/
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}
My First Fragment1.java code
package longitude.com.anychart;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.anychart.APIlib;
import com.anychart.AnyChart;
import com.anychart.AnyChartView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.listener.Event;
import com.anychart.chart.common.listener.ListenersInterface;
import com.anychart.charts.Pie;
import com.anychart.enums.Align;
import com.anychart.enums.LegendLayout;
import java.util.List;
public class Fragment1 extends Fragment {
private AnyChartView anyChartView;
private List<DataEntry> data;
private Pie pie;
public Fragment1() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
data = (List<DataEntry>) getArguments().getSerializable("data");
//childData = (HashMap<String, ArrayList<DataEntry>>) getArguments().getSerializable("childData");
getArguments().remove("data");
getArguments().remove("childData");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
anyChartView = rootView.findViewById(R.id.any_chart_view1);
anyChartView.setProgressBar(rootView.findViewById(R.id.progress_bar1));
showChart(anyChartView, data);
return rootView;
}
private void showChart(AnyChartView anyChartView, List<DataEntry> data) {
APIlib.getInstance().setActiveAnyChartView(anyChartView);
pie = AnyChart.pie();
pie.data(data);
pie.title("1st Anychart Title");
//pie.labels().position("outside");
pie.innerRadius(50);
pie.legend().title().enabled(true);
pie.legend().title(false);
pie.legend()
.position("center-bottom")
.itemsLayout(LegendLayout.HORIZONTAL_EXPANDABLE)
.align(Align.CENTER);
//pie.fill("aquastyle");
pie.labels().format("{%x}\\n{%value}");
anyChartView.setChart(pie);
pie.tooltip(false);
pie.setOnClickListener(new ListenersInterface.OnClickListener(new String[]{"x", "value"}) {
#Override
public void onClick(Event event) {
Toast.makeText(getActivity(), "Fragment1==>" + event.getData().get("x") + ":" + event.getData().get("value"), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
My Second Fragment2.java code
package longitude.com.anychart;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
import com.anychart.APIlib;
import com.anychart.AnyChart;
import com.anychart.AnyChartView;
import com.anychart.chart.common.dataentry.DataEntry;
import com.anychart.chart.common.listener.Event;
import com.anychart.chart.common.listener.ListenersInterface;
import com.anychart.charts.Pie;
import com.anychart.enums.Align;
import com.anychart.enums.LegendLayout;
import java.util.List;
public class Fragment2 extends Fragment {
private AnyChartView anyChartView;
private List<DataEntry> data;
private Pie pie;
public Fragment2() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(false);
data = (List<DataEntry>) getArguments().getSerializable("data");
//childData = (HashMap<String, ArrayList<DataEntry>>) getArguments().getSerializable("childData");
getArguments().remove("data");
getArguments().remove("childData");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment1, container, false);
anyChartView = rootView.findViewById(R.id.any_chart_view1);
anyChartView.setProgressBar(rootView.findViewById(R.id.progress_bar1));
showChart(anyChartView, data);
return rootView;
}
private void showChart(AnyChartView anyChartView, List<DataEntry> data) {
APIlib.getInstance().setActiveAnyChartView(anyChartView);
pie = AnyChart.pie();
pie.data(data);
pie.title("2nd Anychart Title");
//pie.labels().position("outside");
pie.innerRadius(50);
pie.legend().title().enabled(true);
pie.legend().title(false);
pie.legend()
.position("center-bottom")
.itemsLayout(LegendLayout.HORIZONTAL_EXPANDABLE)
.align(Align.CENTER);
//pie.fill("aquastyle");
pie.labels().format("{%x}\\n{%value}");
anyChartView.setChart(pie);
pie.tooltip(false);
pie.setOnClickListener(new ListenersInterface.OnClickListener(new String[]{"x", "value"}) {
#Override
public void onClick(Event event) {
Toast.makeText(getActivity(), "Fragment2==>"+event.getData().get("x") + ":" + event.getData().get("value"), Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#Override
public void onDetach() {
super.onDetach();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
}
fragment1.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btn_back"
android:enabled="false"
android:layout_width="60dp"
android:layout_height="40dp"
android:text="BACK" />
<com.anychart.AnyChartView
android:id="#+id/any_chart_view1"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progress_bar1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
Here is my code link: https://drive.google.com/file/d/1YnIL1fE52W_Gy4yuc2rYb4fh4Y1hGNuG/view?usp=sharing
Unfortunately, now we have no idea what exactly happens with event dispatching in Fragments. But I would like to bring to your attention that there's a possible workaround.
Click on a chart returns correct point name and value. Only the fragment name is wrong. The name is hardcoded in the click event handler.
So if the fragment name is not required in output, you can just drop it. If the name is required you can apply a specific ID to the Fragment and then get that ID from active fragment view. This should solve the issue as a temporary workaround.

Using ViewPager for Screen Slides Incompatible Types

I downloaded the sample Screen Swipe today and wanted to test it in my project but had to stop because there are some issues with incompatible types of return values...
https://developer.android.com/training/animation/screen-slide.html
Thats where i downloaded it.
ScreenSlideActivity:
package ur.mi.android.wgplus05.FotoApp;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
import android.view.MenuItem;
import ur.mi.android.wgplus05.R;
/**
* Demonstrates a "screen-slide" animation using a {#link ViewPager}. Because {#link ViewPager}
* automatically plays such an animation when calling {#link
ViewPager#setCurrentItem(int)}, there
* isn't any animation-specific code in this sample.
*
* <p>This sample shows a "next" button that advances the user to the
next step in a wizard,
* animating the current screen out (to the left) and the next screen in
(from the right). The
* reverse animation is played when the user presses the "previous"
button.</p>
*
* #see ScreenSlidePageFragment
*/
public class ScreenSlideActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 5;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager());
**//ScreenSlidePagerAdapter
(android.support.v4.app.FragmentManager)
in ScreenSlidePagerAdapter cannot be applied
to android.app.FragmentManager)**
mPager.setAdapter(mPagerAdapter);
mPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// When changing pages, reset the action bar actions since they are dependent
// on which page is currently active. An alternative approach is to have each
// fragment expose actions itself (rather than the activity exposing actions),
// but for simplicity, the activity provides the actions in this sample.
invalidateOptionsMenu();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_screen_slide, menu);
menu.findItem(R.id.action_previous).setEnabled(mPager.getCurrentItem() > 0);
// Add either a "next" or "finish" button to the action bar, depending on which page
// is currently selected.
MenuItem item = menu.add(Menu.NONE, R.id.action_next, Menu.NONE,
(mPager.getCurrentItem() == mPagerAdapter.getCount() - 1)
? R.string.action_finish
: R.string.action_next);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// Navigate "up" the demo structure to the launchpad activity.
// See http://developer.android.com/design/patterns/navigation.html for more.
NavUtils.navigateUpTo(this, new Intent(this, FotoWand.class));
return true;
case R.id.action_previous:
// Go to the previous step in the wizard. If there is no previous step,
// setCurrentItem will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
return true;
case R.id.action_next:
// Advance to the next step in the wizard. If there is no next step, setCurrentItem
// will do nothing.
mPager.setCurrentItem(mPager.getCurrentItem() + 1);
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A simple pager adapter that represents 5 {#link CustomScreenSlidePageFragment} objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ScreenSlidePageFragment.create(position);
**// Incompatible types.
Required:
android.support.v4.app.Fragment
Found: ur.mi.android.wgplus05.FotoApp.ScreenSlidePageFragment**
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
ScreenSliderPagerActivity:
package ur.mi.android.wgplus05.FotoApp;
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.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import ur.mi.android.wgplus05.R;
public class ScreenSlidePagerActivity extends FragmentActivity {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 5;
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_screen_slide);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) findViewById(R.id.pager);
mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
}
#Override
public void onBackPressed() {
if (mPager.getCurrentItem() == 0) {
// If the user is currently looking at the first step, allow the system to handle the
// Back button. This calls finish() on this activity and pops the back stack.
super.onBackPressed();
} else {
// Otherwise, select the previous step.
mPager.setCurrentItem(mPager.getCurrentItem() - 1);
}
}
/**
* A simple pager adapter that represents 5 ScreenSlidePageFragment objects, in
* sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return new ScreenSlidePageFragment();
** // Incompatible types.
Required:
android.support.v4.app.Fragment
Found:ur.mi.android.wgplus05.FotoApp.ScreenSlidePageFragment**
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
I marked the errors i get with **
I'm completely new to this and haven't found out how this all works together. Hope someone can help me with that! Thanks in advance.
package ur.mi.android.wgplus05.FotoApp;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import ur.mi.android.wgplus05.R;
public class ScreenSlidePageFragment extends Fragment {
/**
* The argument key for the page number this fragment represents.
*/
public static final String ARG_PAGE = "page";
/**
* The fragment's page number, which is set to the argument value for {#link #ARG_PAGE}.
*/
private int mPageNumber;
/**
* Factory method for this fragment class. Constructs a new fragment for the given page number.
*/
public static ScreenSlidePageFragment create(int pageNumber) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
Bundle args = new Bundle();
args.putInt(ARG_PAGE, pageNumber);
fragment.setArguments(args);
return fragment;
}
public ScreenSlidePageFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPageNumber = getArguments().getInt(ARG_PAGE);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout containing a title and body text.
ViewGroup rootView = (ViewGroup) inflater
.inflate(R.layout.fragment_screen_slide_page, container, false);
// Set the title view to show the page number.
((TextView) rootView.findViewById(android.R.id.text1)).setText(
getString(R.string.title_template_step, mPageNumber + 1));
return rootView;
}
/**
* Returns the page number represented by this fragment object.
*/
public int getPageNumber() {
return mPageNumber;
}
}
you are extending android.app.Fragment for ScreenSlidePageFragment instead of android.support.v4.app.Fragment
define your ScreenSlidePageFragment like follows
public class ScreenSlidePageFragment extends android.support.v4.app.Fragment
This will solve your problem

Send data from fragment to fragment using Tab Layout with Swipeable Views in Android

I created a Tab Layout with Swipeable Views.
I'm trying to pass a string from fragment
to Fragment Thank you in Advance
Details_customer.java
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.support.design.widget.TabLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
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.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.appindexing.Action;
import com.google.android.gms.appindexing.AppIndex;
import com.google.android.gms.appindexing.Thing;
import com.google.android.gms.common.api.GoogleApiClient;
public class Details_customer extends AppCompatActivity implements Cust_Details_basic.FragmentDataListener {
SharedPreferences login_pref, IP;
private ProgressDialog pDialog;//For Loading activity..
Bundle dataBundle;
/**
* The {#link 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 FragmentStatePagerAdapter}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details_customer);
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);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}
#Override
public void onFragmentDataUpdated(Bundle dataBundle)
{
this.dataBundle=dataBundle;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
//getMenuInflater().inflate(R.menu.menu_details_customer, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
login_pref = getSharedPreferences("Login Pref", MODE_PRIVATE);
SharedPreferences.Editor editor = login_pref.edit();
editor.putString("username", null);
Intent intent = new Intent(this, MainActivity.class);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
Toast.makeText(getApplicationContext(), "Logout", Toast.LENGTH_SHORT).show();
/*editor.clear();*/
editor.commit();
finish();
break;
}
return super.onOptionsItemSelected(item);
}
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
public Action getIndexApiAction() {
Thing object = new Thing.Builder()
.setName("Details_customer Page") // TODO: Define a title for the content shown.
// TODO: Make sure this auto-generated URL is correct.
.setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]"))
.build();
return new Action.Builder(Action.TYPE_VIEW)
.setObject(object)
.setActionStatus(Action.STATUS_TYPE_COMPLETED)
.build();
}
#Override
public void onStart() {
super.onStart();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
client.connect();
AppIndex.AppIndexApi.start(client, getIndexApiAction());
}
#Override
public void onStop() {
super.onStop();
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
AppIndex.AppIndexApi.end(client, getIndexApiAction());
client.disconnect();
}
//deleted
/**
* 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:
Cust_Details_basic cust_basic = new Cust_Details_basic();
cust_basic.setArguments(dataBundle);
return cust_basic;
case 1:
Cust_Details_address address = new Cust_Details_address();
address.setArguments(dataBundle);
return address;
/* case 2:
Cust_Details_last details_last = new Cust_Details_last();
return details_last;*/
}
return null;
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
/***
* new addition
***/
public void showFragment(String val) {
System.out.println(val);
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Basic Info";
case 1:
return "Address";
/* case 2:
return "Address";*/
}
return null;
}
}}
Cust_Details_basic.java Here is my Edittext i want to send the value to next fragment
public class Cust_Details_basic extends Fragment {
EditText finame;
private ProgressDialog pDialog;//For Loading activity..
public interface FragmentDataListener{
void onFragmentDataUpdated(Bundle dataBundle);
}
private FragmentDataListener mFragmentDataListener;
#Override
public void onAttach( Context context )
{
super.onAttach( context );
mFragmentDataListener=(FragmentDataListener)getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details_customer_1, container, false);
finame = (EditText)view.findViewById(R.id.fname);
/**********************************************/
Bundle bundle = new Bundle();
bundle.putString("fname",finame.getText().toString());
mFragmentDataListener.onFragmentDataUpdated(bundle);
/*********************************************/
return view;
}}
Here is Cust_Details_address.java here i want Edittext value
public class Cust_Details_address extends Fragment implements View.OnClickListener{
Button btnsubmit;
String fname,firstname;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details_customer_2, container, false);
Bundle bundle = this.getArguments();
if (bundle != null) {
firstname = bundle.getString("fname",fname);
Toast.makeText(getActivity().getApplicationContext(),"fname:"+firstname,Toast.LENGTH_SHORT).show();
Log.d("First Name:","=======>"+firstname);
}
else{
Toast.makeText(getActivity().getApplicationContext(),"Am Empty:",Toast.LENGTH_SHORT).show();
}
btnsubmit = (Button)view.findViewById(R.id.btnsubmit);
btnsubmit.setOnClickListener(this);
return view;
}}
In Cust_Details_address.java I Override the method like this
#Override
public void onStart(){
super.onStart();
btnsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String firstname = ((EditText)getActivity().findViewById(R.id.fname)).getText().toString();
Toast.makeText(getActivity().getApplicationContext(),"Hi "+firstname ,Toast.LENGTH_SHORT).show();
} });
I got the result which i have accepted. Thank you so much 'Talha' for your needful help.
CallBacks(interface) and Bundles are recommended way but this is a quick solution:
YourActivity:
public void randomMethod(String val){
System.out.println(val);
}
Fragment1:
onClick(){
((YourActivity) getActivity()).randomMethod(yourString1);
}
Fragment2:
onClick(){
((YourActivity) getActivity()).randomMethod(yourString2);
}
You can call that method from any fragment of an activity and use the updated value.
In your activity define interface, bundle object, then call interface method of Activity instance with data from your fragment:
In Details_customer activity you do this,
public class Details_customer extends AppCompatActivity
implements Cust_Details_basic.FragmentDataListener {
SharedPreferences login_pref,IP;
private ProgressDialog pDialog;//For Loading activity..
Bundle dataBundle;
..... other code
// override method of interface
#override void onFragmentDataUpdated(Bundle dataBundle)
{
this.dataBundle=dataBundle;
}
...... other code
// in SectionsPagerAdapter adapter
#Override public Fragment getItem(int position) {
switch (position) {
case 0:
Cust_Details_basic cust_basic = new Cust_Details_basic();
cust_basic.setArguments(dataBundle); // remember to update
//bundle object as per requirement
return cust_basic;
case 1:
Cust_Details_address address = new Cust_Details_address();
address.setArguments(dataBundle);
return address;
/* case 2:
Cust_Details_last details_last = new Cust_Details_last();
return details_last;*/
}
return null;
}
In your Cus_Details_basic Fragment, declare interface:
public class Cust_Details_basic extends Fragment {
public interface FragmentDataListener{
void onFragmentDataUpdated(Bundle dataBundle);
}
private FragmentDataListener mFragmentDataListener;
// create fragment object and initialize it in onAttach()
#Override public void onAttach( Context context )
{
super.onAttach( context );
mFragmentDataListener=(FragmentDataListener)getActivity();
}
// then update your onCreate as:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.details_customer_1, container, false);
Fragment fragment = new Fragment();
Bundle bundle = new Bundle();
bundle.putString("fname",fname);
//fragment.setArguments(bundle);
mFragmentDataListener.onFragmentDataUpdated(bundle);
// this will update dataBundle object in your activity
return view;
}
This will call onFragmentDataUpdated() of your Details_customer class, which will update its dataBundle object, now whenever Viewpager changes, you should be able to setArguments() with this Bundle object, and eventually getArguments() in onCreate of that fragment will be able to retrieve data.
Useful links:
Communicating between Fragments.
How To Communicate Between Fragments and Activities in Android.
Since all the fragment are in view pager that means they share the same activity.So just put the value inside the intent and get it in any fragment of that view pager, no need to pass the data separately in bundle.
In your Cust_Details_basic Fragment (Save it like this)
getActivity().getIntent().putExtra("name",fname);
In Cust_Details_address Fragment (Get it like this )
String fname = getActivity().getIntent().getStringExtra("name");

Open new activity using intent on FragmentPagerAdapter

i want open new activity (List Activity) List.java under Tile Strip
how to use intent on the onCreateView
OR
How To add List On the onCreateView
main.java is Sample for Swipe View and Tile Strip on the Eclipse
Main.java :
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.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Main extends FragmentActivity {
/**
* 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;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 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);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* 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 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase();
case 1:
return getString(R.string.title_section2).toUpperCase();
case 2:
return getString(R.string.title_section3).toUpperCase();
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Create a new Intent and open New Activity
return ;
}
}
}
List.Java :
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class List extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
final String[] products = getResources().getStringArray(R.array.products);
// Binding Array to ListAdapter
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, R.id.label, products));
}
}
Your class List should extends ListFragment instead of ListActivity, then in your getItem from SectionsPagerAdapter, if position is 0 returns an istance of the class List else return an istance of DummyFragment
#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 = null;
if (position == 0) {
fragment = new List();
} else {
fragment = new DummySectionFragment();
Bundle args = new Bundle();
args.putInt(DummySectionFragment.ARG_SECTION_NUMBER, position + 1);
fragment.setArguments(args);
}
return fragment;
}
your class List has to extends ListFragment
public class List extends ListFragment

Add button to a specific fragment in ViewPager

I found the ViewPager in the android SDK and was messing around with it. Basically my final task is to create a youtube, facebook, and twitter feed all in one app, using the ViewPager and Fragments to scroll between the 3 categories. I'm having a bit of a hard time understanding house these work, more specifically, how to I add an element (Button) to a specific Fragment? Here's my code so far:
package com.ito.mindtrekkers;
import java.util.ArrayList;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
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.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
import android.widget.Toast;
#SuppressLint("ShowToast")
//Brady Mahar
public class Main extends FragmentActivity {
/**
* 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;
ArrayList<String> tweetList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
// 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);
mViewPager.setCurrentItem(1); //sets initial page to "Facebook"
new DownloadFilesTask().execute("weather" , null, null);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/**
* 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 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.title_youtube);
case 1:
return getString(R.string.title_facebook);
case 2:
return getString(R.string.title_twitter);
}
return null;
}
}
/**
* A dummy fragment representing a section of the app, but that simply
* displays dummy text.
*/
public static class DummySectionFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
public static final String ARG_SECTION_NUMBER = "section_number";
public DummySectionFragment() {
}
#SuppressLint("ShowToast")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Create a new TextView and set its text to the fragment's section
// number argument value.
TextView textView = new TextView(getActivity());
textView.setGravity(Gravity.CENTER);
textView.setText(Integer.toString(getArguments().getInt(ARG_SECTION_NUMBER)));
return textView;
}
}
/**
* Class for handling NetworkOnMainThread
* Sends the command Asynchronously
* #author austinn
*
*/
private class DownloadFilesTask extends AsyncTask<String, Void, String> {
protected String doInBackground(String... command) {
Twitter twitter = new TwitterFactory().getInstance();
Query query = new Query("from:MindTrekkers");
query.setRpp(100);
try {
QueryResult result = twitter.search(query);
for(twitter4j.Tweet tweet : result.getTweets()) {
//Toast.makeText(getApplicationContext(), tweet.getText(), Toast.LENGTH_SHORT);
Log.v("Tweet", tweet.getText());
tweetList.add(tweet.getText());
}
} catch (TwitterException e) {
//Toast.makeText(getApplicationContext(), e + "", Toast.LENGTH_SHORT);
Log.v("Error", e+"");
}
return null;
}
protected void onProgressUpdate(Void... progress) {}
protected void onPostExecute(String result) {}
}
}
Implement your 3 Fragment categories (youtube, facebook, and twitter) in separate Fragment classes with a Singleton instance getter. Here's an Facebook Fragment example (note the onCreateView() inflates a fragment_facebook layout):
public class FaceBookFragment extends Fragment {
private static FaceBookFragment instance = null;
public static FaceBookFragment newInstance() {
if(instance == null) {
instance = new FaceBookFragment();
Bundle args = new Bundle();
instance.setArguments(args);
return instance;
}
return instance;
}
public FaceBookFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_facebook, container,
false);
...
return rootView;
}
}
Then in your FragmentPagerAdapter (located in the MainActivity of your code above), have the getItem() return the Fragment instance:
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment frag = null;
switch (position) {
case 0:
frag = FaceBookFragment.newInstance();
break;
case 1:
frag = TwitterFragment.newInstance();
break;
case 2:
frag = YouTubeFragment.newInstance();
break;
}
return frag;
}
}
BONUS: Also, I know your code was experimental, but your tweetlist won't be accessible from any of your Fragments.
A Fragment is a new class object and can't access anything in the MainActivity directly unless you pass a reference to an object (the tweetlist) during construction (limiting), or get a 'final' on an object/variable if the Fragment code is under MainActivity (the list will never change from the Fragment's perspective). Maybe I didn't articulate this statement as well as other might, but tweetlist will not be accessible from your Fragment as it is.
There's a couple of solutions:
Move tweetlist to the Twitter Fragment and have it call the downloader. Then your TwitterFragment can construct and hold the list and update the UI as necessary. HOWEVER, consider the Fragment lifecycle (http://developer.android.com/guide/components/fragments.html), see the lifecycle section and diagram) The onDestroyView() method will be called when you swipe/flip over a couple of Fragments and back again. e.g. Android will not keep an indefinite number of Fragment alive and will destroy/re-create the view as needed. Don't try to update the Fragment's UI/layout objects from an AsyncTask. It's possible the Fragment might call onDestoryView() before your task completes. (you'll probably get NullPointerExceptions then) Instead have your AsyncTask only update Fragment scope variables (tweetlist) and have your onCreateView() use that same variable. (maybe synchronize the variable too)
Keep your major variable/objects/AsyncTask invoking code, all in the MainActivity, and add methods to access them from a Fragment, and have the Fragment getActivity() and cast it to MainActivity and call the method when needed:
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
ArrayList<String> tweetList = new ArrayList<String>();
...
public ArrayList<String> getTweetlist() {
return tweetlist;
}
...
}
public class TwitterFragment extends Fragment {
...
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_twitter, container, false);
...
ArrayList<String> tweetList = ((MainActivity)getActivity()).getTweetlist();
...
return rootView;
}
...
}
Let me try to explain, first use this FragmentPagerAdapter:
public class TestFragmentAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
protected static final String[] CONTENT = new String[] { "CATEGORIAS", "PRINCIPAL", "AS MELHORES", };
protected static final int[] ICONS = new int[] {
R.drawable.perm_group_calendar,
R.drawable.perm_group_camera,
R.drawable.perm_group_device_alarms,
};
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {Fragment f = null;
switch(position){
case 0:
{
f = new ArrayListFragment();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
case 1:
{
f = new HomeFragment();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
case 2:
{
f = new EndlessCustomView();//YourFragment
// set arguments here, if required
Bundle args = new Bundle();
f.setArguments(args);
break;
}
default:
throw new IllegalArgumentException("not this many fragments: " + position);
}
return f;
}
#Override
public int getCount() {
return mCount;
}
#Override
public CharSequence getPageTitle(int position) {
return TestFragmentAdapter.CONTENT[position % CONTENT.length];
}
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
As you can see, ArrayListFragment, HomeFragment and EndlessCustomView is a class that extends Fragment, so for each of these classes inside onCreate() , You can setContentView(R.layout.your_layout);
Then you can add a button or whatever you want in this layout.

Categories

Resources