Missing data depending on the number of tabs - java

I want to create multiple tabs depending on number of items retained from API. I have successfully created tabs, and swiping over is working fine, but the issue is that for instance, let's say I have 3 tabs. When they are all created, first and second tabs are empty, and the third has data, when I swipe back to 1, I see the data loaded too, but never on the second tab. When the tabs are 2, neither show data. Here is my code:
Activity
public class MenuActivity extends AppCompatActivity {
private ViewPager tabsPager;
private Toolbar toolbar;
private ImageView toolbarImageView;
private TextView subTitleView, titleView, priceCounterView, itemsCounterView;
private RatingBar ratingBar;
private TabLayout tabLayout;
private LinearLayout cartButton;
private AVLoadingIndicatorView avi;
private MenuPagerAdapter tabsAdapter;
public List<MenuType> menuTypes = new ArrayList<>();
public List<MenuItem> menuItems = new ArrayList<>();
private Restaurant restaurant;
private Context context;
private CollapsingToolbarLayout collapsingToolbarLayout;
private AppBarLayout appBarLayout;
private int i = -1;
public List<Fragment> fragments = new ArrayList<>();
private int cartCount = 0;
private int priceCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
context = this;
tabsPager = (ViewPager) findViewById(R.id.tabs_pager);
toolbar = (Toolbar) findViewById(R.id.toolbar);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
avi = (AVLoadingIndicatorView) findViewById(R.id.avi);
titleView = (TextView) findViewById(R.id.titleView);
subTitleView = (TextView) findViewById(R.id.subTitle);
ratingBar = (RatingBar) findViewById(R.id.ratingBar);
toolbarImageView = (ImageView) findViewById(R.id.restoIcon_toolbar);
appBarLayout = (AppBarLayout) findViewById(R.id.app_bar);
collapsingToolbarLayout = (CollapsingToolbarLayout) findViewById(R.id.toolbar_layout);
priceCounterView = (TextView) findViewById(R.id.items_price_counter);
itemsCounterView = (TextView) findViewById(R.id.items_counter);
cartButton = (LinearLayout) findViewById(R.id.view_order_button);
if (cartCount == 0 && priceCount == 0){
cartButton.setVisibility(View.GONE);
}
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
tabsPager.setCurrentItem(0);
restaurant = (Restaurant) getIntent().getSerializableExtra("restaurant");
collapsingToolbarLayout.setExpandedTitleColor(getResources().getColor(R.color.totalTransparent));
getSupportActionBar().setTitle(restaurant.getName());
titleView.setText(restaurant.getName());
subTitleView.setText(restaurant.getSlogan());
ratingBar.setRating(Float.parseFloat(restaurant.getRating()));
Picasso.with(context)
.load(restaurant.getImageURL())
.placeholder(R.drawable.restaurant_placeholder)
.into(toolbarImageView);
loadMenuTypes();
}
//LOAD MENU TYPES
public void loadMenuTypes(){
RequestQueue queue = Volley.newRequestQueue(this);
String url = getResources().getString(R.string.api) + "get-menu-types";
final StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("menu_types");
for (int i = 0; i < array.length(); i++){
JSONObject restoMainMenu = array.getJSONObject(i);
if (restoMainMenu.getBoolean("hasData")) {
MenuType menuType = new MenuType();
menuType.setMenuIcon(restoMainMenu.getString("icon"));
menuType.setRestaurant(restaurant);
menuType.setRmenu(restoMainMenu.getString("title"));
menuType.setMenuId(restoMainMenu.getString("id"));
menuTypes.add(menuType);
}
}
} catch (JSONException e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
loadMenuItems();
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
menuTypes.clear();
menuItems.clear();
loadMenuTypes();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("UID", restaurant.getId());
return params;
}
};
queue.add(postRequest);
}
//LOAD MENUS
public void loadAllMenu(final MenuType mMenuType){
RequestQueue queue = Volley.newRequestQueue(this);
String url = getResources().getString(R.string.api) + "get-all-menu";
StringRequest postRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>()
{
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray array = jsonObject.getJSONArray("detailed_menus");
List<MenuItem> menuItems1 = new ArrayList<>();
for (int i = 0; i< array.length(); i++){
JSONObject restoDetailMenu = array.getJSONObject(i);
MenuItem item = new MenuItem(
restaurant.getId(),
restoDetailMenu.getString("Name"),
restoDetailMenu.getString("id"),
restoDetailMenu.getString("Price"),
restoDetailMenu.getString("Description"),
restoDetailMenu.getString("AvailableIn"),
restoDetailMenu.getString("Icon")
);
menuItems.add(item);
menuItems1.add(item);
}
mMenuType.setMenuItems(menuItems1);
}
catch (JSONException e) {
Toast.makeText(context, e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError error) {
loadAllMenu(menuTypes.get(i));
Toast.makeText(context, error.getMessage(), Toast.LENGTH_SHORT).show();
}
}
) {
#Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
params.put("MenuTypeId", mMenuType.getMenuId());
params.put("restId", mMenuType.getRestaurant().getId());
return params;
}
};
queue.add(postRequest);
}
//TRIGER ALL MENU LOADER
public void loadMenuItems(){
for (int j = 0; j < menuTypes.size(); j++) {
i = j;
loadAllMenu(menuTypes.get(j));
}
avi.setVisibility(View.GONE);
setUpTabs();
}
public void setUpTabs(){
for (int j = 0; j < menuTypes.size(); j++) {
tabLayout.addTab(tabLayout.newTab().setText(menuTypes.get(j).getRmenu()));
MenuFragment fragment = new MenuFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("data", menuTypes.get(j));
fragment.setArguments(bundle);
fragments.add(MenuFragment.newInstance(menuTypes.get(j)));
}
tabsAdapter = new MenuPagerAdapter(getSupportFragmentManager(), menuTypes);
tabsAdapter.notifyDataSetChanged();
tabsPager.setAdapter(tabsAdapter);
tabLayout.setupWithViewPager(tabsPager);
tabsPager.setAdapter(tabsAdapter);
}
public void addedToCart(int price){
priceCount = priceCount + price;
cartCount = cartCount + 1;
if (cartCount > 0 && priceCount > 0){
if (cartCount == 1){
itemsCounterView.setText( String.valueOf(cartCount) + " item");
} else {
itemsCounterView.setText( String.valueOf(cartCount) + " items");
}
priceCounterView.setText(String.valueOf(priceCount) + " RWF");
cartButton.setVisibility(View.VISIBLE);
} else {
cartButton.setVisibility(View.GONE);
}
}
#Override
public boolean onSupportNavigateUp() {
onBackPressed();
return true;
}
}
PagerAdapter
public class MenuPagerAdapter extends FragmentStatePagerAdapter {
private List<MenuType> menuTypes;
public MenuPagerAdapter(FragmentManager fm, List<MenuType> menuTypes) {
super(fm);
this.menuTypes = menuTypes;
}
#Override
public Fragment getItem(int position) {
return MenuFragment.newInstance(menuTypes.get(position));
}
#Override
public int getCount() {
return menuTypes.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return menuTypes.get(position).getRmenu();
}
}
Fragment
public class MenuFragment extends Fragment {
#BindView(R.id.menuRecyclerView) RecyclerView menuRecyclerView;
#BindView(R.id.avi) AVLoadingIndicatorView avi;
private MenuType menuType;
private Bundle args;
private MenuAdapter adapter;
private Context context;
private int position;
public MenuFragment() {
// Required empty public constructor
}
public static MenuFragment newInstance(MenuType mMenuType){
MenuFragment fragment = new MenuFragment();
Bundle args = new Bundle();
args.putSerializable("data", mMenuType);
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_menu, container, false);
ButterKnife.bind(this, view);
context = container.getContext();
menuRecyclerView.setHasFixedSize(true);
menuRecyclerView.setLayoutManager(new LinearLayoutManager(context));
adapter = new MenuAdapter(menuType.getMenuItems(), context);
menuRecyclerView.setAdapter(adapter);
avi.setVisibility(View.GONE);
setData();
return view;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
args = getArguments();
menuType = (MenuType) args.getSerializable("data");
}
public MenuType getMenuType() {
return menuType;
}
public void setMenuType(MenuType menuType) {
this.menuType = menuType;
}
public void setData(){
adapter = new MenuAdapter(menuType.getMenuItems(), getActivity());
menuRecyclerView.setAdapter(adapter);
avi.setVisibility(View.GONE);
}
}
As it is seen, I'm loading MenuTypes(List) first, then for each MenuType, I load all associated items (MenuItems) List too. I, then, create Tabs with respect to the number of MenuTypes, and then create instances of the MenuFragment with respect to the number of MenuItems in the list, and the for each instance of MenuFragment, I just list MenuItems for particular MenuType in a RecyclerView(which is working fine). I tried to add a static TextView in the MenuFragment, and it was shown every time, on all tabs, but the actual data I want are not shown. I also tried a temporary solution to manually set Data I want to each created fragment from the Activity in OnPageChangeListener, but it was not directly working on the first tab until I first navigate to any other tab, which made me to opt out the strategy. Any help is much appreciated. Screenshots are also included for reference.
When tabs are 2 (Screenshot)
When tabs are 2 (Screenshot)
3 tabs, at first, the tab 1 is empty (Screenshot)
3 tabs, last tab has data (Screenshot)
3 tabs, After navigating tabs, the tab 1 also got data (Screenshot)
3 tabs, tab 2 never gets data (Screenshot)

