How to add item in listview dynamically in android? - java

Hi i know question like this asked before several times but i couldn't find a way to fix my problem.
What i want to do: i want to add items to listview from my mainactivity in swiping page project.
My mainactivity
public class MainActivity extends SherlockFragmentActivity {
// Declare Variables
ActionBar mActionBar;
ViewPager mPager;
Tab tab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from activity_main.xml
setContentView(R.layout.activity_main);
final Context context = getApplicationContext();
for (int s = 0; s < 10; s++) {
Swap.stafu1.add("F" + s);
Swap.stafu2.add("F" + s);
}
// Activate Navigation Mode Tabs
mActionBar = getSupportActionBar();
mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Locate ViewPager in activity_main.xml
mPager = (ViewPager) findViewById(R.id.pager);
// Activate Fragment Manager
FragmentManager fm = getSupportFragmentManager();
// Capture ViewPager page swipes
ViewPager.SimpleOnPageChangeListener ViewPagerListener = new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
// Find the ViewPager Position
mActionBar.setSelectedNavigationItem(position);
if (position == 1) {
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.d("bingo", "clicked" + Swap.stafu1.size());
Swap.stafu1.add("sometext");
Swap.stafu2.add("sometext");
Swap.stafu1.remove(0);
Swap.stafu2.remove(0);
FragmentTab2 f2 = new FragmentTab2();
f2.nDChanged();
}
});
}
}
};
mPager.setOnPageChangeListener(ViewPagerListener);
// Locate the adapter class called ViewPagerAdapter.java
ViewPagerAdapter viewpageradapter = new ViewPagerAdapter(fm);
// Set the View Pager Adapter into ViewPager
mPager.setAdapter(viewpageradapter);
// Capture tab button clicks
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Pass the position on tab click to ViewPager
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
};
// Create first Tab
tab = mActionBar.newTab().setText("Tab1").setTabListener(tabListener);
mActionBar.addTab(tab);
// Create second Tab
tab = mActionBar.newTab().setText("Tab2").setTabListener(tabListener);
mActionBar.addTab(tab);
// Create third Tab
tab = mActionBar.newTab().setText("Tab3").setTabListener(tabListener);
mActionBar.addTab(tab);
}
}
FragmentTab2.java
public class FragmentTab2 extends SherlockFragment {
ListView list;
ListViewAdapter adapter;
#Override
public SherlockFragmentActivity getSherlockActivity() {
return super.getSherlockActivity();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragmenttab2, container,
false);
// Locate the ListView in fragmenttab1.xml
list = (ListView) rootView.findViewById(R.id.listview);
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(getActivity(), Swap.stafu1, Swap.stafu2);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
return rootView;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
setUserVisibleHint(true);
}
public void nDChanged() {
Log.d("bingo", "clicked"+Swap.stafu1.size());
adapter = new ListViewAdapter(getActivity(), Swap.stafu1, Swap.stafu2);
adapter.notifyDataSetChanged();
}
}
Swap.java
public class Swap {
public static ArrayList<String> stafu1=new ArrayList<String>();
public static ArrayList<String> stafu2=new ArrayList<String>();
}
problem: notifyDataSetChanged() dosn't work until i remove one item from listview and that's mean i cant increasing item in listview.
When i don't use notifyDataSetChanged() i can add text to Swap.stafu1 and Swap.stafu1 and that's appear in listview when i swipe page and swipe page back to fragmenttab2.
I guess i need to refresh listview or fragmenttab2 every time i add items on listview. but I don't know how can i do that.
Thanks for any help.

You need emplacement this notifyDataSetChanged() and registerDataSetObserver() method in your listview adapter.
private ArrayList<DataSetObserver> observers = new ArrayList<DataSetObserver>();
public void registerDataSetObserver(DataSetObserver observer) {
observers.add(observer);
}
public void notifyDataSetChanged(){
for (DataSetObserver observer: observers) {
observer.onChanged();
}
}

Related

Starting Fragment method from MainActivity causes Exception

