ArrayAdapter not binding data to ListView - android

I am trying learn Android and building a very basic ListView, the data set up using ArrayAdapter is not showing up. My Activity code is:
MainActivity Class(default no changes)
`public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}`
**MainActivityFragment class**
public class MainActivityFragment extends Fragment {
private ListAdapter arrayAdapter;
public MainActivityFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayList<String> myEntries = new ArrayList<String>();
myEntries.add("Unix");
myEntries.add("Java");
myEntries.add("Android");
arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_forecast_item_textview, myEntries);
ListView listView = (ListView)inflater.inflate(R.layout.fragment_main, container, false).findViewById(R.id.list_view_forecast);
listView.setAdapter(arrayAdapter);
return inflater.inflate(R.layout.fragment_main, container, false);
}
}
list_item_forecast.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:minHeight="?android:listPreferredItemHeight"
android:gravity="center_vertical"
android:text=""
android:id="#+id/list_forecast_item_textview">
</TextView>
fragment_main.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:showIn="#layout/activity_main"
tools:context=".MainActivityFragment"
android:id="#+id/forecastFragment">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/list_view_forecast" />
<include layout="#layout/list_item_forecast" />
</FrameLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton android:id="#+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
All my application code is as above. I have tried tweaking the code and also tried this link but cannot get this to work. Please help.

The listview you setAdapter is not the listview you return in the fragment.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ArrayList<String> myEntries = new ArrayList<String>();
myEntries.add("Unix");
myEntries.add("Java");
myEntries.add("Android");
arrayAdapter = new ArrayAdapter<String>(getActivity(), R.layout.list_item_forecast, R.id.list_forecast_item_textview, myEntries);
View view =inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView)view .findViewById(R.id.list_view_forecast);
listView.setAdapter(arrayAdapter);
return view ;
}

Related

Why option menu does not show in this code

Why option menu does not show in this code while option menu declear in Blank fragment
BasicActivity.java - Here my first entry code
public class BasicActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_basic);
FragmentLoader.loadFragment(this, R.id.container, new BlankFragment());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
boolean retVal = super.onCreateOptionsMenu(menu);
return retVal;
}
#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);
}
}
activity_basic.xml xml file of activity basic
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BasicActivity">
<FrameLayout
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
BlankFragment.java - when i include toolbar option it appers but option menu in this fragment doesnot appear
public class BlankFragment extends Fragment {
private static final String TAG = BlankFragment.class.getName();
// TODO: Customize parameter initialization
#SuppressWarnings("unused")
public static BlankFragment newInstance( ) {
BlankFragment fragment = new BlankFragment();
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setRetainInstance(true);
setHasOptionsMenu(true);
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_blank, container, false);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.episodes, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
}
fragment_blank.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".BlankFragment" >
<!-- tools:context=".MainActivity2">-->
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="180dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:ignore="InconsistentLayout"
android:theme="#style/Theme.Fragment.AppBarOverlay"
android:fitsSystemWindows="true" >
<com.google.android.material.appbar.CollapsingToolbarLayout
android:id="#+id/chat_toolbar_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
app:contentScrim="?attr/colorPrimary"
android:background="#color/colorPrimary"
app:layout_scrollFlags="scroll|exitUntilCollapsed"
app:toolbarId="#+id/toolbar">
<ImageView
android:id="#+id/mainAppbarImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:minHeight="?actionBarSize"
android:padding="10dp"
android:text="#string/app_name"
android:textAppearance="#style/TextAppearance.Widget.AppCompat.Toolbar.Title" />
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
app:layout_collapseMode="pin"
app:popupTheme="#style/Theme.Fragment.PopupOverlay" >
<!-- <include layout="#layout/layout_main_toolbar" />-->
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.CollapsingToolbarLayout>
</com.google.android.material.appbar.AppBarLayout>
<com.google.android.material.floatingactionbutton.FloatingActionButton
android:id="#+id/chat_fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
android:src="#mipmap/ic_forward"
app:backgroundTint="#color/colorPrimary"/>
</androidx.coordinatorlayout.widget.CoordinatorLayout>

Menu in the toolbar changes or disappears