The answer is to use the newInstance() function of the Fragment, and pass everything you want initially as arguments.

Related

Android Restful API retrofit fetching data on Create method but not display

Here is complete code
(In first activity two values are taken from spinner and through a function data sent to second activity)
First Activity:
public class FindBloodActivity extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
TextView t;
Spinner spbgid;
Spinner spcityid;
ProgressBar pro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_blood);
t = (TextView) findViewById(R.id.tv);
pro=(ProgressBar) findViewById(R.id.progressBar2);
pro.setVisibility(View.INVISIBLE);
spbgid=(Spinner) findViewById(R.id.spinnerBG);
spcityid=(Spinner) findViewById(R.id.spinnerLocation);
t.setVisibility(View.INVISIBLE);
}
public void SearchOn(View v) {
String BGId = Integer.toString(spbgid.getSelectedItemPosition()+1);
String CityId =Integer.toString(spcityid.getSelectedItemPosition()+1);
Intent intent=new Intent(getApplicationContext(),SearchResult2.class);
intent.putExtra("bid",BGId);
intent.putExtra("cid",CityId);
startActivity(intent);
}
}
Second Activity: In second activity on tt.append(string.toString()); working fine, but when i add below code than application terminated if i try to debug than also application terminate.
public class SearchResult2 extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
Spinner sp;
TextView t;
TextView tt;
public int totalUsersCount = 0;
String[] allUserNames;
String[] allUserContacts;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result2);
tt=(TextView)findViewById(R.id.tvTest);
tt.setVisibility(View.INVISIBLE);
Bundle extras = getIntent().getExtras();
String BGId = extras.getString("bid");
String CityId = extras.getString("cid");
tt.setText("");
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API).build();
final gitapi git = restAdapter.create(gitapi.class);
git.SearchUsers(BGId, CityId, new Callback<String>() {
#Override
public void success(String string, Response response) {
tt.append(string.toString());
}
#Override
public void failure(RetrofitError retrofitError) {
tt.setText("No User Found");
}
});
String bigArray = tt.getText().toString();
listView = (ListView)findViewById(R.id.lvUsers);
bigArray = bigArray.substring(0, bigArray.length() - 1);
totalUsersCount = bigArray.split(",").length;
listView.clearTextFilter();
if (totalUsersCount > 0)
{
String[] allUsers = new String[totalUsersCount];
allUsers = bigArray.split(",");
allUserNames = new String[totalUsersCount];
allUserContacts = new String[totalUsersCount];
String[] temp = new String[3];
for (int i = 0; i < totalUsersCount; i++) {
temp = allUsers[i].split("-");
allUserNames[i] = temp[1];
allUserContacts[i] = temp[2];
}
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, allUserNames);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SendSMS(position);
}
});
}
}
}
This is log
02-08 12:40:51.433 9970-10008/com.example.abdulqadir.bd I/OpenGLRenderer: Initialized EGL, version 1.4
02-08 12:40:51.457 9970-10008/com.example.abdulqadir.bd W/linker: /vendor/lib64/libhwuibp.so: unused DT entry: type 0xf arg 0xe3a
02-08 12:40:51.458 9970-9970/com.example.abdulqadir.bd W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
02-08 12:40:51.548 9970-10008/com.example.abdulqadir.bd E/hwaps: APS: SSR : The platform cannot support SSR !: 0x0,0x0,8
This code below is working fine for me but when i changed this to above than getting errors, here is code please check
public class FindBloodActivity extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
TextView t;
Spinner spbgid;
Spinner spcityid;
ProgressBar pro;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_blood);
t = (TextView) findViewById(R.id.tv);
pro=(ProgressBar) findViewById(R.id.progressBar2);
pro.setVisibility(View.INVISIBLE);
spbgid=(Spinner) findViewById(R.id.spinnerBG);
spcityid=(Spinner) findViewById(R.id.spinnerLocation);
t.setVisibility(View.INVISIBLE);
}
public void SearchOn(View v) {
String BGId = Integer.toString(spbgid.getSelectedItemPosition()+1);
String CityId =Integer.toString(spcityid.getSelectedItemPosition()+1);
SearchAllUsers(BGId.toString(), CityId.toString());
}
public void SearchAllUsers(String BGId,String CityId) {
t.setText("");
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API).build();
final gitapi git= restAdapter.create(gitapi.class);
git.SearchUsers(BGId,CityId,new Callback<String>() {
#Override
public void success(String string, Response response) {
t.append(string.toString());
}
#Override
public void failure(RetrofitError retrofitError) {
t.setText("No User Found");
}
});
}
public void Search(View v){
try {
Thread.sleep(9000);
Intent intent=new Intent(getApplicationContext(),SearchResult.class);
intent.putExtra("users",t.getText().toString());
startActivity(intent);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Second Activity:
public class SearchResult2 extends AppCompatActivity {
String API = "http://abdolqadir-001-site1.ctempurl.com/Account.svc";
Spinner sp;
TextView t;
TextView tt;
public int totalUsersCount = 0;
String[] allUserNames;
String[] allUserContacts;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_result2);
tt=(TextView)findViewById(R.id.tvTest);
tt.setVisibility(View.INVISIBLE);
Bundle extras = getIntent().getExtras();
String BGId = extras.getString("bid");
String CityId = extras.getString("cid");
tt.setText("");
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API).build();
final gitapi git = restAdapter.create(gitapi.class);
git.SearchUsers(BGId, CityId, new Callback<String>() {
#Override
public void success(String string, Response response) {
tt.append(string.toString());
}
#Override
public void failure(RetrofitError retrofitError) {
tt.setText("No User Found");
}
});
String bigArray = tt.getText().toString();
listView = (ListView)findViewById(R.id.lvUsers);
bigArray = bigArray.substring(0, bigArray.length() - 1);
totalUsersCount = bigArray.split(",").length;
listView.clearTextFilter();
if (totalUsersCount > 0)
{
String[] allUsers = new String[totalUsersCount];
allUsers = bigArray.split(",");
allUserNames = new String[totalUsersCount];
allUserContacts = new String[totalUsersCount];
String[] temp = new String[3];
for (int i = 0; i < totalUsersCount; i++) {
temp = allUsers[i].split("-");
allUserNames[i] = temp[1];
allUserContacts[i] = temp[2];
}
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, allUserNames);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SendSMS(position);
}
});
}
}
Here are the things you can try, use this code in onCreate()
listView = (ListView)findViewById(R.id.lvUsers);
ArrayAdapter<String> itemsAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, allUserNames);
listView.setAdapter(itemsAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SendSMS(position);
}
});
and where you were using the above code before replace it with i.e of inside of if condition
itemsAdapter.notifyDatasetChanged();
Hope this helps
Why not do your REST call from the onCreate() method?
Also component.setVisibility(View.INVISIBLE); retains space in the overall layout. You could use 'GONE' instead and see if that helps or hurts.
And try have your URL and other components in different methods or classes. This can help a WHOLE LOT to keep the code clean and easy to find errors.
With all this said, after using breakpoints and running in debug mode which line is the error?