I work on an app which contains Fragments and a ViewPager. I fetch location data in my MainActivity and want to use it inside the fragments, so I created a method to pass the variables and process with them. Unfortunately I get a NullPointerException on all view objects, like the progressBar or the CollapsingToolbarLayout inside of the Fragment when the method is called. I guess the fragment is not correctly started just by calling a method, but how can I change it, so the view objects are created? Or is there another way to first fetch location data and use it inside the fragments afterwards?
My MainActivity:
public class MainActivity extends AppCompatActivity implements Serializable {
private ViewPager viewPager;
BottomNavigationView bottomNavigationView;
FragmentA FragmentA;
FragmentB FragmentB;
FragmentC FragmentC;
MenuItem prevMenuItem;
public double lat;
public double lon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.viewpager);
bottomNavigationView = (BottomNavigationView)findViewById(R.id.bottom_navigation);
bottomNavigationView.setOnNavigationItemSelectedListener(
new BottomNavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.navigation_umkreis:
viewPager.setCurrentItem(0);
break;
case R.id.navigation_karte:
viewPager.setCurrentItem(1);
break;
case R.id.navigation_einstellungen:
viewPager.setCurrentItem(2);
break;
}
return false;
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
if (prevMenuItem != null) {
prevMenuItem.setChecked(false);
}
else
{
bottomNavigationView.getMenu().getItem(0).setChecked(false);
}
Log.d("page", "onPageSelected: "+position);
bottomNavigationView.getMenu().getItem(position).setChecked(true);
prevMenuItem = bottomNavigationView.getMenu().getItem(position);
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
setupViewPager(viewPager);
}
private void setupViewPager(ViewPager viewPager) {
ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
callsFragment = new CallsFragment();
chatFragment = new ChatFragment();
contactsFragment = new ContactsFragment();
adapter.addFragment(callsFragment);
adapter.addFragment(chatFragment);
adapter.addFragment(contactsFragment);
viewPager.setAdapter(adapter);
int limit = adapter.getCount();
viewPager.setOffscreenPageLimit(limit);
}
public void start() {
//Location data fetched here
FragmentB fb = new FragmentB();
fb.start(lat, lon);
}
}
My FragmentB:
public class FragmentB extends Fragment {
private ProgressBar progressBar;
private double lat;
private double lon;
String title;
private BaseAdapter mItemsAdapter;
private final List<HashMap<String, String>> mItemList = new ArrayList<>();
ArrayList<HashMap<String, String>> resultList = new ArrayList<>();
public FragmentB() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_b, container, false);
progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
progressBar.setVisibility(View.VISIBLE);
((ListView) view.findViewById(R.id.list))
.setAdapter(mItemsAdapter);
return view;
}
public void start(double latGet, double lonGet){
lat = latGet;
lon = lonGet;
new GetContacts().execute();
}
private class GetContacts extends AsyncTask<Void, Void, Void>{
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
}
#Override
protected Void doInBackground(Void... arg0) {
//Fetch And Process Data -> Result into resultList
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
final CollapsingToolbarLayout collapsingToolbarLayout = (CollapsingToolbarLayout) getActivity().findViewById(R.id.toolbar_layout);
AppBarLayout appBarLayout = (AppBarLayout) getActivity().findViewById(R.id.appBar);
progressBar.setVisibility(View.GONE);
//Updating parsed JSON data into ListView
mItemsAdapter = new SimpleAdapter(
getActivity(), mItemList,
R.layout.list_item, new String[]{"brand", "price",
"dist", "street", "houseNumber", "postcode", "place"}, new int[]{R.id.brand,
R.id.price, R.id.dist, R.id.street, R.id.houseNumber, R.id.postCode, R.id.place});
mItemList.addAll(resultList);
mItemsAdapter.notifyDataSetChanged();
}
}
}
In the following method from MainActivity, you try to pass the location data to an instance of FragmentB:
public void start() {
//Location data fetched here
FragmentB fb = new FragmentB();
fb.start(lat, lon);
}
The resulting crash is due to the fact that you only instantiate the Fragment, nothing else. Methods like onCreateView() or onAttach() will only be called if the Fragment is (about to be) added to the View hierarchy. So for this instance of FragmentB, methods like getContext() or getActivity() will return null. That's why you get NullPointerExceptions.
Make sure that you only call start() on a Fragment which has been added to the View hierarchy. Or modify the method so that it stores the location data in some appropriate structure which can be accessed from e.g. onViewCreated(), onStart() or onResume()
See the docs for more information on the Fragment lifecycle

How to make FloatingActionButton take you to specific tab in Tab Layout

