I am trying to make my tabbed activity content to change dynamically, depended on the user choices in the other tabs.
All tabs are using the same fragment. only the content in the view is supposed to change (in this case a ListView)
Now the main problem is that when I make a choice (click on some line in the ListView) the next tab shows all of the content instead of filtering the data according to my choice in the previous tab, though when I click on a not-neighbor tab and then go back, the tab is filtered like I wanted.
From what I understand, the activity load the neighbor tabs of the current tab even if those are not focused and this is why I get the default result.
To simplify things:
Then I choose some line from the ListView and the focus automatically goes to the next tab.
The listView will show me the default contet, as if I chose nothing. But if I move the focus to the forth tab, and then again back to the second, the listView will be filtered as I wanted
Here is my code
public class Catalog_actbartabs 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
public static String PACKAGE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_catalog_actbartabs);
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);
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();
}
});
PACKAGE_NAME = getApplicationContext().getPackageName();
}
public void setCurrentItem(int item, boolean smoothScroll) {
mViewPager.setCurrentItem(item, smoothScroll);
}
#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_catalog_actbartabs, 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 {
protected ClogListAdapter2 clogListAdapter2;
protected ArrayList<String[]> stringArrayList;
protected static String topic = null;
protected static String rName = null;
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String EXTRA_ITEM_INFO = "com.dstudio.dvir.EXTRA_ITEM_INFO";
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;
rootView = inflater.inflate(R.layout.fragment_catalog, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getString(R.string.section_format, getArguments().getInt(ARG_SECTION_NUMBER)));
try {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1)
stringArrayList = Utils.getNamesList(super.getContext());
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2)
stringArrayList = Utils.getTopicsList(super.getContext(), rName);
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3)
stringArrayList = Utils.getClassesList(super.getContext(), rName, topic);
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4)
stringArrayList = Utils.getFilesList(super.getContext());
} catch (Throwable t) {
Toast.makeText(super.getContext(), "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
}
if (savedInstanceState != null) {
String[] values = savedInstanceState.getStringArray("myKey");
if (values != null) {
stringArrayList = ClogListAdapter2.bmListFromArray(values);
}
} else if (stringArrayList == null) {
stringArrayList = new ArrayList<String[]>();
}
clogListAdapter2 = new ClogListAdapter2(super.getContext(), stringArrayList, getArguments().getInt(ARG_SECTION_NUMBER));
ListView listV = (ListView) rootView.findViewById(R.id.listView);
listV.setAdapter(clogListAdapter2);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
if (clogListAdapter2.getItem(position)[0].equals("All"))
rName = null;
else rName = clogListAdapter2.getItem(position)[0];
topic = null;
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
if (clogListAdapter2.getItem(position)[0].equals("All"))
topic = null;
else topic = clogListAdapter2.getItem(position)[0];
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4) {
Intent intent = new Intent(parent.getContext(), AudioPlayerActivity.class);
intent.putExtra(EXTRA_ITEM_INFO, clogListAdapter2.getItem(position));
startActivityForResult(intent, 1);
}
((Catalog_actbartabs) getActivity()).setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER), true);
}
});
return rootView;
}
}
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 PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 4 total pages.
return 4;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "page 1";
case 1:
return "page 2";
case 2:
return "page 3";
case 3:
return "page 4";
}
return null;
}
}
}
UPDATE
Working Solution From #AmeyShirke
I added the var _hasLoadedOnce= false; to the rest of the vars in PlaceholderFragment class:
public static class PlaceholderFragment extends Fragment {
protected ClogListAdapter2 clogListAdapter2;
protected ArrayList<String[]> stringArrayList;
protected View rootView;
protected static String topic = null;
protected static String rName = null;
private boolean _hasLoadedOnce= false;
//Rest of the code
}
Now All the data setting code is inside setUserVisibleHint() without changing _hasLoadedOnce so it look like this:
#Override
public void setUserVisibleHint(boolean isFragmentVisible_) {
super.setUserVisibleHint(true);
if (this.isVisible()) {
// we check that the fragment is becoming visible
if (isFragmentVisible_ && !_hasLoadedOnce) {
Log.i("visable: ", getArguments().getInt(ARG_SECTION_NUMBER)+"");
try {
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1)
stringArrayList = Utils.getNamesList(super.getContext());
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2)
stringArrayList = Utils.getTopicsList(super.getContext(), rName);
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 3)
stringArrayList = Utils.getClassesList(super.getContext(), rName, topic);
else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4)
stringArrayList = Utils.getFilesList(super.getContext());
} catch (Throwable t) {
Toast.makeText(super.getContext(), "Exception: " + t.toString(), Toast.LENGTH_LONG).show();
}
clogListAdapter2 = new ClogListAdapter2(super.getContext(), stringArrayList, getArguments().getInt(ARG_SECTION_NUMBER));
ListView listV = (ListView) rootView.findViewById(R.id.listView);
listV.setAdapter(clogListAdapter2);
listV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO: 23/12/2016 remember to also give the needed info to get the asked next category
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
if (clogListAdapter2.getItem(position)[0].equals("All"))
rName = null;
else rName = clogListAdapter2.getItem(position)[0];
topic = null;
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 2) {
if (clogListAdapter2.getItem(position)[0].equals("All"))
topic = null;
else topic = clogListAdapter2.getItem(position)[0];
} else if (getArguments().getInt(ARG_SECTION_NUMBER) == 4) {
Intent intent = new Intent(parent.getContext(), AudioPlayerActivity.class);
intent.putExtra(EXTRA_ITEM_INFO, clogListAdapter2.getItem(position));
startActivityForResult(intent, 1);
}
((Catalog_actbartabs) getActivity()).setCurrentItem(getArguments().getInt(ARG_SECTION_NUMBER), true);
}
});
//Notify that _hasLoadedOnce = true; is now gone
}
}
}
I also added the line mViewPager.setOffscreenPageLimit(3); in the activity's onCreate() because if I chose to go directly to the forth tab after the first filtering it wouldn't filter it, so that way the activity will filter it correctly.
This is default behaviour of ViewPager. To load only single tab use:
mViewPager.setOffscreenPageLimit(1);
If that doesnt work, then you have to create your own sub-class of ViewPager and override the below method:
private boolean _hasLoadedOnce= false; // your boolean field
#Override
public void setUserVisibleHint(boolean isFragmentVisible_) {
super.setUserVisibleHint(true);
if (this.isVisible()) {
// we check that the fragment is becoming visible
if (isFragmentVisible_ && !_hasLoadedOnce) {
//your code here
_hasLoadedOnce = true;
}
}
}
Related
First of all, I'm sorry for my english, but I need your help.
I got a recyclerView gallery with photos and option to show the selected photo in another activity.
I`m trying to share an image that activity to somewhere, e.g. email, but I receive an empty message with no image.
Could you help me to find out, what am I doing wrong?
Below is the code of gallery activity and single image activity.
Thank you for answers.
public class MainActivity extends AppCompatActivity {
GalleryAdapter mAdapter;
RecyclerView mRecyclerView;
ArrayList<ImageModel> data = new ArrayList<>();
public static String getURLForResource(int resourceId) {
return Uri.parse("android.resource://" + R.class.getPackage().getName() + "/" + resourceId).toString();
}
public static String IMGS[];
public static String MAYF[] = {
"file:///android_asset/mayf1.jpg",
"file:///android_asset/mayf2.gif",
"file:///android_asset/mayf3.jpg",
"file:///android_asset/mayf4.jpg",
"file:///android_asset/mayf5.gif",
"file:///android_asset/mayf6.gif",
"file:///android_asset/mayf7.jpg",
"file:///android_asset/mayf8.jpg",
"file:///android_asset/mayf9.jpg",
"file:///android_asset/mayf10.jpg"
};
public static String APRF[] = {
"file:///android_asset/apr1.jpg",
"file:///android_asset/apr2.gif",
"file:///android_asset/apr3.jpg",
"file:///android_asset/apr4.jpg",
"file:///android_asset/apr5.gif",
"file:///android_asset/apr6.gif",
"file:///android_asset/apr7.jpg",
"file:///android_asset/apr8.jpg",
"file:///android_asset/apr9.jpg",
"file:///android_asset/apr10.jpg"
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (StartingActivity.count == 1)
IMGS = Arrays.copyOf(APRF, APRF.length);
else if (StartingActivity.count == 2) {
IMGS = Arrays.copyOf(MAYF, MAYF.length);
} else {
Toast.makeText(getBaseContext(), "not filled yet",
Toast.LENGTH_LONG).show();
}
for (int i = 0; i < IMGS.length; i++) {
ImageModel imageModel = new ImageModel();
imageModel.setName("Image " + i);
imageModel.setUrl(IMGS[i]);
data.add(imageModel);
}
mRecyclerView = (RecyclerView) findViewById(R.id.list);
mRecyclerView.setLayoutManager(new GridLayoutManager(this, 3));
mRecyclerView.setHasFixedSize(true);
mAdapter = new GalleryAdapter(MainActivity.this, data);
mRecyclerView.setAdapter(mAdapter);
mRecyclerView.addOnItemTouchListener(new RecyclerItemClickListener(this,
new RecyclerItemClickListener.OnItemClickListener() {
#Override
public void onItemClick(View view, int position) {
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
intent.putParcelableArrayListExtra("data", data);
intent.putExtra("pos", position);
intent.putExtra("superUri", IMGS[position]);
startActivity(intent);
}
}));
}
#Override
public void onBackPressed() {
super.onBackPressed();
StartingActivity.count = 0;
}
}
This part is a part of a single image.
public class DetailActivity 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
private ShareActionProvider mShareActionProvider;
public ArrayList<ImageModel> data = new ArrayList<>();
int pos;
String shPos;
Toolbar toolbar;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
//toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
// setSupportActionBar(toolbar);
data = getIntent().getParcelableArrayListExtra("data");
pos = getIntent().getIntExtra("pos", 0);
shPos = getIntent().getStringExtra("superUri");
setTitle("Открытки");
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager(), data);
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setPageTransformer(true, new DepthPageTransformer());
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.setCurrentItem(pos);
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
//noinspection ConstantConditions
//setTitle(data.get(position).getName());
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
#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_detail, menu);
// Fetch and store ShareActionProvider
// Return true to display 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
return super.onOptionsItemSelected(item);
}
public void onShClick(MenuItem item) {
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(shPos));
shareIntent.setType("image/*");
startActivity(shareIntent);
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public ArrayList<ImageModel> data = new ArrayList<>();
public SectionsPagerAdapter(FragmentManager fm, ArrayList<ImageModel> data) {
super(fm);
this.data = data;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position, data.get(position).getName(), data.get(position).getUri());
}
#Override
public int getCount() {
// Show 3 total pages.
return data.size();
}
#Override
public CharSequence getPageTitle(int position) {
return data.get(position).getName();
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
String name, url;
int pos;
private static final String ARG_SECTION_NUMBER = "section_number";
private static final String ARG_IMG_TITLE = "image_title";
private static final String ARG_IMG_URL = "image_url";
#Override
public void setArguments(Bundle args) {
super.setArguments(args);
this.pos = args.getInt(ARG_SECTION_NUMBER);
this.name = args.getString(ARG_IMG_TITLE);
this.url = args.getString(ARG_IMG_URL);
}
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber, String name, String url) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
args.putString(ARG_IMG_TITLE, name);
args.putString(ARG_IMG_URL, url);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
#Override
public void onStart() {
super.onStart();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_detail, container, false);
final ImageView imageView = (ImageView) rootView.findViewById(R.id.detail_image);
Glide.with(getActivity()).load(url).thumbnail(0.1f).into(imageView);
return rootView;
}
}
}
Here is an example of trying to share image via gmail. I can see the image "attached", but can`t open it. Another email receives an empty message with no attachment inside.
sharing example
I've created a tabbed activity in Android Studio, selecting it from the "New activity" window dialog.
The tabs number is not fixed, but it is read from a file, so that there is a random number of tabs. For this purpose, I used a FragmentStatePagerAdapter.
In this activity I want to show a listview populated differently for each tab, but the problem is that the listview is not shown.
As you can see below, this is the java class, where I handle the operations within the tabs.
public class TournamentActivity extends AppCompatActivity {
private int returnT = 0, goingT = 0;
/**
* 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tournament);
Intent intent = this.getIntent();
String committee = intent.getStringExtra(TournamentsAdapter.EXTRA_COMMITTEE);
String tournament = intent.getStringExtra(TournamentsAdapter.EXTRA_TOURNAMENT);
String roundName = intent.getStringExtra(TournamentsAdapter.EXTRA_ROUNDNAME);
int roundId = intent.getExtras().getInt("EXTRA_ROUNDID");
int roundAr = intent.getExtras().getInt("EXTRA_ROUNDAR");
int matchDay = intent.getExtras().getInt("EXTRA_MATCHDAY");
int roundStage = intent.getExtras().getInt("EXTRA_ROUNDSTAGE");
new GetDataFromURL(this, "tournament.html").execute("http://www.fip.it/AjaxGetDataCampionato.asp?com=" + committee + "&camp=" + tournament + "&fase=" + roundStage + "&girone=" + roundId + "&ar=" + roundAr + "&turno=" + matchDay);
//parse del file per vedere titolo e quante schede fare (numero di giornate del campionato)
try{
FileReader fr = new FileReader(getFilesDir() + "/ImportData/tournament.html");
BufferedReader br = new BufferedReader(fr);
String line;
while((line = br.readLine())!= null){
if(line.contains("tableTopBkg")){
while((line = br.readLine())!= null){
Pattern pattern = Pattern.compile(">(.+?)</div>");
Matcher matcher = pattern.matcher(line);
while (matcher.find()){
String s = matcher.group(1);
s = s.substring(s.lastIndexOf(">") + 1);
returnT = Integer.parseInt(s);
}
if(line.equals("</tr>") && goingT == 0){
goingT += returnT;
}
else if(line.equals("</tr>")){
break;
}
}
}
}
System.out.println(returnT);
}catch (IOException ignored){}
catch (Exception e){e.printStackTrace();}
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);
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();
}
});
if(roundAr == 1)
mViewPager.setCurrentItem(matchDay - 1);
else if(roundAr == 0)
mViewPager.setCurrentItem((matchDay + goingT) - 1);
}
#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_tournament, 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;
}
// +++++ QUI SI POPOLANO LE TABS +++++
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_tournament, 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;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ListView listViewGames = (ListView) view.findViewById(R.id.listViewGames);
GamesAdapter adapter = new GamesAdapter(getActivity(), android.R.layout.simple_list_item_1);
listViewGames.setAdapter(adapter);
}
/*
#Override
public void onActivityCreated(Bundle savedInstanceState){
super.onActivityCreated(savedInstanceState);
GamesAdapter adapter = new GamesAdapter(getContext(), R.layout.activity_tournament);
listViewGames.setAdapter(adapter);
}*/
}
/**
* A {#link FragmentPagerAdapter} that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentStatePagerAdapter {
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 PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show N total pages.
return goingT + returnT;
}
}
}
In the onViewCreated method I get the reference of the listview and then create my custom adapter. Subsequently, with listViewGames.setAdapter(adapter); I set the adapter.
At this point when onViewCreated is called, the setAdapter method doesn't call getView in the adapter.
I also tried to set the adapter in the onCreateView method, but it still does not work.
This is the adapter class:
public class GamesAdapter extends ArrayAdapter{
private Context context;
public GamesAdapter(Context context, int resource) {
super(context, resource);
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.fragment_games, null);
ImageView imageViewStatus = (ImageView) convertView.findViewById(R.id.imageViewStatus);
ImageView imageViewTeamA = (ImageView) convertView.findViewById(R.id.imageViewTeamA);
ImageView imageViewTeamB = (ImageView) convertView.findViewById(R.id.imageViewTeamB);
TextView textViewGameId = (TextView) convertView.findViewById(R.id.textViewGameId);
TextView textViewDateTime = (TextView) convertView.findViewById(R.id.textViewDateTime);
TextView textViewTeamA = (TextView) convertView.findViewById(R.id.textViewTeamA);
TextView textViewTeamB = (TextView) convertView.findViewById(R.id.textViewTeamB);
TextView textViewScoreA = (TextView) convertView.findViewById(R.id.textViewScoreA);
TextView textViewScoreB = (TextView) convertView.findViewById(R.id.textViewScoreB);
FileReader fr = null;
String gameId = "";
try {
fr = new FileReader(context.getFilesDir() + "/ImportData/tournament.html");
BufferedReader br = new BufferedReader(fr);
String line;
int hops = 0;
while((line = br.readLine())!= null){
if(line.contains("<div class=\"risTrCode\">") && hops == position){
Pattern pattern = Pattern.compile(">(.+?)</a></div>");
Matcher matcher = pattern.matcher(line);
gameId = matcher.group(1);
System.out.println(gameId);
hops++;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
textViewGameId.setText(gameId);
return convertView;
}
}
I have a ViewPager that I set up in a simple example app. I have a single static fragment implemented as an inner-class with a RecylerView in it. I'd like to change the LayoutManager of the RecyclerView based on which tab I'm in. My implementation is show below. This is not working for me. When I load this ViewPager is starts in the 1st position but has a staggered layout (which should be for the 3rd position). When I swipe over to the 2nd position it is still the staggered layout, nothing changed as the getItem() method of my PagerAdapter was never called. When I switch over to the 3rd position is does call getItem() and the RecylerView is reloaded, however it still has the staggered layout (this is where it actually should have the staggered layout).
After reading up a bit on ViewPagers I'm realizing that the PagerAdapter will reuse the fragment if it determines that it can. I think that is what is happening here. Is there any way to keep this from happening? Can I get my LayoutManager to switch for each tab while just using one Fragment? Essentially I want it to instantiate a new Fragment for each tab.
public class TabbedActivity 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}.
*/
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
public static Intent newIntent(Context packageContext){
Intent intent = new Intent(packageContext, TabbedActivity.class);
return intent;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
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);
}
#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_tabbed, 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);
}
public static class RecyclerFragment extends Fragment {
private static final String ARG_LAYOUT_TYPE = "layout-type";
private int layoutType = 0;
RecyclerView recyclerView;
public ArrayList<AndroidVersion> data;
public DataAdapter adapter;
public static final int FRAGMENT_LINEAR = 0;
public static final int FRAGMENT_GRID = 1;
public static final int FRAGMENT_STAG_GRID = 2;
public static RecyclerFragment newInstance(int layoutType) {
Timber.d("newInstance() called with int: " + layoutType);
RecyclerFragment fragment = new RecyclerFragment();
Bundle args = new Bundle();
args.putInt(ARG_LAYOUT_TYPE, layoutType);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
if(getArguments() != null){
layoutType = getArguments().getInt(ARG_LAYOUT_TYPE);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_linear, container, false);
Button button = (Button) rootView.findViewById(R.id.view_pager_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent mainActivityIntent = MainActivity.newIntent(getActivity().getApplicationContext());
startActivity(mainActivityIntent);
}
});
recyclerView = (RecyclerView) rootView.findViewById(R.id.card_recyler_view_pager);
//recyclerView.setHasFixedSize(true);
// Check to see what the layout type should be and create the necessary LayoutManager
switch(layoutType){
case FRAGMENT_LINEAR:
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity(), LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
case FRAGMENT_GRID:
GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
recyclerView.setLayoutManager(gridLayoutManager);
case FRAGMENT_STAG_GRID:
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
}
loadJSON();
return rootView;
}
private void loadJSON() {
Retrofit retrofit = MainActivity.getRestAdapter();
RequestInterface request = retrofit.create(RequestInterface.class);
Call<JSONResponse> call = request.getJSON();
call.enqueue(new Callback<JSONResponse>() {
#Override
public void onResponse(Call<JSONResponse> call, Response<JSONResponse> response) {
JSONResponse jsonResponse = response.body();
data = new ArrayList<>(Arrays.asList(jsonResponse.getAndroid()));
adapter = new DataAdapter(data);
recyclerView.setAdapter(adapter);
}
#Override
public void onFailure(Call<JSONResponse> call, Throwable t) {
Log.d("Error", t.getMessage());
}
});
}
}
/**
* 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.
Timber.d("getItem called, position: " + position);
return RecyclerFragment.newInstance(position);
}
#Override
public int getCount() {
// Show 3 total pages.
return 3;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Linear";
case 1:
return "Grid";
case 2:
return "Staggered";
}
return null;
}
}
}
Try this :
inside the RecyclerFragment class define a static variable :
private static RecyclerFragment instance = null;
and change newInstance method like below :
public static RecyclerFragment newInstance(int layoutType) {
Timber.d("newInstance() called with int: " + layoutType);
instance =new RecyclerFragment();
Bundle args = new Bundle();
args.putInt(ARG_LAYOUT_TYPE, layoutType);
instance.setArguments(args);
return instance;
}
From MainActivity when i goto HolidayActivity by using explicit intent i am able to see the LisView is populated with distinct elements within the fragment, After pressing back button i again goto MainActivity and when i again try to open HolidayActivity the ListView is populated again with duplicate elements, I have used LoaderManager, so when device is rotated there is no duplicate elements, the problems occurs only when i switch between activities as described above. I have also tried to Override methos onKeyDown() and onBackPresses() but nothing seems to work out. Point to be noted out here is that i am fetching the list items from server.
HolidayActivity.java
public class HolidaysActivity extends AppCompatActivity {
public static String HOLIDAY_REQUEST_URL;
public static holidayAdapter adapter;
public static final String LOG_TAG = HolidaysActivity.class.getSimpleName();
public static Context mcontext ;
public static Activity activity = null;
public static int list_id;
public static ListView listView_holiday;
/**
* 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 static boolean studentLogin = false;
private static boolean employeeLogin = false;
private SectionsPagerAdapter mSectionsPagerAdapter;
/**
* The {#link ViewPager} that will host the section contents.
*/
private ViewPager mViewPager;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
mcontext = this;
activity = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_holidays);
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(container);
mViewPager.setAdapter(mSectionsPagerAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(mViewPager);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK))
{
HolidaysActivity.this.finish();
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onBackPressed() {
super.onBackPressed();
activity.finish();
}
#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_holidays, 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 implements LoaderManager.LoaderCallbacks<List<holidays>> {
/**
* 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.holidays_list, container, false);
// condition for switching to student login in TabWidget for registering complain
if (getArguments().getInt(ARG_SECTION_NUMBER) == 1) {
HOLIDAY_REQUEST_URL = "http://192.168.43.26/fetch_restricted_holidays.php";
listView_holiday = (ListView)rootView.findViewById(R.id.list);
adapter = new holidayAdapter(activity,new ArrayList<holidays>(),0);
listView_holiday.setAdapter(adapter);
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(1,null,this);
}
//condition for switching to employee login in Tabwidget for registering complain
else {
}
return rootView;
}
#Override
public Loader<List<holidays>> onCreateLoader(int id, Bundle args) {
return new HolidayLoader(activity,HOLIDAY_REQUEST_URL);
}
#Override
public void onLoadFinished(Loader<List<holidays>> loader, List<holidays> holidays) {
adapter.clear();
if(holidays!=null && !holidays.isEmpty()){
adapter.addAll(holidays);
adapter.notifyDataSetChanged();
}
}
#Override
public void onLoaderReset(Loader<List<holidays>> loader) {
adapter.clear();
}
}
/**
* 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 PlaceholderFragment (defined as a static inner class below).
return PlaceholderFragment.newInstance(position + 1);
}
#Override
public int getCount() {
// Show 2 total pages.
return 2;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "Gazetted Holidays";
case 1:
return "Restricted Holidays";
}
return null;
}
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout complainLinearLayout = (LinearLayout)findViewById(R.id.complain_LinearLayout);
complainLinearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent complainIntent = new Intent(MainActivity.this, Complain.class);
startActivity(complainIntent);
}
});
LinearLayout holiday = (LinearLayout)findViewById(R.id.holidays_LinearLayout);
holiday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity( new Intent(MainActivity.this, HolidaysActivity.class));
}
});
}
}
I have created a Tabbed layout in a Activity. My Activity as following point for consideration
1. Number of tabs depends on sorting type available for a Source object. There can be max three tabs i.e. Top, Latest and popular.
2. Each tab contains a GridView and it should be updated when IntentService gets data
3. User can choose the Source from toolbar
4. When new Source is selected, number of tabs should be according to new Source and GridView should also update accordingly
TabbedActivity
public class TabbedActivity extends AppCompatActivity {
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager mViewPager;
private List<Source> allSourceItem;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabbed);
context = this;
// register broadcast
IntentFilter statusIntentFilter = new IntentFilter(Asset.ARTICLE_BROADCAST_ACTION);
TabbedActivity.ArticleStateReceiver mDownloadStateReceiver = new TabbedActivity.ArticleStateReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(mDownloadStateReceiver, statusIntentFilter);
// set toolbar
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// set tab layout
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
// set the viewpager
mViewPager = (ViewPager) findViewById(R.id.container);
// set up page listner to viewpager
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
startSetUp(getRecentDisplayedData());
}
public void startSetUp(Source src){
int tabsCount = 3;
setTitle(src.getName());
tabsCount = getNumberOfTabs(src.getSortByAvailableTop(),src.getSortByAvailableLatest(),src.getSortByAvailablePopular());
setTabs(tabsCount);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
mViewPager.setAdapter(new SectionsPagerAdapter(getSupportFragmentManager(),tabsCount,src));
}
// handle menus of activity
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tabbed, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent intent = new Intent(this, SourcesActivity.class);
intent.putExtra("SOURCE_ACTIVITY_ACTION","TABBED");
startActivity(intent);
return true;
}
if(id == R.id.change_src){
//get all selected sources
allSourceItem = Source.getAll();
List<String> listItems = new ArrayList<String>();
for(int i = 0; i < allSourceItem.size(); i++ ){
listItems.add(allSourceItem.get(i).getName());
}
final CharSequence[] items = listItems.toArray(new CharSequence[listItems.size()]);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.chnage_news_source);
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
Source.updateRecentDisplayed(allSourceItem.get(item));
restartActivity();
}
});
AlertDialog alert = builder.create();
alert.show();
}
return super.onOptionsItemSelected(item);
}
// for creatting tabs Fragments
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private GridView mGridView;
private ArticleAdapter mArticleAdapter;
private ArrayList<Article> mGridData = new ArrayList<Article>();
private TextView tv;
private static final String ARG_SECTION_NUMBER = "section_number";
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
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_tabbed, container, false);
tv = (TextView) rootView.findViewById(R.id.test_tv);
tv.setText("Page counter :: "+getArguments().getInt(ARG_SECTION_NUMBER));
mGridView = (GridView) rootView.findViewById(R.id.article_grid);
update(mGridData);
return rootView;
}
public void update(ArrayList<Article> data){
mArticleAdapter = new ArticleAdapter(getContext(),R.layout.aricle_grid_element,data);
mGridView.setAdapter(mArticleAdapter);
}
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
int tabsCount;
Source src;
public SectionsPagerAdapter(FragmentManager fm, int tabsCount, Source src) {
super(fm);
this.tabsCount = tabsCount;
this.src = src;
}
#Override
public Fragment getItem(int position) {
// getItem is called to instantiate the fragment for the given page.
// Return a PlaceholderFragment (defined as a static inner class below).
if( position == 0){
runArticleService(position+1);
return PlaceholderFragment.newInstance(position + 1);
}else if (position == 1){
runArticleService(position+1);
return PlaceholderFragment.newInstance(position + 1);
}else if (position == 2){
runArticleService(position+1);
return PlaceholderFragment.newInstance(position + 1);
}
return null;
}
#Override
public int getCount() {
// Show 3 total pages.
return tabsCount;
}
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case 0:
return "SECTION 1";
case 1:
return "SECTION 2";
case 2:
return "SECTION 3";
}
return null;
}
private void runArticleService(int tabNumber){
Intent mServiceIntent = new Intent(getBaseContext(), ArticleService.class);
mServiceIntent.setData(Uri.parse(Asset.getSourceArticleURL(src.getUniqueId(),tabNumber)));
startService(mServiceIntent);
}
}
// broadcast receivers handle
private class ArticleStateReceiver extends BroadcastReceiver
{
private ArticleStateReceiver() {
}
// Called when the BroadcastReceiver gets an Intent it's registered to receive
#Override
public void onReceive(Context context, Intent intent) {
String response = intent.getStringExtra(Asset.ARTICLE_EXTENDED_DATA_TYPE);
String sortType = intent.getStringExtra(Asset.ARTICLE_EXTENDED_DATA_SORT);
if(sortType.equals("TOP")){
SectionsPagerAdapter sectionsPagerAdapter = (SectionsPagerAdapter) mViewPager.getAdapter();
PlaceholderFragment placeholderFragment = (PlaceholderFragment) sectionsPagerAdapter.getItem(0);
placeholderFragment.update(Asset.getArticleObjectFromJSON(response.toString()));
}else if(sortType.equals("LATEST")){
SectionsPagerAdapter sectionsPagerAdapter = (SectionsPagerAdapter) mViewPager.getAdapter();
PlaceholderFragment placeholderFragment = (PlaceholderFragment) sectionsPagerAdapter.getItem(1);
placeholderFragment.update(Asset.getArticleObjectFromJSON(response.toString()));
}else if(sortType.equals("POPULAR")){
SectionsPagerAdapter sectionsPagerAdapter = (SectionsPagerAdapter) mViewPager.getAdapter();
PlaceholderFragment placeholderFragment = (PlaceholderFragment) sectionsPagerAdapter.getItem(2);
placeholderFragment.update(Asset.getArticleObjectFromJSON(response.toString()));
}
}
}
// Extra methods
private int getNumberOfTabs(boolean top, boolean latest, boolean popular ){
if( top && latest && popular){
return 3;
}else if( top && latest && !popular ){
return 2;
}else if( top && !latest && !popular ){
return 1;
}else{
return 1;
}
}
private void setTabs(int tabCount){
tabLayout.removeAllTabs();
if(tabCount == 3){
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_1_text)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_2_text)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_3_text)));
}
if(tabCount == 2){
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_1_text)));
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_2_text)));
}
if(tabCount == 1){
tabLayout.addTab(tabLayout.newTab().setText(getString(R.string.tab_1_text)));
}
}
private Source getRecentDisplayedData(){
Source src = Source.getRecentDisplayed();
if(src!=null){
return src;
}else{
src = Source.getRandom();
Source.updateRecentDisplayed(src);
return Source.getRecentDisplayed();
}
}
public void restartActivity(){
Intent myIntent = new Intent(this, TabbedActivity.class);
startActivity(myIntent);
finish();
}
}
IntentService
public class ArticleService extends IntentService {
public String responseStr = null;
public String urlStr = null;
public ArticleService() {
super("ArticleService");
}
#Override
protected void onHandleIntent(Intent intent) {
Uri url = intent.getData();
urlStr = url.toString();
responseStr = Asset.fetchSourceDataFromURL(urlStr);
sendBroadcast();
}
protected void sendBroadcast(){
Intent localIntent = new Intent(Asset.ARTICLE_BROADCAST_ACTION).putExtra(Asset.ARTICLE_EXTENDED_DATA_TYPE,responseStr);
if(urlStr.toLowerCase().contains(Asset.SORT_TOP_URL.toLowerCase())){
localIntent.putExtra(Asset.ARTICLE_EXTENDED_DATA_SORT,"TOP");
}else if (urlStr.toLowerCase().contains(Asset.SORT_LATEST_URL.toLowerCase())){
localIntent.putExtra(Asset.ARTICLE_EXTENDED_DATA_SORT,"LATEST");
}else if (urlStr.toLowerCase().contains(Asset.SORT_POPULAR_URL.toLowerCase())){
localIntent.putExtra(Asset.ARTICLE_EXTENDED_DATA_SORT,"POPULAR");
}
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
}
}
Error that I am not able to understand
01-26 07:57:29.789 1494-1494/in.co.yogender.newsnick.newsnick E/AndroidRuntime: FATAL EXCEPTION: main
Process: in.co.yogender.newsnick.newsnick, PID: 1494
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.content.Context.getSystemService(java.lang.String)' on a null object reference
at android.view.LayoutInflater.from(LayoutInflater.java:232)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:181)
at android.widget.ArrayAdapter.<init>(ArrayAdapter.java:166)
at in.co.yogender.newsnick.newsnick.Adapters.ArticleAdapter.<init>(ArticleAdapter.java:0)
at in.co.yogender.newsnick.newsnick.TabbedActivity$PlaceholderFragment.update(TabbedActivity.java:197)
at in.co.yogender.newsnick.newsnick.TabbedActivity$ArticleStateReceiver.onReceive(TabbedActivity.java:273)
at android.support.v4.content.LocalBroadcastManager.executePendingBroadcasts(LocalBroadcastManager.java:297)
at android.support.v4.content.LocalBroadcastManager.access$000(LocalBroadcastManager.java:46)
at android.support.v4.content.LocalBroadcastManager$1.handleMessage(LocalBroadcastManager.java:116)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6077)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Thanks in advance
I think, you are updating GridView from IntentService where Context is null. Try to pull context from IntentService like below and let me know.
public void update(Context cont, ArrayList<Article> data){
mArticleAdapter = new ArticleAdapter(cont, R.layout.aricle_grid_element,data);
mGridView.setAdapter(mArticleAdapter);
}