Attempt to invoke virtual method 'java.lang.Object android.app.Activity.getSystemService(java.lang.String)' on a null object reference [duplicate]

This question already has answers here:
Android. Fragment getActivity() sometimes returns null
(8 answers)
Closed 6 years ago.
this is my code:
public class LatestPostFragment extends Fragment {
private static final String TAG = LatestPostFragment.class.getSimpleName();
View rootView;
LinearLayout grid_view_wrapper;
private ViewPager viewPager;
private MyViewPagerAdapter myViewPagerAdapter;
private LinearLayout layout_dots;
private TextView[] dots;
private Integer viewPagerLength;
Typeface font;
ArrayList<Post>viewPagerItems = new ArrayList<Post>();
private List<Category> categoriesList;
public LatestPostFragment() {}
#Override
public void onResume() {
super.onResume();
//Get a Tracker (should auto-report)
if (Const.Analytics_ACTIVE) {
AnalyticsUtil.sendScreenName(getActivity(), TAG);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_latest, container, false);
//Forcing RTL Layout, If Supports and Enabled from Const file
Utils.forceRTLIfSupported(getActivity());
grid_view_wrapper = (LinearLayout) rootView.findViewById(R.id.grid_view_wrapper);
font = Typeface.createFromAsset(getActivity().getAssets(), "fonts/iran_sans.ttf");
ConnectionDetector cd = new ConnectionDetector(this.getActivity());
Boolean isInternetPresent = cd.isConnectingToInternet();
if (isInternetPresent) {
getFeaturedPosts();
categoriesList = AppController.getInstance().getPrefManger().getFeaturedCategories();
for (Category a : categoriesList) {
getLatestPosts(a.getId());
}
}
return rootView;
}
private void getFeaturedPosts(){
String featured_url = Const.URL_BLOG + Const.URL_BLOG_API + Const.URL_FEATURED + "?t=" + System.currentTimeMillis();
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET, featured_url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null) {
try {
if (response.has("error")) {
String error = response.getString("error");
Toast.makeText(getActivity().getApplicationContext(), error, Toast.LENGTH_LONG).show();
}else {
if (response.isNull("feed")) {
}else{
viewPagerLength = response.getInt("total_items");
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
Post item = new Post();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
item.setCategory(feedObj.getString("category"));
String image = feedObj.isNull("image_big") ? null : feedObj.getString("image_big");
item.setImge(image);
item.setTimeStamp(feedObj.getString("timeStamp"));
item.setAuthor(feedObj.getString("author"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj.getString("url");
item.setUrl(feedUrl);
viewPagerItems.add(item);
}
setupViewPager();
}
}
}catch (JSONException es) {
es.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "Featured: " + getString(R.string.unknown_error), Toast.LENGTH_LONG).show();
}
}else{
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/** Passing some request headers **/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("ApiKey", Const.AuthenticationKey);
return headers;
}
};
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
public void setupViewPager(){
layout_dots = (LinearLayout) rootView.findViewById(R.id.layout_dots);
viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
addBottomDots(0);
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
myViewPagerAdapter = new MyViewPagerAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
}
private void addBottomDots(int currentPage) {
dots = new TextView[viewPagerLength];
layout_dots.removeAllViews();
for (int i = 0; i < Const.FeaturedView; i++) {
dots[i] = new TextView(getActivity());
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(getResources().getColor(R.color.viewpager_inactive));
layout_dots.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(getResources().getColor(R.color.viewpager_active));
}
public class MyViewPagerAdapter extends PagerAdapter {
private LayoutInflater layoutInflater;
public MyViewPagerAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.viewpager_item, container, false);
final Post p = viewPagerItems.get(position);
TextView name = (TextView) view.findViewById(R.id.name);
name.setTypeface(font);
name.setTextSize(20);
name.setText(Html.fromHtml(p.getName()));
TextView category = (TextView) view.findViewById(R.id.category);
category.setText(Html.fromHtml(p.getCategory()));
ImageView img = (ImageView) view.findViewById(R.id.feedImage1);
Picasso.with(getActivity()).load(p.getImge()).into(img);
//TextView post_author = (TextView) view.findViewById(R.id.post_author);
//post_author.setText(String.format(getString(R.string.post_by), Html.fromHtml(p.getAuthor())));
CharSequence timeAgo = DateUtils.getRelativeTimeSpanString(
Long.parseLong(p.getTimeStamp()),
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS);
TextView timestamp = (TextView) view.findViewById(R.id.timestamp);
// amin time
DateTime dateTime = new DateTime(Long.parseLong(p.getTimeStamp()));
dateTime.withZone(DateTimeZone.forID("Asia/Tehran"));
Roozh jCal = new Roozh();
jCal.GregorianToPersian(dateTime.getYear(), dateTime.getMonthOfYear(), dateTime.getDayOfMonth());
CharSequence timeAmin = jCal.toString();
// view time
if(System.currentTimeMillis() - Long.parseLong(p.getTimeStamp())<604800000)
timestamp.setText(String.format(getString(R.string.publish_on), timeAgo));
else
timestamp.setText(String.format(getString(R.string.publish_on), timeAmin));
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent();
i.setClass(getActivity(), PostViewActivity.class);
i.putExtra(PostViewActivity.TAG_SEL_POST_ID, "P" + p.getId());
i.putExtra(PostViewActivity.TAG_SEL_POST_TITLE, p.getName());
startActivity(i);
}
});
container.addView(view);
return view;
}
#Override
public int getCount() {
return viewPagerItems.size();
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
private void getLatestPosts(final String category_id){
String featured_url = Const.URL_BLOG + Const.URL_BLOG_API + Const.URL_FEATURED_CATEGORY_POST.replace("_CAT_ID_", category_id) + "?t=" + System.currentTimeMillis();
Log.d(TAG, featured_url);
// making fresh volley request and getting json
JsonObjectRequest jsonReq = new JsonObjectRequest(Request.Method.GET, featured_url, null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
if (response != null) {
try {
if (response.has("error")) {
String error = response.getString("error");
Toast.makeText(getActivity().getApplicationContext(), error, Toast.LENGTH_LONG).show();
}else {
if (response.isNull("feed")) {
}else{
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.gridview_category, null, false);
final TextView category_button = (TextView) view.findViewById(R.id.btnCategory);
final String category_name = response.getString("category");
TextView category_title = (TextView) view.findViewById(R.id.category_title);
category_title.setText(Html.fromHtml(category_name));
category_title.setTypeface(font);
category_title.setTextSize(20);
category_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(category_name);
Fragment fragment = GridFragment.newInstance(GridFragment.PageType.CATEGORY, category_id, category_name);
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).commit();
}
});
LinearLayout hsv = (LinearLayout) view.findViewById(R.id.recycler_view);
JSONArray feedArray = response.getJSONArray("feed");
for (int i = 0; i < feedArray.length(); i++) {
JSONObject feedObj = (JSONObject) feedArray.get(i);
View lvg = layoutInflater.inflate(R.layout.listview_item_grid, null, false);
TextView post_name = (TextView) lvg.findViewById(R.id.post_name);
post_name.setText(Html.fromHtml(feedObj.getString("name")));
ImageView img = (ImageView) lvg.findViewById(R.id.feedImage1);
Picasso.with(getActivity()).load(feedObj.getString("image_big")).into(img);
final Post item = new Post();
item.setId(feedObj.getInt("id"));
item.setName(feedObj.getString("name"));
/*item.setCategory(feedObj.getString("category"));
String image = feedObj.isNull("image_big") ? null : feedObj.getString("image_big");
item.setImge(image);
item.setTimeStamp(feedObj.getString("timeStamp"));
// url might be null sometimes
String feedUrl = feedObj.isNull("url") ? null : feedObj.getString("url");
item.setUrl(feedUrl);
postList.add(item);*/
lvg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent();
i.setClass(getActivity(), PostViewActivity.class);
i.putExtra(PostViewActivity.TAG_SEL_POST_ID, "P" + item.getId());
i.putExtra(PostViewActivity.TAG_SEL_POST_TITLE, item.getName());
startActivity(i);
}
});
hsv.addView(lvg);
}
grid_view_wrapper.addView(view);
}
}
}catch (JSONException es) {
es.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), getString(R.string.unknown_error), Toast.LENGTH_LONG).show();
}
}else{
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/** Passing some request headers **/
#Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json");
headers.put("ApiKey", Const.AuthenticationKey);
return headers;
}
};
// Adding request to volley request queue
AppController.getInstance().addToRequestQueue(jsonReq);
}
}
I have an error in this line:
LayoutInflater layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE)
Throwing this:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.Object android.app.Activity.getSystemService(java.lang.String)' on a null object reference
Well your getActivity() can return null if the context is lost after a long running background call like when running your jsonRequest.
Maybe the user clicks the home button while the request is running, and when it returns in the onResponse method, the activity is already destroyed, thus the getActivity() call returns a null object.
There are multiple solutions to this; easiest is a null check after the getActivity() return. Also you could check this stackoverflow question
I would suggest giving a Context to the PagerAdapter
public class MyViewPagerAdapter extends PagerAdapter {
private Context mContext;
public MyViewPagerAdapter(Context ctx) {
this.mContext = ctx;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = LayoutInflater.from(mContext);
View view = inflater.inflate(R.layout.viewpager_item, container, false);
Now, you can use that class from any context, but from the Fragment, you do
myViewPagerAdapter = new MyViewPagerAdapter(getActivity());
Though, this may still be null for alternative reasons.

OnItemClicklistener on list adapter that populate its items from database

I have a list view that implement swipelistadapter and app controller. The list view display correctly from the database, the only thing I need is to get position of each item and assign intent activity on each. These are my codes
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rows, null);
TextView serial = (TextView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
serial.setText(String.valueOf(movieList.get(position).id));
title.setText(movieList.get(position).title);
String color = bgColors[position % bgColors.length];
serial.setBackgroundColor(Color.parseColor(color));
return convertView;
}
}
Below Class is the main activity
public class Tab1 extends Fragment implements ViewSwitcher.ViewFactory, SwipeRefreshLayout.OnRefreshListener {
private int index;
private int[] images = new int[] { R.drawable.gallery1, R.drawable.gallery2, R.drawable.gallery3, R.drawable.gallery4, R.drawable.gallery5, R.drawable.gallery6, R.drawable.gallery7, R.drawable.gallery8 };
ImageSwitcher switcher;
android.os.Handler Handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
// private static final String url = "http://api.androidhive.info/json/movies.json";
private String URL_TOP_250 = "http://192.158.33.172/locator/test/refractor.php?offset=";
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab_1,container,false);
listView = (ListView) v.findViewById(R.id.list);
// Adding request to request queue
//Editted AppController.getInstance().addToRequestQueue(movieReq);
swipeRefreshLayout = (SwipeRefreshLayout) v.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//String selectedFromList = (listView.getItemAtPosition(position).getString());
// String text = movieList[position];
Intent i = new Intent(getActivity(), Tab2.class);
// i.putExtra("TEXT", text);
startActivity(i);
}
});
return v;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
switcher = (ImageSwitcher) getActivity().findViewById(R.id.imageSwitcher1);
switcher.setFactory(this);
switcher.setImageResource(images[index]);
switcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index++;
if (index >= images.length) {
index = 0;
}
switcher.setImageResource(images[index]);
}
});
switcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
//auto change image
Handler.post(UpdateImage);
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Runnable UpdateImage = new Runnable() {
public void run() {
// Increment index
index++;
if (index > (images.length - 1)) {
index = 0;
}
switcher.setImageResource(images[index]);
// Set the execution after 5 seconds
Handler.postDelayed(this, (3 * 1000));
}
};
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(Gallery.LayoutParams.
FILL_PARENT, Gallery.LayoutParams.FILL_PARENT));
return myView;
}
}
Any help will be appreciated. Thanks.
Code for getting a single item:
String singleItem = getItem(position);
this is quite straight forward. here is a modification to your onItemClickListener:
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
String text = movieList.get(position);
Intent i = new Intent(getActivity(), Tab2.class);
i.putExtra("TEXT", text);
startActivity(i);
}
});
just note that movieList object should be the same object you pass to your adapter