I have a FloatingActionButton in my android navigation drawer with tablayout which displays the following message :
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
homeFragment();
SnackBarMessage("Go To Inbox.");
}
});
using snackbar
public void SnackBarMessage(String message){
Snackbar.make(coordinatorLayout, message, Snackbar.LENGTH_LONG).setAction("Action", null).show();
}
let's say I have 3 tabs e.g (tab 0 ,tab 1 , tab 2)
how can I make the Floating action button take me to tab 2 once I click on it
This is the fragment containing the tabs
public class HomeFragment extends Fragment {
private TabLayout tabLayout;
private ViewPager mViewPager;
private OnFragmentInteractionListener mListener;
private SectionsPagerAdapter mSectionsPagerAdapter;
ArrayList<String> tabName;
public HomeFragment() {
// Required empty public constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_home, container, false);
tabLayout = (TabLayout)view.findViewById(R.id.tabs);
mViewPager = (ViewPager)view.findViewById(R.id.container);
tabName=new ArrayList<String>();
int [] tabIcons = {
R.drawable.ic_home,
R.drawable.ic_move_to_inbox,
R.drawable.ic_notifications,
R.drawable.ic_swap_horiz,
R.drawable.ic_people,
};
String[] strings = { "Main Page Goes Here", "Messages Go Here", "Notifications Go Here", "Trade Page Goes Here", "People Online Page Goes Here"};
for(int i=0;i<5;i++){
tabLayout.addTab(tabLayout.newTab().setIcon(tabIcons[i]));
tabName.add((strings[i]));
}
tabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName);
mViewPager.setAdapter(mSectionsPagerAdapter);
mViewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
getChildFragmentManager().beginTransaction().addToBackStack(null).commit();
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
// Note that we are passing childFragmentManager, not FragmentManager
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager(),tabLayout.getTabCount(),tabName);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
if (context instanceof OnFragmentInteractionListener) {
mListener = (OnFragmentInteractionListener) context;
} else {
throw new RuntimeException(context.toString()
+ " must implement OnFragmentInteractionListener");
}
}
#Override
public void onDetach() {
super.onDetach();
mListener = null;
}
#Override
public void onResume() {
super.onResume();
}
public interface OnFragmentInteractionListener {
// TODO: Update argument type and name
void onFragmentInteraction(Uri uri);
}
}
To be able to do this from another Fragment you will need to send a something in a Bundle, such as the position of the page, then do something like this:
HomeFragment fragment = new HomeFragment();
Bundle bundle = new Bundle();
bundle.putInt(YOUR_PAGE, youPage);
fragment.setArguments(bundle);
getSupportFragmentManager().beginTransaction().replace(R.id.container, fragment).addToBackStack("Name").commit();
Then in your HomeFragment:
Bundle bundle = this.getArguments();
if (bundle != null) { viewPager.setCurrentItem(bundle.getInt(YOUR_PAGE) }

How can i load WebView URL in fragment from another AppCompatActivity class

I am creating project for "Drawer with Swipe Tab". There i used a webview in fragment and i want to load Webview URL from Another AppCompatActivity. How can i do it?
Fragment Class:
public class SocialFragment extends Fragment {
ProgressBar pb_per;
public WebView mWebView;
View view;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.social_layout, container, false);
pb_per = (ProgressBar) view.findViewById(R.id.progressBar_book1);
mWebView = (WebView) view.findViewById(R.id.web_book1); //This is the id you gave for webview
//--------------------------- to over ride keyboard error ------(1)
mWebView.setWebViewClient(new myWebClient());
mWebView.getSettings().setJavaScriptEnabled(true);
//--------------------------------------------------
mWebView.getSettings().setSupportZoom(true); //Zoom Control on web (You don't need this
//if ROM supports Multi-Touch
mWebView.getSettings().setBuiltInZoomControls(true); //Enable Multitouch if supported by ROM
mWebView.setBackgroundColor(Color.parseColor("#FFFFFF"));
mWebView.getSettings().setUseWideViewPort(true);
mWebView.getSettings().setLoadWithOverviewMode(false);
// Load URL
mWebView.loadUrl("http://www.twitter.com");
mWebView.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN) {
WebView webView = (WebView) v;
switch (keyCode) {
case KeyEvent.KEYCODE_BACK:
if (webView.canGoBack()) {
webView.goBack();
return true;
}
break;
}
}
return false;
}
});
return view;
}
//===================================================================
public class myWebClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
pb_per.setVisibility(View.VISIBLE);
// multi_per.setVisibility(ProgressBar.GONE);
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
pb_per.setVisibility(View.GONE);
// multi_per.setVisibility(ProgressBar.VISIBLE);
}
}
}
TabFragment.Java Class
public class TabFragment extends Fragment {
public static TabLayout tabLayout;
public static ViewPager viewPager;
public static int int_items = 2;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
*Inflate tab_layout and setup Views.
*/
View x = inflater.inflate(R.layout.tab_layout,null);
tabLayout = (TabLayout) x.findViewById(R.id.tabs);
viewPager = (ViewPager) x.findViewById(R.id.viewpager);
/**
*Set an Apater for the View Pager
*/
viewPager.setAdapter(new MyAdapter(getChildFragmentManager()));
/**
* Now , this is a workaround ,
* The setupWithViewPager dose't works without the runnable .
* Maybe a Support Library Bug .
*/
tabLayout.post(new Runnable() {
#Override
public void run() {
tabLayout.setupWithViewPager(viewPager);
}
});
return x;
}
class MyAdapter extends FragmentPagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
}
// Return fragment with respect to Position .
#Override
public Fragment getItem(int position)
{
switch (position){
case 0 : return new PrimaryFragment();
case 1 : return new SocialFragment();
}
return null;
}
#Override
public int getCount() {
return int_items;
}
// This method returns the title of the tab according to the position.
#Override
public CharSequence getPageTitle(int position) {
switch (position){
case 0 :
return "Facebook";
case 1 :
return "Twitter";
}
return null;
}
}
}
AppCompatActivity class:
public class MainActivity extends AppCompatActivity {
DrawerLayout mDrawerLayout;
NavigationView mNavigationView;
FragmentManager mFragmentManager;
FragmentTransaction mFragmentTransaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setup the DrawerLayout and NavigationView
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
mNavigationView = (NavigationView) findViewById(R.id.shitstuff);
// Lets inflate the very first fragment
// Here , we are inflating the TabFragment as the first Fragment
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
// Setup click events on the Navigation View Items.
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
if (menuItem.getItemId() == R.id.nav_item_sent) {
//###############################From Here I Call WEBVIEW URL #######################
SocialFragment.mWebView.loadUrl("http://www.busindia.com/busindia_TNSTC.jsp");
}
if (menuItem.getItemId() == R.id.nav_item_inbox) {
FragmentTransaction xfragmentTransaction = mFragmentManager.beginTransaction();
xfragmentTransaction.replace(R.id.containerView, new TabFragment()).commit();
}
return false;
}
});
// Setup Drawer Toggle of the Toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
ActionBarDrawerToggle mDrawerToggle
= new ActionBarDrawerToggle(this, mDrawerLayout, toolbar, R.string.app_name, R.string.app_name);
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
}
}
I had Tried #cprakashagr Given Solutation but getting error See below Image
See Error ScreenShot
Use localBroadCastManager
WebViewHavingActivity
#Override
protected void onPause() {
// Unregister since the activity is paused.
LocalBroadcastManager.getInstance(this).unregisterReceiver(
mWebViewLoader);
super.onPause();
}
#Override
protected void onResume() {
// Register to receive messages.
// We are registering an observer (mWebViewLoader) to receive Intents
// with actions named "WebView".
LocalBroadcastManager.getInstance(this).registerReceiver(
mWebViewLoader, new IntentFilter("WebView"));
super.onResume();
}
// Our handler for received Intents. This will be called whenever an Intent
// with an action named "WebView" is broadcasted.
private BroadcastReceiver mWebViewLoader = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mWebView.post(new Runnable() {
#Override
public void run() {
mWebView.loadUrl("http://google.com");
}
});
}
};
CallingActivity
LocalBroadcastManager.getInstance(JobDetailScreen.this).sendBroadcast(new Intent("WebView"));
This Work for me Thanks For trying me to Help
SocialFragment.mWebView.post(new Runnable() {
public void run() {
SocialFragment.mWebView.loadUrl("http://www.busindia.com/busindia_TNSTC.jsp");
}
});