The structure of my app , an Activity with fragments that use navigationcomponent.
In the toolbar of my HomeFragment there is a toolbar with a search icon as a menu. This clicked icon leads to the search activity.
HomeFragment
Browsing in my app and changing fragment up to the ProfileFragment, I have the opportunity to view my lists and clicking on one of these opens another fragment to show the contents of that list
ProfileFragment, ShowListContent.
Now here's the magic
If I click on the toolbar icon to change the description of my list everything is perfect and we are delighted but ...
New HomeFragment
If I go back to the HomeFragment, the icon in the toolbar is no longer the same and I cannot go to the SearchActivity.
What can I do to avoid this problem?
Code time
public class HomeFragment extends Fragment{
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragment_home, container,
false);
initToolbar(view);
//other code
return view;
}
private void initToolbar(View view) {
Toolbar toolbar = view.findViewById(R.id.app_bar);
((AppCompatActivity) getActivity()).setSupportActionBar(toolbar);
toolbar.inflateMenu(R.menu.menu_main_toolbar);
}
#Override
public void onCreateOptionsMenu(#NotNull Menu menu, #NotNull MenuInflater
inflater) {
super.onCreateOptionsMenu(menu, inflater);
menu.clear();
inflater.inflate(R.menu.menu_main_toolbar, menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_search) {
Intent intent = new Intent(getActivity(), SearchActivity.class);
startActivity(intent);
}
return true;
}
}
fragment_home.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#141a32"
tools:context=".fragments.HomeFragment">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:elevation="4dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent">
<androidx.appcompat.widget.Toolbar
android:id="#+id/app_bar"
style="#style/toolbar"
app:menu="#menu/menu_main_toolbar"
app:titleTextAppearance="#style/Toolbar.TitleText"
app:titleTextColor="#color/white" />
</com.google.android.material.appbar.AppBarLayout>
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="0dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/appBarLayout">
//other code
</androidx.core.widget.NestedScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
ShowContentListFragment
public class ShowContentListFragment extends Fragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
final View view = inflater.inflate(R.layout.fragments_layout_lists, container, false);
setHasOptionsMenu(true);
getDataFromSafeArgs();
initWidgets(view);
initToolbar();
return view;
}
private void initToolbar() {
toolbar.setVisibility(View.VISIBLE);
toolbar.setNavigationIcon(R.drawable.ic_friend_list_back_button);
toolbar.inflateMenu(R.menu.menu_profile_edit_list);
toolbar.setNavigationOnClickListener(v -> {
Navigation.findNavController(getView())
.navigate(R.id.action_showContentListFragment_to_profileFragmentOriginal);
movies_into_list.clear();
getAndPostMovieIntoLIstModel.clearPersonalList();
});
toolbar.setOnMenuItemClickListener(item -> {
if (item.getItemId() == R.id.menu_edit) {
dialogModifyDescription();
return true;
} else {
return false;
}
});
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, #NonNull MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.menu_profile_edit_list, menu);
super.onCreateOptionsMenu(menu, inflater);
}
}
fragment_showListContent.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/big_stone"
tools:context=".fragments.MyListsFragment">
<include
layout="#layout/layout_toolbar"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
//other code
</androidx.constraintlayout.widget.ConstraintLayout>
You should have 1 toolbar and maybe 1 menu and instead disable/enable icons using menu.findItem(R.id.menu_edit).setVisible(true/false);
Maybe you could try calling requireActivity().invalidateOptionsMenu() as well.

When I am adding fragment to my view pager (in nested scroll view), I can not exit from application with device back button