Move from a fragment with listview adapter to new activity base on each item selected

I have done some series of research about how to make each item of the listview in fragment activity to move to another activity having getView() from swipeListadapter. The codes below contain the tab fragment containing the swipe listadapter for the list view and the setonitemclicklistener.
public class SwipeListAdapter extends BaseAdapter {
private Activity activity;
private LayoutInflater inflater;
private List<Movie> movieList;
private String[] bgColors;
public SwipeListAdapter(Activity tab1, List<Movie> movieList) {
this.activity = tab1;
this.movieList = movieList;
bgColors = activity.getApplicationContext().getResources().getStringArray(R.array.movie_serial_bg);
}
#Override
public int getCount() {
return movieList.size();
}
#Override
public Object getItem(int location) {
return movieList.get(location);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (inflater == null)
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
convertView = inflater.inflate(R.layout.list_rows, null);
TextView serial = (TextView) convertView.findViewById(R.id.serial);
TextView title = (TextView) convertView.findViewById(R.id.title);
serial.setText(String.valueOf(movieList.get(position).id));
title.setText(movieList.get(position).title);
String color = bgColors[position % bgColors.length];
serial.setBackgroundColor(Color.parseColor(color));
return convertView;
}
}
The code below is my fragment tab class
public class Tab1 extends Fragment implements ViewSwitcher.ViewFactory, SwipeRefreshLayout.OnRefreshListener {
private int index;
private int[] images = new int[] { R.drawable.gallery1, R.drawable.gallery2, R.drawable.gallery3, R.drawable.gallery4, R.drawable.gallery5, R.drawable.gallery6, R.drawable.gallery7, R.drawable.gallery8 };
ImageSwitcher switcher;
android.os.Handler Handler = new Handler();
private SwipeRefreshLayout swipeRefreshLayout;
private SwipeListAdapter adapter;
private List<Movie> movieList;
private ListView listView;
// private static final String url = "http://api.androidhive.info/json/movies.json";
private String URL_TOP_250 = "http://192.177.53.152/locator/test/refractor.php?offset=";
// initially offset will be 0, later will be updated while parsing the json
private int offSet = 0;
private static final String TAG = Tab1.class.getSimpleName();
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View vi = inflater.inflate(R.layout.tab_1,container,false);
listView = (ListView) vi.findViewById(R.id.list);
listView.setBackgroundColor(Color.WHITE);
swipeRefreshLayout = (SwipeRefreshLayout) vi.findViewById(R.id.swipe_refresh_layout);
movieList = new ArrayList<>();
adapter = new SwipeListAdapter(getActivity(), movieList);
listView.setAdapter(adapter);
//getView().setOnClickListener();
swipeRefreshLayout.setOnRefreshListener(this);
swipeRefreshLayout.post(new Runnable() {
#Override
public void run() {
swipeRefreshLayout.setRefreshing(true);
fetchMovies();
}
}
);
return vi;
}
#Override
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
switch(position) {
case 1:
intent = new Intent(getActivity().getApplicationContext(), New1.class);
startActivity(intent);
break;
case 2:
intent = new Intent(getActivity().getApplicationContext(), New2.class);
startActivity(intent);
break;
default:
intent = new Intent(getActivity().getApplicationContext(), New3.class);
startActivity(intent);
}
}
});
switcher = (ImageSwitcher) getActivity().findViewById(R.id.imageSwitcher1);
switcher.setFactory(this);
switcher.setImageResource(images[index]);
switcher.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
index++;
if (index >= images.length) {
index = 0;
}
switcher.setImageResource(images[index]);
}
});
switcher.setInAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_in));
switcher.setOutAnimation(AnimationUtils.loadAnimation(getActivity(), android.R.anim.fade_out));
//auto change image
Handler.post(UpdateImage);
}
#Override
public void onRefresh() {
fetchMovies();
}
private void fetchMovies() {
// showing refresh animation before making http call
swipeRefreshLayout.setRefreshing(true);
// appending offset to url
String url = URL_TOP_250 + offSet;
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, response.toString());
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
int rank = movieObj.getInt("rank");
String title = movieObj.getString("postTitle");
Movie m = new Movie(rank, title);
movieList.add(0, m);
// updating offset value to highest value
if (rank >= offSet)
offSet = rank;
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
adapter.notifyDataSetChanged();
}
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
Toast.makeText(getActivity().getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();
// stopping swipe refresh
swipeRefreshLayout.setRefreshing(false);
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
Runnable UpdateImage = new Runnable() {
public void run() {
// Increment index
index++;
if (index > (images.length - 1)) {
index = 0;
}
switcher.setImageResource(images[index]);
// Set the execution after 5 seconds
Handler.postDelayed(this, (3 * 1000));
}
};
#Override
public View makeView() {
ImageView myView = new ImageView(getActivity());
myView.setScaleType(ImageView.ScaleType.FIT_CENTER);
myView.setLayoutParams(new ImageSwitcher.LayoutParams(Gallery.LayoutParams.
FILL_PARENT, Gallery.LayoutParams.FILL_PARENT));
return myView;
}
}
In a nutshell, whenever I click any of the item listview, the app crashes and system logcat is not giving any clue to that. I want to be able to click an item on the listview in d fragment and to be directed to a new activity. Any help will be appreciated. Thanks.