Activity is not an enclosing class in Android Studio

I am New to Android. I Have Created Tab using android.support.v4.view.ViewPager. When i trying to get data from server using Json Request it give me the Error
AccountActivity is not an enclosing class.
please Any Help will be Appreciated
TAb1.java
public class Tab1 extends Fragment {
private ProgressDialog pDialog;
private UserAddress userAddress;
private TextView txtResponsec;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new LoadUserAddress().execute();
}
class LoadUserAddress extends AsyncTask<String,String,String> {
private ProgressDialog progressDialog;
#Override
protected String doInBackground(String... params) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
JSONHttpClient jsonHttpClient = new JSONHttpClient();
userAddress = jsonHttpClient.Get(ServiceUrl.UserAddress, nameValuePairs, UserAddress.class);
String id = userAddress.GetId();
}
catch (Exception ex){
String message = ex.getMessage();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute(); //To change body of overridden methods use File | Settings | File Templates.
progressDialog = new ProgressDialog(AccountActivity.this);
progressDialog.setMessage("Loading products. Please wait...");
progressDialog.show();
}
#Override
protected void onPostExecute(String s) {
progressDialog.dismiss();
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
txtResponsec.setText(userAddress.GetCountry());
}
});
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
return v;
}
}
AccountActivity.java
public class AccountActivity extends AppCompatActivity {
Toolbar toolbar;
ActionBar actionBar;
ViewPager pager;
ViewPagerAdapter adapter;
SlidingTabLayout tabs;
CharSequence Titles[]={"Info.","Address","Contact","Email"};
int Numboftabs =4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_account);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
assert getSupportActionBar() != null;
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (toolbar != null) {
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
}
adapter = new ViewPagerAdapter(getSupportFragmentManager(),Titles,Numboftabs);
// Assigning ViewPager View and setting the adapter
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(adapter);
// Assiging the Sliding Tab Layout View
tabs = (SlidingTabLayout) findViewById(R.id.tabs);
tabs.setDistributeEvenly(true); // To make the Tabs Fixed set this true, This makes the tabs Space Evenly in Available width
// Setting Custom Color for the Scroll bar indicator of the Tab View
tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() {
#Override
public int getIndicatorColor(int position) {
return getResources().getColor(R.color.tabsScrollColor);
}
});
// Setting the ViewPager For the SlidingTabsLayout
tabs.setViewPager(pager);
}
#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_account, 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);
}
}
You should change
progressDialog = new ProgressDialog(AccountActivity.this);
to
progressDialog = new ProgressDialog(getActivity());
in Tab1 Fragment also i see txtResponsec=null you forget to initialized it.
Edit:
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v =inflater.inflate(R.layout.tab_1,container,false);
txtResponsec=(TextView)v.findViewById(R.id.txtResponsecId);
return v;
}