This is my activity_main code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
android:layoutDirection="rtl"
tools:context=".MainActivity"
tools:openDrawer="start">
<android.support.design.widget.CoordinatorLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:fitsSystemWindows="true"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:layoutDirection="rtl"
app:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/AppTheme.PopupOverlay"
app:title="#string/app_name">
</android.support.v7.widget.Toolbar>
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="rtl" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<com.duolingo.open.rtlviewpager.RtlViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layoutDirection="rtl"
app:layout_behavior="#string/appbar_scrolling_view_behavior"/>
</android.support.v4.widget.NestedScrollView>
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/navigation_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:layoutDirection="rtl"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/menu_drawer" />
</android.support.v4.widget.DrawerLayout>
I want to add some fragments to ViewPager in NestedScrollView.
Without adding fragments to ViewPager everything is ok and I can exit from app by device back button, but when I am adding fragment(s) to ViewPager I can not exit from app by pressing device back button.(Back button is working and for example can close soft keyboard)
this is my fragment code:
(empty fragment!)
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable
ViewGroup container, #Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_jadvalyab,container,false);
}
and this is my adapter:
public class MyFragmentPagerAdapter extends FragmentPagerAdapter {
private ArrayList<Fragment> fragmentsList = new ArrayList<>();
private ArrayList<String> fragsTitleList = new ArrayList<>();
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
public void addFragment(Fragment fragment,String title){
fragmentsList.add(fragment);
fragsTitleList.add(title);
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return fragsTitleList.get(position);
}
#Override
public Fragment getItem(int position) {
return fragmentsList.get(position);
}
#Override
public int getCount() {
return fragmentsList.size();
}
}
Does anyone have an idea to solving this problem?
Thanks.
Edit:
Problem solved by removing NestedScrollingView from coordinator layout in activity_main and putting that in fragment layout (inside viewpager).
But still I don't know why device back button did not worked in former state.
I think the problem is occurring because you have used a third party library for ViewPager.
Just copy and paste the following code in the place of your "activity_main.xml" file.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main2Activity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
<android.support.design.widget.TabLayout
android:id="#+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main2" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="#dimen/fab_margin"
app:srcCompat="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/drawer_header"
app:menu="#menu/menu_drawer" />
</android.support.v4.widget.DrawerLayout>
I have initialized fragment to ViewPager like this
ViewPager viewPager2 = findViewById(R.id.viewpager);
MyFragmentPagerAdapter pagerAdapter2 = new MyFragmentPagerAdapter(getSupportFragmentManager());
pagerAdapter2.addFragment(TestFragment.createInstance(),"Home");
viewPager2.setAdapter(pagerAdapter2);
TabLayout tabLayout2 = findViewById(R.id.tabs);
tabLayout2.setupWithViewPager(viewPager2);
Here is the Testfragment.java class
public class TestFragment extends Fragment {
public static TestFragment createInstance() {
TestFragment profileFragment = new TestFragment();
return profileFragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_jadvalyab, container, false);
return rootView;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
}
And the full code of "Main2Activity.java" class is here
public class Main2Activity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
initViewPager();
}
private void initViewPager() {
ViewPager viewPager2 = findViewById(R.id.viewpager);
MyFragmentPagerAdapter pagerAdapter2 = new MyFragmentPagerAdapter(getSupportFragmentManager());
pagerAdapter2.addFragment(TestFragment.createInstance(),"Home");
viewPager2.setAdapter(pagerAdapter2);
TabLayout tabLayout2 = findViewById(R.id.tabs);
tabLayout2.setupWithViewPager(viewPager2);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main2, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Edit:
Code of "content_main2.xml"
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_behavior="#string/appbar_scrolling_view_behavior" />
</android.support.v4.widget.NestedScrollView>
Code for "fragment_jadvalyab.xml" is in te following
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Best Wishes"
android:gravity="center"/>
</LinearLayout>
Try this
#Override
public void onBackPressed() {
//Your Action
}
Override onBackPress(){} event in your MainActivity which holds your above xml layout.
#Override
public void onBackPressed() {
finish();
}
override OnBackPressed() method , or you can write your adapter as this.
public class Adapter extends FragmentStatePagerAdapter {
public Adapter (FragmentManager fm) {
super(fm);
}
// you can add fragments according to your requirement
#Override
public Fragment getItem(int position) {
Fragment fragment= null;
switch (position){
case 0:
fragment= new fragmentDay();
break;
case 1:
fragment= new fragmentWeek();
break;
case 2:
fragment= new fragmentMonth();
break;
}
return fragment;
}
#Override
public int getCount() {
return 3;
}
}
and inside activity pass fragment manager to adapter constructor.
fragmentManager= getSupportFragmentManager();
adapter= new Adapter(fragmentManager);
viewPager.setAdapter(adapter);
I have used tablayout with viewpager
tabLayout.setupWithViewPager(viewPager);
tabLayout.setTabsFromPagerAdapter(adapter);
tabLayout.getTabAt(0).setText("Day");
tabLayout.getTabAt(1).setText("Week");
tabLayout.getTabAt(2).setText("Month");
tabLayout.getTabAt(1).select();
tabLayout.setSelectedTabIndicatorColor(Color.WHITE);

Android View Displaying twice

This is what I mean by displaying twice. Both of them are able to scroll depending on where you place your finger.
I have a basic adapter that doesn't do anything other than load the view (which has some placeholder data seen above).
Here is where the view is referenced in the adapter:
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = LayoutInflater.from(context).inflate(R.layout.list_item_forecast, parent, false);
return view;
}
And the Adapter is call in a fragment here:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
mForecastAdapter = new ForecastAdapter(getActivity(), null, 0);
ListView forecastListView = (ListView) rootView.findViewById(R.id.listView_forecast);
forecastListView.setAdapter(mForecastAdapter);
forecastListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView adapterView, View view, int position, long l) {
// CursorAdapter returns a cursor at the correct position for getItem(), or null
// if it cannot seek to that position.
Cursor cursor = (Cursor) adapterView.getItemAtPosition(position);
if (cursor != null) {
String locationSetting = Utility.getPreferredLocation(getActivity());
Intent intent = new Intent(getActivity(), DetailActivity.class)
.setData(WeatherContract.WeatherEntry.buildWeatherLocationWithDate(
locationSetting, cursor.getLong(COL_WEATHER_DATE)
));
startActivity(intent);
}
}
});
return rootView;
}
I also have a cursor loader in that fragment that swaps the cursor onLoadFinished and onLoaderReset.
My layout.xml file, just in case it's relevant.
<?xml version="1.0" encoding="utf-8"?>
<!-- Layout for weather forecast list item for future day (not today) -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:minHeight="?android:attr/listPreferredItemHeight"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:id="#+id/list_item_icon"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"/>
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="0dp"
android:layout_weight="1"
android:orientation="vertical"
android:paddingLeft="16dp">
<TextView
android:id="#+id/list_item_date_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tomorrow"/>
<TextView
android:id="#+id/list_item_forecast_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Clear"/>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/list_item_high_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="81"/>
<TextView
android:id="#+id/list_item_low_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="68"/>
</LinearLayout>
</LinearLayout>
Asked for my MainActivity.java:
public class MainActivity extends AppCompatActivity {
String LOG_TAG = MainActivity.class.getSimpleName();
private final String FORECASTFRAGMENT_TAG = "FFTAG";
String mLocation;
private void showMap(Uri zipCode){
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(zipCode);
if(intent.resolveActivity(this.getPackageManager()) != null){
startActivity(intent);
}else{
View view = getCurrentFocus();
Snackbar.make(view, "No Map application found", Snackbar.LENGTH_SHORT).setAction("", null).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
// super.onCreate(savedInstanceState);
// setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//
// mLocation = Utility.getPreferredLocation(this);
//
// Log.v(LOG_TAG, "onCreate()");
mLocation = Utility.getPreferredLocation(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment, new ForecastFragment(), FORECASTFRAGMENT_TAG)
.commit();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.v(LOG_TAG, "onDestroy()");
}
#Override
protected void onStart() {
super.onStart();
Log.v(LOG_TAG, "onStart()");
}
#Override
protected void onResume() {
super.onResume();
if(mLocation != Utility.getPreferredLocation(this)){
mLocation = Utility.getPreferredLocation(this);
ForecastFragment ff = (ForecastFragment)getSupportFragmentManager().findFragmentByTag(FORECASTFRAGMENT_TAG);
ff.onLocationChange();
}
Log.v(LOG_TAG, "onResume()");
}
#Override
protected void onStop() {
super.onStop();
Log.v(LOG_TAG, "onStop()");
}
#Override
protected void onPause() {
super.onPause();
Log.v(LOG_TAG, "onPause()");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
Context context = getApplicationContext();
// int duration = Toast.LENGTH_SHORT;
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
// Toast toast = Toast.makeText(context, "Settings Pressed", duration);
// toast.show();
Intent intent = new Intent(context, SettingsActivity.class);
startActivity(intent);
return true;
}else if(id == R.id.action_map_view){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getApplication());
String zipCode = preferences.getString(getString(
R.string.pref_location_key),
getString(R.string.pref_location_default));
Uri geolocation = Uri.parse("geo:0,0?").buildUpon()
.appendQueryParameter("q", zipCode)
.build();
showMap(geolocation);
}
return super.onOptionsItemSelected(item);
}
}
This is the main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.example.android.sunshine.app.MainActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<!--<android.support.design.widget.FloatingActionButton-->
<!--android:id="#+id/fab"-->
<!--android:layout_width="wrap_content"-->
<!--android:layout_height="wrap_content"-->
<!--android:layout_gravity="bottom|end"-->
<!--android:layout_margin="#dimen/fab_margin"-->
<!--android:src="#android:drawable/ic_dialog_email" />-->
</android.support.design.widget.CoordinatorLayout>
And this is the content_main.xml that is referenced:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment"
android:name="com.example.android.sunshine.app.ForecastFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_main" />
I have seen this sort of behavior before with fragments. It indicates that you have more than one fragment that has been attached to the activity. Each with its own functioning listview. I am unsure how this is happening as of yet in your code.
EDIT
Two fragments are being attached in the following places.
Once in your xml:
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/fragment"
android:name="com.example.android.sunshine.app.ForecastFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:layout="#layout/fragment_main" />
And once in your Activity:
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment, new ForecastFragment(), FORECASTFRAGMENT_TAG)
.commit();
To fix this, remove
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment, new ForecastFragment(), FORECASTFRAGMENT_TAG)
.commit();
in your onCreate() of your activity and you'll now have just one list displaying.
You don't need to add the fragment in the onCreate since you have declared it in the xml:
Remove this from your onCreate:
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.fragment, new ForecastFragment(),FORECASTFRAGMENT_TAG)
.commit();
}
And make it this:
#Override
protected void onCreate(Bundle savedInstanceState) {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mLocation = Utility.getPreferredLocation(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

How to get edit text values from list view on button click

I have two edit texts and text views in my list view.The text view values are set from Sq lite through adapter.and I have a button outside list view. My problem is when I clicks the button the values in each edit text will be stored to an array and later I can store it to the SQLite again. But I get null values when running the code. I tried so many methods from other questions but failed.Please help to get the answer.
Here is my code
protected void InsertDb() {
// TODO Auto-generated method stub
View v;
HashMap<String, String> itemdata = new HashMap<String, String>();
for (int i = 0; i < list.getChildCount(); i++) {
v = list.getAdapter().getView(i, null, null);
cases = (EditText) v.findViewById(R.id.cases);
pcs = (EditText)v.findViewById(R.id.pcs);
itemdata.put("cases", cases.getText().toString());
itemdata.put("pieces", pcs.getText().toString());
}
Log.v("working correctly", itemdata.toString());
}
this is how my activity looks like
Thanks in advance..
Activity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ListView mList;
private Button mButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
mList = (ListView) findViewById(R.id.list);
mButton = (Button) findViewById(R.id.click_btn);
MyAdapter adapter = new MyAdapter(this);
mList.setAdapter(adapter);
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();
}
});
mButton.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if(mList != null){
for(int i = 0; i< mList.getChildCount();i++){
View vie = mList.getChildAt(i);
EditText ed1= (EditText) vie.findViewById(R.id.edone);
EditText ed2 = (EditText) vie.findViewById(R.id.edtwo);
Log.d("value",ed1.getText().toString());
Log.d("value",ed2.getText().toString());
}
}
}
class MyAdapter extends BaseAdapter{
private LayoutInflater inflater;
public MyAdapter(Context context){
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return 5;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
if(row == null){
row = inflater.inflate(R.layout.item_list,parent,false);
}
return row;
}
/* class MyViewHolder{
public MyViewHolder(View v){
}
}*/
}
}
activity_main:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:fitsSystemWindows="true"
tools:context=".MainActivity">
<android.support.design.widget.AppBarLayout android:layout_height="wrap_content"
android:layout_width="match_parent" android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar android:id="#+id/toolbar"
android:layout_width="match_parent" android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary" app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_main" />
<android.support.design.widget.FloatingActionButton android:id="#+id/fab"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_gravity="bottom|end" android:layout_margin="#dimen/fab_margin"
android:src="#android:drawable/ic_dialog_email" />
</android.support.design.widget.CoordinatorLayout>
content_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:showIn="#layout/activity_main" tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/list">
</ListView>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Click Me"
android:id="#+id/click_btn"
android:background="#color/colorPrimary"
android:textColor="#ffffff"
android:layout_below="#+id/list"
/>
</RelativeLayout>
item_list.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edone"
/>
<EditText
android:paddingTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/edtwo"
android:layout_below="#+id/edone"
/>
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.naveenbm.edittexttest" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:windowSoftInputMode="adjustPan"
android:theme="#style/AppTheme.NoActionBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The problem is that getting a reference to the EditText is difficult from the ListView. I'm suggesting the following approach.
Have 2 class variables of type String Array
String[] csArray = new String[];
String[] pcsArray = new String[];
Now on your list's Adapter's getView method, add a TextWatcher and populate the csArray and pcsArray whenever the user changes the value.
E.g.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
csEditText.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable s) {
csArray[position] = s.toString();
}
});`
// Repeat the same for pcsEditText
Now, on the button press method, simply get the value you require from the csArray and pcsArray objects.
Try replacing this line
v = list.getAdapter().getView(i, null, null);
With
v = list.getChildAt(i);

Categories

Resources