Android Tabs with same Fragment

I'm trying to implement Tabs. The Tabs will contain the exact same layout and the same fragment with only one difference - the API URL! (e.g. Trending/Newest).
My Code:
TabFragment
public class TabFragments extends Fragment implements OnPageChangeListener,
OnTabChangeListener {
private TabHost tabHost;
private int currentTab = 0;
private ViewPager viewPager;
private TabFragmentPageAdapter pageAdapter;
private List<Fragment> fragments;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.tabhost, null);
tabHost = (TabHost) rootView.findViewById(android.R.id.tabhost);
viewPager = (ViewPager) rootView.findViewById(R.id.viewpager);
viewPager.setOnPageChangeListener(this);
//Create correct fragment
fragments=new ArrayList<>();
fragments.add(new ItemStreamFragment());
fragments.add(new ItemStreamFragment());
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setRetainInstance(true);
pageAdapter = new TabFragmentPageAdapter(getChildFragmentManager(),
fragments);
pageAdapter.notifyDataSetChanged();
viewPager.setAdapter(pageAdapter);
setupTabs();
}
private void setupTabs() {
tabHost.setup();
tabHost.addTab(newTab(R.string.tab_1_item));
tabHost.addTab(newTab(R.string.tab_2_item));
for (int i = 0; i < tabHost.getTabWidget().getChildCount(); i++) {
tabHost.getTabWidget().getChildAt(i)
.setBackgroundColor(Color.parseColor("#304c58"));
// tabHost.setBackgroundResource(R.drawable.tab_selector);
final View view = tabHost.getTabWidget().getChildTabViewAt(i);
final View textView = view.findViewById(android.R.id.title);
((TextView) textView).setTextColor(Color.parseColor("#e2ebf0"));
((TextView) textView).setSingleLine(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
tabHost.getTabWidget().getChildAt(i)
.findViewById(android.R.id.icon);
tabHost.getTabWidget().getChildAt(i).getLayoutParams().height = 75;
} else {
if (view != null) {
// reduce height of the tab
view.getLayoutParams().height *= 0.77;
if (textView instanceof TextView) {
((TextView) textView).setGravity(Gravity.CENTER);
textView.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
textView.getLayoutParams().width = ViewGroup.LayoutParams.WRAP_CONTENT;
}
}
}
}
tabHost.setOnTabChangedListener(TabFragments.this);
tabHost.setCurrentTab(currentTab);
}
private TabSpec newTab(int titleId) {
TabSpec tabSpec = tabHost.newTabSpec(getString(titleId));
tabSpec.setIndicator(getString(titleId));
tabSpec.setContent(new TabFactory(getActivity()));
return tabSpec;
}
#Override
public void onPageScrollStateChanged(int position) {
}
#Override
public void onPageScrolled(int position, float arg1, int arg2) {
}
#Override
public void onPageSelected(int position) {
tabHost.setCurrentTab(position);
}
#Override
public void onTabChanged(String tabId) {
currentTab = tabHost.getCurrentTab();
viewPager.setCurrentItem(currentTab);
}
#SuppressWarnings("unused")
private void updateTab() {
switch (currentTab) {
case 0:
ItemStreamFragment login = (ItemStreamFragment) fragments.get(currentTab);
break;
case 1:
ItemStreamFragment register = (ItemStreamFragment) fragments
.get(currentTab);
break;
}
}
class TabFactory implements TabContentFactory {
private final Context context;
public TabFactory(Context context) {
this.context = context;
}
#Override
public View createTabContent(String tag) {
View v = new View(context);
v.setMinimumHeight(0);
v.setMinimumWidth(0);
return v;
}
}
}
TabFragmentPageAdapter
public class TabFragmentPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public TabFragmentPageAdapter(FragmentManager fm, List<Fragment> fragments
) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
Fragment fragment = fragments.get(position);
Bundle args = new Bundle();
args.putInt("position", position);
fragment.setArguments(args);
return fragment;
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
And finally ItemStreamFragment
public class ItemStreamFragment extends Fragment {
private String mApiUrl = "http://api.eese.com:8080/ICDS_API/v1/reco.getNewest/?page=0&limit=13&timestamp=2015-07-02+10%3A34%3A07&lang_key=en";
private final String mImages = "http://d30q95ofpjr96w.cloudfront.net/";
private ItemStream[] mObjectItem;
private int mPosition = 0;
public ItemStreamAdapter mAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle bundle = getArguments();
if (bundle != null) {
mPosition = bundle.getInt("position", 0);
}
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_itemstream, container, false);
view.setId(mPosition);
getStream(mPosition);
return view;
}
private void getStream(int position) {
switchUrl(position);
new GetRequestTask(new OnTaskCompleted() {
#Override
public void onTaskCompleted(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonResults = jsonObject.getJSONArray("results");
final int resultLength = jsonResults.length();
mObjectItem = new ItemStream[resultLength];
for (int i = 0; i < resultLength; i++) {
JSONObject item = jsonResults.getJSONObject(i);
mObjectItem[i] = new ItemStream(item.getInt("id"), item.getString("title"), mImages + "" + item.getString("thumbnail") + ".374x210." + item.getString("thumbnail_type"));
}
if (getActivity() != null) {
mAdapter = new ItemStreamAdapter(getActivity(), R.layout.list_itemstream, mObjectItem);
ListView scrollView = (ListView) getActivity().findViewById(R.id.itemstream_trend);
scrollView.setAdapter(mAdapter);
}
} catch (Exception ex) {
}
}
}).execute(mApiUrl);
}
//Needs to be tuned
private void switchUrl(int position) {
switch (position) {
case 0:
mApiUrl = "http://api.eese.com:8080/ICDS_API/v1/reco.getTrending/?page=0&limit=13&timestamp=2015-07-02+10%3A34%3A07&lang_key=en";
break;
case 1:
mApiUrl = "http://api.eese.com:8080/ICDS_API/v1/reco.getNewest/?page=0&limit=13&timestamp=2015-07-02+10%3A34%3A07&lang_key=en";
break;
}
}
}
And here you see what happens:
(Sry for the overlay :) )
The thing is that the first Tab is loaded with data but the second tab stays empty (it shouldn't be empty though). Not sure what is wrong here. Would be cool if you can point me in the right direction :)
For using Tabs in material design you should use TabLayout from design support library. Here is the tutorial from where you can learn this new approach.
As far as loading fragment is concern, you second fragment will be loaded with first this is complete different discussion with viewpager, so you need to have different url for each fragment and don't create fragment using new Operator. Instead create static getInstance() in Fragment class and pass the url from there and using Fragment#setArgument(Bundle) get new Fragment instance. When fragment view is created i.e in onViewCreated(...) get arguments from bundle in your case String url and call webservice which will return the respective response.
Fixed the problem:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_itemstream, container, false);
view.setId(mPosition);
getStream(mPosition,view);
return view;
}
private void getStream(int position, final View view) {
switchUrl(position);
new GetRequestTask(new OnTaskCompleted() {
#Override
public void onTaskCompleted(String result) {
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray jsonResults = jsonObject.getJSONArray("results");
final int resultLength = jsonResults.length();
mObjectItem = new ItemStream[resultLength];
for (int i = 0; i < resultLength; i++) {
JSONObject item = jsonResults.getJSONObject(i);
mObjectItem[i] = new ItemStream(item.getInt("id"), item.getString("title"), mImages + "" + item.getString("thumbnail") + ".374x210." + item.getString("thumbnail_type"));
}
if (getActivity() != null) {
mAdapter = new ItemStreamAdapter(getActivity(), R.layout.list_itemstream, mObjectItem);
ListView scrollView = (ListView) view.findViewById(R.id.itemstream_trend);
scrollView.setAdapter(mAdapter);
}
} catch (Exception ex) {
}
}
}).execute(mApiUrl);
}
Just added view to the method getStream. Now it is working! What do you think about this solution?

Categories