It's working fine in single GridView Json Object,when i am calling to tabView my tabs will displaying but my Gridview not set into my Tabs.
Please any one help me
Main Activity
public class MainActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Top Rated", "Games", "Movies" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
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) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
MyAdapter
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new Kids();
case 1:
// Games fragment activity
return new Kids();
case 2:
// Movies fragment activity
return new Kids();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
this activity not displaying in my Tabview,it will working fine in my single gridview activity,when i am calling in tabview it will not diisplaed my gridview
kids.java
public class Kids extends Fragment {
ListAdapter adapter;
private ArrayList<Pojo> gridData;
GridView grd;
private ProgressBar mProgressBar;
private String Sam_URL = "http://example.in/rest/jsoMain/document?name=Rekapalli";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
System.out.println("Servce Called");
gridData=new ArrayList<Pojo>();
grd =(GridView)rootView.findViewById(R.id.gridview);
Async as=new Async(getActivity(),grd);
as.execute(Sam_URL);
mProgressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
// grd.setBackgroundColor(Color.CYAN);
grd.setVerticalSpacing(7);
grd.setHorizontalSpacing(7);
return super.onCreateView(inflater, container, savedInstanceState);
}
class Async extends AsyncTask<String, Void, Integer>{
Context context;
GridView gridView;
public Async(Context context,GridView gridView) {
// TODO Auto-generated constructor stub
this.context=context;
this.gridView=gridView;
}
#Override
protected Integer doInBackground(String... params) {
// TODO Auto-generated method stub
Integer result = 0;
try {
// Create Apache HttpClient
//HttpClient httpclient = new DefaultHttpClient();
URL url = new URL(Sam_URL);
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(
urlConnection.getInputStream());
// int statusCode =
// httpResponse.getStatusLine().getStatusCode();
// 200 represents HTTP OK
if (true) {
String response = streamToString(in);
parseResult(response);
result = 1; // Successful
} else {
result = 0; // "Failed
}
} catch (Exception e) {
}
return result;
}
String streamToString(InputStream stream) throws IOException {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(stream));
String line;
String result = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
// Close stream
if (null != stream) {
stream.close();
}
return result;
}
#Override
protected void onPostExecute(Integer result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result == 1) {
gridView.setAdapter(new MyAdapter(context,gridData));
gridView.setVisibility(View.VISIBLE);
}mProgressBar.setVisibility(View.GONE);
}
private void parseResult(String result) {
try {
Log.d("MainActivity", "JSON Result : " + result);
JSONArray response = new JSONArray(result);
for (int i = 0; i < response.length(); i++)
{
JSONObject obj = response.getJSONObject(i);
String Doc_name = obj.getString("documentName");
Log.d("documentName",Doc_name);
String Doc_file = obj.getString("documentFile");
String Doc_content = obj.getString("documentContent");
String Doc_offer=obj.getString("offer");
String Doc_address=obj.getString("address");
//Log.d("documentName","JSON Result : " + result);
Pojo gd = new Pojo();
gd.setDocumentName(Doc_name);
gd.setDocumentFile(Doc_file);
gd.setOffer(Doc_offer);
gd.setDocumentContent(Doc_content);
gd.setAddress(Doc_address);
gridData.add(gd);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Change from:
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new Kids();
case 1:
// Games fragment activity
return new Kids();
case 2:
// Movies fragment activity
return new Kids();
}
return null;
}
To:
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
// Top Rated fragment activity
return new Kids();
case 1:
// Games fragment activity
return new Games();
case 2:
// Movies fragment activity
return new Movies();
}
return null;
}
Hope that Helps!!!
Related
Im trying to update the progress bar based on the swiping of fragments , totally there are three fragments , and three circular progress bar , im getting the progress bar along with the test values no problem about that , but im not getting the fragments displayed ,this is the code please let me know where im wrong .
public class History extends Fragment {
final int PAGE_COUNT = 3;
private String tabTitles[] = new String[]{"Tab1", "Tab2", "Tab3"};
public static final String ARG_PAGE = "ARG_PAGE";
private static final int NUM_PAGES = 3;
String medicinename,medicinepercentage,numberdosages,time;
String date,day,daypercentage;
String month,monthdata;
/**
* 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;
private int selectedPage; // set selected page
// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
DonutProgress dp;
DonutProgress dp2;
DonutProgress dp3;
public static History newInstance(int page) {
Log.e("History ", String.valueOf(page));
Bundle args = new Bundle();
args.putInt(ARG_PAGE, page);
History fragment = new History();
fragment.setArguments(args);
return fragment;
}
// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;
public History() {
// Required empty public constructor
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment History.
*/
// TODO: Rename and change types and number of parameters
public static History newInstance(String param1, String param2) {
Log.e("History2 ", param1+param2);
History fragment = new History();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View v = inflater.inflate(R.layout.fragment_history, container, false);
dp = (DonutProgress) v.findViewById(R.id.donut_progress1);
dp2 = (DonutProgress) v.findViewById(R.id.donut_progress2);
dp3 = (DonutProgress) v.findViewById(R.id.donut_progress3);
new Progress(100).execute();
new Progress2(20).execute();
new Progress3(30).execute();
new Progress(40).execute();
new Progress2(50).execute();
new Progress3(90).execute();
new Progress(50).execute();
new Progress2(10).execute();
new Progress3(30).execute();
/* new Progress(0).execute();
new Progress2(0).execute();
new Progress3(0).execute();*/
if (getArguments() != null)
{
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
mPager = (ViewPager) v.findViewById(pager); //the UI pager
mPagerAdapter = new ScreenSlidePagerAdapter(getFragmentManager()) {
#Override
public int getCount()
{
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
};
mPager.setAdapter(mPagerAdapter);
// mPager.setPageTransformer(true, new RotateDownTransformer()); //set the animation
selectedPage = 0; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 1; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
selectedPage = 2; //current page
if (savedInstanceState != null) { //if app was paused, you can reopen the same page
selectedPage = savedInstanceState.getInt("SELECTED_PAGE");
}
mPager.setCurrentItem(selectedPage);
mPager.setOffscreenPageLimit(0);
//set the current page
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position)
{
// Check if this is the page you want.
getItem(position);
Log.e("Started","hello");
}
public Fragment getItem(int position) {
int i = 0;
switch (position) {
case 0: { // Fragment # 0 - This will show FirstFragment
if (!(i < 3)) {
}
++i;
return SlideFragment.newInstance(String.valueOf(0), " ");
}
case 1: { // Fragment # 1 - This will show SecondFragment
Log.e("Fragment", "Fragment 2");
if (!(i < 3)) {
/*new Progress(40).execute();
new Progress2(50).execute();
new Progress3(90).execute();*/
}
++i;
return Slidetwo.newInstance(String.valueOf(1), " ");
}
case 2: { // Fragment # 1 - This will show SecondFragment
Log.e("Fragment", "Fragment 3");
if (!(i < 3)) {
/* new Progress(50).execute();
new Progress2(10).execute();
new Progress3(0).execute();*/
}
++i;
return SlideThree.newInstance(String.valueOf(2), " ");
}
default:
return null;
}
}
});
return v;
}
class Progress extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable = 0;
Progress(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dp.setMax(100);
// Progress.getIndeterminateDrawable().setColorFilter(Color.parseColor("#C0D000"), android.graphics.PorterDuff.Mode.SRC_ATOP);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++)
{
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
class Progress2 extends AsyncTask<Void, Integer, Integer> {
int dummyVariable =0;
Progress2(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
dp2.setMax(100);
}
#Override
protected Integer doInBackground(Void... params) {
for (int i = 0; i <= dummyVariable; i++) {
publishProgress(i);
try {
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp2.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
class Progress3 extends AsyncTask<Void, Integer, Integer>
{
int dummyVariable =0;
Progress3(int dummyVariable)
{
this.dummyVariable = dummyVariable;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
dp3.setMax(100);
}
#Override
protected Integer doInBackground(Void... params)
{
for (int i = 0; i <= dummyVariable; i++) {
publishProgress(i);
try
{
Thread.sleep(20);
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
dp3.setProgress(values[0]);
}
#Override
protected void onPostExecute(Integer integer) {
super.onPostExecute(integer);
}
}
private class ScreenSlidePagerAdapter extends PagerAdapter {
public ScreenSlidePagerAdapter(Object fragmentManager) {
}
#Override
public int getCount() {
return 0;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return false;
}
}
// TODO: Rename method, update argument and hook method into UI event
}
`
I have a 7 tabs and their shared fragment whose data depends on XML received from url. The problem is if I set setOffscreenPageLimit(6) and for first tab, everything is fine for tab number 1 but tab number 2 to 7 shows the data from url that supposed to show in last tab.
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager(), this, negeri);
viewPager.setAdapter(mAdapter);
viewPager.setOffscreenPageLimit(6);
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setTitle("List");
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
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) {
}
});
FragmentStatePagerAdapter;
public class TabsPagerAdapter extends FragmentStatePagerAdapter {
static Context context;
static Resources res = null;
static String[] CONTENT = null;
public TabsPagerAdapter(FragmentManager fm, Context c, String negeri) {
super(fm);
context = c;
res = context.getResources();
CONTENT = res.getStringArray(R.array.values);
}
#Override
public ListFragment getItem(int index) {
return DaerahFragment.newInstance(CONTENT[index]);
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return CONTENT.length;
}
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
ListFragment;
public static ListFragment newInstance(String daerahVal) {
// TODO Auto-generated method stub
Bundle args = new Bundle();
args.putString(ARG_DAERAH, daerahVal);
DaerahFragment fragment = new DaerahFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Bundle args = getArguments();
//String daerah=args.getString("daerah");
daerah = getArguments().getString(ARG_DAERAH);
Toast.makeText(getActivity(), "daerah= " + daerah , Toast.LENGTH_SHORT).show();
URL = "http://www.url.com/android/daerahMarker.php?daerah="+daerah;
setRetainInstance(true);
if (mListViewScrollPos != null && adapter != null) {
getListView().onRestoreInstanceState(mListViewScrollPos);
} else {
myTask = new TalkToServer();
myTask.execute();
}
}
TQ
i solved this
just remove static
static String URL = "";
to
String URL = "";
:)
In my Androidapp I use Swipe View as my navigation now.
If I start my App, this one loads all of my different fragments and not only this one whioch is selected. If I switch between the Fragments the view doesn't get reloaded.
How can I do this that only getting load the view which is selected and if I switch to a fragment this is getting reloaded again.
Thanks
MainActivity:
public class MainActivity extends FragmentActivity implements ActionBar.TabListener {
AppSectionsPagerAdapter mAppSectionsPagerAdapter;
ViewPager mViewPager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAppSectionsPagerAdapter = new AppSectionsPagerAdapter(getSupportFragmentManager());
final ActionBar actionBar = getActionBar();
assert actionBar != null;
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mAppSectionsPagerAdapter);
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
for (int i = 0; i < mAppSectionsPagerAdapter.getCount(); i++) {
actionBar.addTab(
actionBar.newTab()
.setText(mAppSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
public class AppSectionsPagerAdapter extends FragmentPagerAdapter {
public AppSectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int i) {
switch (i) {
case 0:
return new EventCalendarFragment();
default:
return new VideoListFragment();
}
}
#Override
public int getCount() {
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
if (position == 0) {
return "Event";
} else {
return "Videos";
}
}
}
VideoListFragment:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_videos_table, container, false);
//load customBanner
imageView = (ImageView) rootView.findViewById(R.id.video_imageView);
imageView.setVisibility(View.GONE);
new AsyncTaskParseJson().execute();
inputSearch = (EditText) rootView.findViewById(R.id.video_inputSearch);
new UpdateData().execute();
return rootView;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser){
if (isVisibleToUser == true){
new AsyncTaskParseJson().execute();
new UpdateData().execute();
}
}
UpdateData:
class UpdateData extends AsyncTask<Void, Void, JSONArray> {
int error = 0;
InputStream is = null;
String result = "";
JSONArray jArray = null;
ProgressDialog pd;
#Override
protected void onPostExecute(JSONArray result) {
super.onPostExecute(result);
pd.dismiss();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = ProgressDialog.show(getActivity(), "",
"Loading...", true);
}
#Override
protected JSONArray doInBackground(Void... arg0) {
error = 0;
url = "************";
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
error = 1;
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
error = 1;
}
deptList.clear();
try {
JSONArray array = new JSONArray(result);
for (int i = 0; i < array.length(); i++) {
JSONObject j = array.getJSONObject(i);
EventCalendarStrings d = new EventCalendarStrings();
d.name = j.optString("name", "");
deptList.add(d);
}
} catch (JSONException e) {
Log.e("log_tag", "No connection " + e.toString());
error = 1;
}
return jArray;
}
}
Logcat:
E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
If I understand your question correctly, you should override setUserVisibleHint(boolean isVisibleToUser) method in your fragments and use it as indicator that your fragment is currently visible (if isVisibleToUser is true). Then you should move there your logic (I suppose it's in onCreateView now) that should be invoked only if a fragment is currently on the screen.
Viewpager reads the loaded one...its clever
override this method.
public int getItemPosition (Object object)
{
return POSITION_NONE;
}
POSITION_NONE: data changed, remove the fragment.
POSITION_UNCHANGED: data unchanged.
I might be late for the party but here's my solution and it works as expected. This solution also prevents your users from re-sending requests again and again (if you're doing network operations).
In all of your child fragments create a boolean variable:
private boolean loadFragmentExecuted = false;
in the child fragments create a generic method called loadFragment and move all of the logic you added in onCreateView to that method:
public void loadFragment()
{
if(!loadFragmentExecuted)
{
//Add your logic to manipulate the UI or load data etc...
loadFragmentExecuted = true;
}
}
in your pageview logic create the fragments dynamically like:
//add the fragment
String fragmentName = "com.something." + fragmentId;
//check if the class exists
try
{
Class myFragmentClass = Class.forName(fragmentName);
Fragment myFragment = (Fragment) myFragmentClass.newInstance();
mFragments.add(myFragment);
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
then set your pager adapter and attach a tablayout with it:
//set our pager adapter that contains different fragments
mPagerAdapter = new BasePagerAdapter(mFragmentManager, mFragments);
//link the adapter to the viewpager
mViewPager.setAdapter(mPagerAdapter);
//cache fragments
int limit = (mPagerAdapter.getCount() > 0 ? mPagerAdapter.getCount() : 1);
mViewPager.setOffscreenPageLimit(limit);
//add the page listner to the viewPager and link it to the tabLayout
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(mTabLayout));
//on tab selected select current viewpager item
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener()
{
#Override
public void onTabSelected(TabLayout.Tab tab)
{
mViewPager.setCurrentItem(tab.getPosition());
//get fragment for the selected tab
Fragment f = mPagerAdapter.getItem(tab.getPosition());
//load the content of the fragment
try
{
Class c = f.getClass();
Method loadFragment = c.getMethod("loadFragment");
loadFragment.invoke(f);
}
catch (IllegalAccessException e){}
catch (InvocationTargetException e){}
catch (NoSuchMethodException e){}
}
#Override
public void onTabUnselected(TabLayout.Tab tab)
{
}
#Override
public void onTabReselected(TabLayout.Tab tab)
{
}
});
My problem is that I can't update the data of my AcTview adapter, when I enter data from another of my fragment.
In PageAdjuFragment I have the ACTV tv2 and his adapter adapter2.
The data of this adapter are created by getListpart() in VenteFragment (PageAdjuFragment extends VenteFragment).
I know that getListpart() and initpart() work cause when I relaunch my app, the new data appears in my actv.
I think that the problem is when I switching between my fragments, they are already launch so the data are initialized just one time at the start.
I navigate between fragment when i switch of page on my app. 3 fragments on 1 activity create with MyPagerAdapter
here my code
The fragment
public class PageAdjuFragment extends VenteFragment {
Context context = getActivity();
public PageAdjuFragment() {
super();
// TODO Auto-generated constructor stub
}
public static PageAdjuFragment newInstance(String vente) {
PageAdjuFragment myFragment = new PageAdjuFragment();
Bundle args = new Bundle();
args.putString("vente", vente);
myFragment.setArguments(args);
return myFragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
final View v = inflater.inflate(R.layout.page_adju_layout, container, false);
final Button b = (Button) v.findViewById(R.id.btconfp);
final RadioGroup radiopmt = (RadioGroup) v.findViewById(R.id.radiopmt);
final RadioButton rb1 = (RadioButton) v.findViewById(R.id.rb1);
final RadioButton rb2 = (RadioButton) v.findViewById(R.id.rb2);
final AutoCompleteTextView tv1 = (AutoCompleteTextView) v.findViewById(R.id.actv1);
final AutoCompleteTextView tv2 = (AutoCompleteTextView) v.findViewById(R.id.actv2);
final EditText tv3 = (EditText) v.findViewById(R.id.edt);
// Recovery of the name of th folder/vente
Bundle arg = getArguments();
// final String vente = arg.getString("vente");
VenteFragment.nomvente = arg.getString("vente");
try {
InitObjet();
InitPart();
} catch (IOException e) {
e.printStackTrace();
}
for (String elem : getListpart()) {
Log.v("part", elem);
}
ArrayAdapter<String> adapter2 = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_dropdown_item_1line, this.getListobject());
tv2.setAdapter(adapter2);
//some useless code ////////////////
}
The ActivityFragment
public class VenteActivity extends FragmentActivity {
private PagerAdapter mPagerAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.viewpager2);
creationPage();
}
public void creationPage() {
// Creation of the list
List<Fragment> fragments = new Vector<Fragment>();
// Recovery
Intent sender = getIntent();
String extraData = sender.getExtras().getString("vente");
Log.v("Vente activity", extraData);
// Add Fragments in a list
Fragment frag1 = PageOffreFragment.newInstance(extraData); // frag1 //
// anymor
fragments.add(frag1);
Fragment frag2 = PageAdjuFragment.newInstance(extraData); // frag2 //
// anymor
fragments.add(frag2);
Fragment frag3 = PagePartFragment.newInstance(extraData); // frag3 //
// anymor
fragments.add(frag3);
// Creation of theadapter
this.mPagerAdapter = new MyPagerAdapter(super.getSupportFragmentManager(), fragments);
final ViewPager pager = (ViewPager) super.findViewById(R.id.viewpager2);
// Affectation on the ViewPager
//pager.setOffscreenPageLimit(1);
pager.setAdapter(this.mPagerAdapter);
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int arg0) {
}
});
}
// Overide for blocking the BACK Key of android device
#Override
public void onBackPressed() {
}
}
The class for work on the fragment :
public class VenteFragment extends Fragment {
protected static List<String> Listobject = null;
protected static List<String> Listpart = null;
protected static List<String> Listclient = null;
protected static String nomvente;
public List<String> getListobject() {
return Listobject;
}
public void setListobject(List<String> listobject) {
Listobject = listobject;
}
public List<String> getListpart() {
return Listpart;
}
public void setListpart(List<String> listpart) {
Listpart = listpart;
}
public List<String> getListclient() {
return Listclient;
}
public void setListclient(List<String> listclient) {
Listclient = listclient;
}
// Create the List of participant
public void InitClient() throws IOException {...}
// Create the List of participant
public void InitPart() throws IOException {
Log.v("VFvente", this.nomvente);
File DIR = new File(Environment.getExternalStorageDirectory() + "/Vente Acta/ListeVente/" + this.nomvente);
final String ADDRESS_FILE = DIR.toString() + "/" + "participant.csv"; // l'emplacement
// de
// achat.csv
Log.v("VFchemin", ADDRESS_FILE);
// if the file doesn't exit, create the file
File f = new File(ADDRESS_FILE);
if (!f.exists()) {
f.createNewFile();
Log.v("VFvente", "ici");
return;
}
List<String> data = new ArrayList<String>(); // liste contenant les
// element a adapter
// aux
// autotextview
// on applique le reader sur le fichier
CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE));
List<String[]> liste = reader.readAll();
int i = 0;
for (String[] ligne : liste) {
for (String col : ligne) {
Log.v("ligne " + i, "col " + col);
}
i++;
}
for (String[] elem : liste) { // pour chaque ligne
Log.v("VFdataelem0", elem[0]);
Log.v("VFdataelem1", elem[1]);
Log.v("VFdataelem2", elem[2]);
data.add(elem[1] + " " + elem[2]); // le nom et prenom
data.add(elem[0]); // le numero de participant pour la vente
}
reader.close();
Log.v("VFvente", "fin");
this.setListpart(data);
}
// Create the List of object
public void InitObjet() throws IOException {...}
}
The Page Adapter
public class MyPagerAdapter extends FragmentStatePagerAdapter {
List<Fragment> fragments;
FragmentManager mFragmentManager;
// On fournit à l'adapter la liste des fragments à afficher
public MyPagerAdapter(FragmentManager fm, List fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int pos) {
return this.fragments.get(pos);
}
#Override
public int getCount() {
return this.fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
I have already try :
public int getItemPosition(Object object) {
return POSITION_NONE;
}
or adapter2.setNotifyOnChange(true);
or onResume
BUT maybe at the wrong place
and
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int i) {
Log.d("onPageSelected: ", i + "");
if(i == 0) {
PageOffreFragment frg = (PageOffreFragment)mPagerAdapter.instantiateItem(pager, i);
frg.onResume();
} else if (i == 1){
PageAdjuFragment frg = (PageAdjuFragment)mPagerAdapter.instantiateItem(pager, i);
frg.onResume();
}else if (i == 2) {
PagePartFragment frg = (PagePartFragment)mPagerAdapter.instantiateItem(pager, i);
frg.onResume();
}
}
in VenteActiivty
Nothing work :(
The creation is ok, the problem is the lifecycle of my fragment. (i think)
and where reload my fragment for update the list of data of my ACTV
Before you call notifychange make sure you add the new data first to you arraylist then call notify change
Finaly I have found a solution: this is my new FragmentActivity:
public class VenteActivity extends FragmentActivity {
private MyPagerAdapter mPagerAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setContentView(R.layout.viewpager2);
creationPage();
}
public void creationPage() {
// Creation of the list
final List<Fragment> fragments = new Vector<Fragment>();
// Recovery
Intent sender = getIntent();
final String extraData = sender.getExtras().getString("vente");
Log.v("Vente activity", extraData);
// Add Fragments in a list
final Fragment frag1 = PageOffreFragment.newInstance(extraData); // frag1
fragments.add(frag1);
final Fragment frag2 = PageAdjuFragment.newInstance(extraData); // frag2
fragments.add(frag2);
final Fragment frag3 = PagePartFragment.newInstance(extraData); // frag3
fragments.add(frag3);
// Creation of theadapter
this.mPagerAdapter = new MyPagerAdapter(super.getSupportFragmentManager(), fragments);
final ViewPager pager = (ViewPager) super.findViewById(R.id.viewpager2);
// Affectation on the ViewPager
// pager.setOffscreenPageLimit(1);
pager.setAdapter(this.mPagerAdapter);
pager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int i) {
Log.d("onPageSelected: ", i + "");
mPagerAdapter.notifyDataSetChanged();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
}
I've started programming for Android (from iOS), and I working with the boiler plate code that ADT generates for me when I choose Activity+Scrollable tabs option in the new Project wizard. In the code below I've marked the same in comments.
The scenario is I enter text in an editText, press the button and fetch some data from a webservice. I wish to put this data in the appropriate fragment (there are 3 fragments) inside a view pager. I am getting the data and I am able to set it on Fragment 2 and Fragment 3 when I swipe, but the data that is relevant to Fragment 1 is not getting set once the AsycTask is complete. However, after swiping to fragment 3, when I come back to fragment 1, the data is there.
Here is my code:
Activity
public class XXXX extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
//My additions to the boiler plate source generated by ADT
public ArrayList<String> p1T,p2T,p3T,p4T;
private EditText editText;
private Button button;
private boolean flag;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.konjugation);
mSectionsPagerAdapter = new SectionsPagerAdapter (getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
//My additions to the boiler plate source below
flag=false;
p1T = new ArrayList<String>(6);
p2T = new ArrayList<String>(6);
p3T = new ArrayList<String>(6);
p4T = new ArrayList<String>(6);
editText = (EditText) findViewById(R.id.editText1);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url = editText.getText().toString();
if(!url.isEmpty()) {
url="http://.../?q="+editText.getText().toString();
PAsyncTask task = new PAsyncTask();
task.execute(url);
}
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener(){
#Override
public void onPageSelected(int pos) {
if(flag==true) {
if(pos==0) DummySectionFragment.setText(p4T,p1T);
if(pos==1) DummySectionFragment.setText(p4T,p2T);
if(pos==2) DummySectionFragment.setText(p4T,p3T);
}
else {
Log.d("ts","data not arrived");
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.konjugation, menu);
return true;
}
PagerAdapter
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
Fragment fragment = new DummySectionFragment();
return fragment;
}
#Override
public int getCount() {
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return getString(R.string.title_section1);
case 1:
return getString(R.string.title_section2);
case 2:
return getString(R.string.title_section3);
}
return null;
}
#Override
public void notifyDataSetChanged() {
int pos = mViewPager.getCurrentItem();
if(pos==0) DummySectionFragment.setText(p4T,p1T);
else if(pos==1) DummySectionFragment.setText(p4T,p2T);
else if(pos==2) DummySectionFragment.setText(p4T,p3T);
}
}
AsyncTask
private class PAsyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params)
{
String response = "";
for (String url : params) {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse execute = client.execute(httpGet);
InputStream content = execute.getEntity().getContent();
BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
String s = "";
while ((s = buffer.readLine()) != null) {
response += s;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return response;
}
protected void onPostExecute(String result)
{
try {
p1T.clear();
p2T.clear();
p3T.clear();
//do something very important with the result here
flag=true;
//hoping that somehow the viewpager adapter will refresh the view
mSectionsPagerAdapter.notifyDataSetChanged();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Viewpager's fragment
public static class DummySectionFragment extends Fragment {
private static TextView dummyTextView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_konjugation_dummy, container, false);
dummyTextView = (TextView) rootView.findViewById(R.id.section_label);
return rootView;
}
public static void setText(ArrayList<String> s, ArrayList<String> t) {
try {
DummySectionFragment.dummyTextView.setText("");
for(int i=0;i<s.size();i++) {
DummySectionFragment.dummyTextView.append(s.get(i)+" "+t.get(i)+"\n\n");
}
} catch(NullPointerException e) {
e.printStackTrace();
}
}
}
}
I feel kinda lost, after reading some threads here. Please help :-(
you should update it inside of runOnUiThread() method, which takes a runnable object as argument, so you can pass your implementation in it.