when i select the contacts tab the tab bar is vanished

i have four tabs in the tab bar when i select the contact tab from the tab bar the tab bar is disappeared.i want to show the tab bar when i select the contact tab.
Here is code
TabActivity.java
public class Tab_Activity extends TabActivity
{
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Resources obj_res = getResources();
TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
TabSpec m_tab1 = tabHost.newTabSpec("First Tab");
TabSpec m_tab2 = tabHost.newTabSpec("Second Tab");
Intent intent1 = new Intent().setClass(this, Phone.class);
Intent intent3 = new Intent().setClass(this, Settings.class);
Intent intent4 = new Intent().setClass(this, Contact.class);
m_tab4.setIndicator("Tab4");
m_tab4=tabHost.newTabSpec("tab4").setIndicator("", obj_res.getDrawable(R.drawable.pic1)).setContent(intent3);
m_tab5.setIndicator("Tab4");
m_tab5=tabHost.newTabSpec("tab4").setIndicator("", obj_res.getDrawable(R.drawable.pic3)).setContent(intent4);
tabHost.addTab(m_tab2);
tabHost.addTab(m_tab4);
tabHost.addTab(m_tab5);
}}
Contact.java
public class Contact extends Activity
{
protected void onCreate(Bundle savedInstanceState)
{
//this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
//setContentView(R.layout.contact);
Intent Contacts = new Intent(Intent.ACTION_GET_CONTENT);
Contacts.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
Contacts.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(Contacts, 1);
}}
This is your activity in which u can put how many tab you want to display.
public class GuestListAdminActivity extends FragmentActivity implements
ActionBar.TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private ActionBar actionBar;
// Tab titles
private String[] tabs = { "Bride", "Groom", "Create Gueset List" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guest_list_admin);
// Initilization
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getActionBar();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(mAdapter);
actionBar.setHomeButtonEnabled(false);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
getActionBar().setHomeButtonEnabled(true);
// Adding Tabs
for (String tab_name : tabs) {
actionBar.addTab(actionBar.newTab().setText(tab_name)
.setTabListener(this));
}
/**
* on swiping the viewpager make respective tab selected
* */
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// on changing the page
// make respected tab selected
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// on tab selected
// show respected fragment view
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
}
This is pager adapter which will show your all fragments.
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new BrideGuestList();
case 1:
return new GroomGuestList();
case 2:
return new NewGuestListActivity();
default:
break;
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 3;
}
}
And make your fragment activity like following
public class BrideGuestList extends android.support.v4.app.Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.bride_guest_list, container, false);
return rootView;
}

Categories