I am trying to implement the Model-View-ViewModel architectural pattern and XML data binding in my Android Java app. The code seems all correct as far as I can see, however I'm getting a blank screen when I run the app (not even the bottomNavigationView is showing). I am using a ViewModel to store/persist data for a fragment called AllTimeBestFragment. Specifically, AllTimeBestFragment is one of three fragments in a Viewpager-tabLayout.
Would appreciated any insight into what I'm doing wrong!
AllTimeBestFragment
public class AllTimeBestFragment extends Fragment {
private ImageViewCallback imageViewCallback;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(Constants.SkiCompanionDebug, "AllTimeBestFragment");
bindToViewModel();
return inflater.inflate(R.layout.fragment_all_time_best, container, false);
}
//imageview callback
#Override
public void setUserVisibleHint(boolean visible) {
super.setUserVisibleHint(visible);
imageViewCallback.setImage(R.drawable.all_time_best);
}
public void addCallback(ImageViewCallback imageViewCallback) {
this.imageViewCallback = imageViewCallback;
}
//binding the view (fragment) to the asoociated viewModel
public void bindToViewModel(){
FragmentAllTimeBestBinding binding = DataBindingUtil.setContentView(getActivity(), R.layout.fragment_all_time_best);
AllTimeBestViewModel viewModel = ViewModelProviders.of(this).get(AllTimeBestViewModel.class);
AllTimeStats allTimeStats = BCCDatabase.getInstance(getActivity()).getAllTimeStats();
viewModel.init(allTimeStats);
binding.setAllTimeBestViewModel(viewModel);
}
}
AllTimeBestViewModel
public class AllTimeBestViewModel extends ViewModel {
private AllTimeStats allTimeStats;
public void init(AllTimeStats allTimeStats) {
this.allTimeStats = allTimeStats;
}
public String getDurationTotal(){
return ""+allTimeStats.getDurationTotal();
}
}
fragment_all_time_best.xml
<data>
<variable
name="allTimeBestViewModel"
type="skicompanion.skicompanion.viewmodels.AllTimeBestViewModel" />
</data>
<ScrollView 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/track_scrollview"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout 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="wrap_content"
android:orientation="vertical"
tools:context="skicompanion.skicompanion.fragments.AllTimeBestFragment">
<android.support.v7.widget.CardView
android:id="#+id/duration_cardview"
android:layout_width="match_parent"
android:layout_height="180dp"
android:layout_marginEnd="8dp"
android:layout_marginLeft="8dp"
android:layout_marginRight="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent">
<android.support.constraint.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/duration_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#{allTimeBestViewModel.durationTotal}"
android:textSize="18sp"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="#+id/duration_total_tv"
app:layout_constraintStart_toStartOf="#+id/imageView2"
app:layout_constraintTop_toBottomOf="#+id/duration_total_tv" />
...
...
...
Gradle
implementation "android.arch.lifecycle:extensions:1.1.1"
implementation "android.arch.lifecycle:viewmodel:1.1.1"
I found the answer here: How to use data-binding with Fragment
I was binding the data as if I were dealing with an activity - I needed to bind it for a fragment instead. The trick was to use DataBindingUtil.inflate rather than DataBindingUtil.setContentView. Below is the correct code snippet:
public class AllTimeBestFragment extends Fragment {
private ImageViewCallback imageViewCallback;
private FragmentAllTimeBestBinding binding;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
Log.d(Constants.SkiCompanionDebug, "AllTimeBestFragment");
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_all_time_best, container, false);
bindToViewModel();
return binding.getRoot();
}
//imageview callback
#Override
public void setUserVisibleHint(boolean visible) {
super.setUserVisibleHint(visible);
imageViewCallback.setImage(R.drawable.all_time_best);
}
public void addCallback(ImageViewCallback imageViewCallback) {
this.imageViewCallback = imageViewCallback;
}
//binding the view (fragment) to the asoociated viewModel
public void bindToViewModel(){
AllTimeBestViewModel viewModel = ViewModelProviders.of(this).get(AllTimeBestViewModel.class);
AllTimeStats allTimeStats = BCCDatabase.getInstance(getActivity()).getAllTimeStats();
viewModel.init(allTimeStats);
binding.setAllTimeBestViewModel(viewModel);
}
}
Related
so i'm creating an android app using Xamarin.android and i'm using the navigation drawer app. I added a fragment and within the fragment I added a button. now I need to handle some events of this button. I tried adding a click event function in the fragment.cs code but I got an exception "System.NullReferenceException: 'Object reference not set to an instance of an object.'". how am I supposed to handle the event?
this is the code of my main activity where I access my fragment when choosing the camera icon option:
Fragment1 fragment = new Fragment1();
public bool OnNavigationItemSelected(IMenuItem item)
{
int id = item.ItemId;
if (id == Resource.Id.nav_camera)
{
SupportFragmentManager.BeginTransaction()
.Replace(Resource.Id.mainFrame, fragment )
.Commit();
}
and this is my fragment's xml code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:text="hi"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:minWidth="25px"
android:minHeight="25px"
android:id="#+id/textView1" />
<Button
android:text="Button"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/button1" />
</LinearLayout>
and this is my fragment's c# code where I try to access the button:
public class Fragment1 : Android.Support.V4.App.Fragment
{
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
// Create your fragment here
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
// Use this to return your custom view for this Fragment
base.OnCreate(savedInstanceState);
var view = inflater.Inflate(Resource.Layout.fragment1, container, false);
Button bulogin = View.FindViewById<Button>(Resource.Id.button1);
bulogin.Click += Bulogin_Click;
// return base.OnCreateView(inflater, container, savedInstanceState);
return view;
}
private void Bulogin_Click(object sender, EventArgs e)
{
TextView txt = View.FindViewById<TextView>(Resource.Id.textView1);
txt.Text = "bye";
}
}
I try to add a fragment to an activity and have already looked at the example from Martijn00.
My problem is, that the activity will be displayed but the fragment will not and in debugging mode, the debugger is not running into the fragment's method OnCreateView. So the attribute of the fragment will be used, but not the fragment. I see only my activity with the green background. I am sure I do something wrong, but after 6 hours I do give up and ask you guys for help :)
Fragment:
namespace TopDownTodoList.Mobile.Droid.Views.Fragments{
[MvxFragment(typeof(MainViewModel), Resource.Id.content_frame, true)]
[Register("topdowntodolist.mobile.droid.views.fragments.TodoOverviewFragment")]
public class TodoOverviewFragment : MvxFragment<TodoOverviewViewModel>
{
protected int LayoutId => Resource.Layout.f_todo_overview_fragment;
public override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
this.Init();
}
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return this.BindingInflate(this.LayoutId, null);
//return inflater.Inflate(this.LayoutId, container, false);
}
public virtual void Init() { }
}}
Activity:
namespace TopDownTodoList.Mobile.Droid.Views{
[Activity(Label = "MainView")]
public class MainView : MvvmCross.Droid.FullFragging.Views.MvxActivity<MainViewModel>
{
protected int LayoutId => Resource.Layout.main_view;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(this.LayoutId);
this.Init();
}
public virtual void Init(){}
}}
App.cs:
protected override void RegisterClasses()
{
RegisterAppStart<TodoOverviewViewModel>();
}
ViewModels:
public class VMName : MvvmCross.Core.ViewModels.MvxViewModel{...}
FragmentLayout (f_todo_overview_fragment):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mvx="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#0000aa"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:gravity="center"/></LinearLayout>
ActivityLayout (main_view):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#aa0000"
android:layout_width="fill_parent"
android:layout_height="fill_parent"><FrameLayout
android:id="#+id/content_frame"
android:background="#00bb00"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerInParent="true" /></LinearLayout>
Your Activity needs to be of the type MvxCachingFragmentCompatActivity or MvxCachingFragmentActivity to support hosting of fragments.
Secondly you need to ignore the normal inflator, and use binding inflate after that:
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignore = base.OnCreateView(inflater, container, savedInstanceState);
return this.BindingInflate(FragmentId, null);
}
I have an activity extending fragment activity and swipable tab view. In tab view i have used fragment and Tabs pager adapter to call fragments according to the tab position.
Now i want to replace these fragment using on click items with another fragment and on back press i want the original fragment back...
But when i am clicking on the items..it do nothing...
What should i do..pls help me ...
Thanks in advance
here is my code-
This is my Homeactivity which has tab
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_screen);
ressources = getResources();
mViewPager = (ViewPager) findViewById(R.id.viewpager);
// Tab Initialization
initialiseTabHost();
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
// Fragments and ViewPager Initialization
mViewPager.setAdapter(mAdapter);
mViewPager.setOnPageChangeListener(HomeScreen.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
// Method to add a TabHost
private static void AddTab(HomeScreen activity, TabHost tabHost,
TabHost.TabSpec tabSpec) {
tabSpec.setContent(new MyTabFactory(activity));
tabHost.addTab(tabSpec);
}
// Manages the Tab changes, synchronizing it with Pages
public void onTabChanged(String tag) {
int pos = this.mTabHost.getCurrentTab();
this.mViewPager.setCurrentItem(pos);
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
// Manages the Page changes, synchronizing it with Tabs
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
int pos = this.mViewPager.getCurrentItem();
this.mTabHost.setCurrentTab(pos);
}
#Override
public void onPageSelected(int arg0) {
}
// Tabs Creation
private void initialiseTabHost() {
mTabHost = (TabHost) findViewById(android.R.id.tabhost);
mTabHost.setup();
// TODO Put here your Tabs
HomeScreen.AddTab(
this,
this.mTabHost,
this.mTabHost.newTabSpec(Button_tab).setIndicator("",
ressources.getDrawable(R.drawable.menu)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec(Image_tab).setIndicator("",ressources.getDrawable(R.drawable.jobs)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec(Text_tab).setIndicator("",ressources.getDrawable(R.drawable.people)));
HomeScreen.AddTab(this, this.mTabHost,
this.mTabHost.newTabSpec("line_tab").setIndicator("",ressources.getDrawable(R.drawable.calenders)));
mTabHost.setOnTabChangedListener(this);
}
#Override
public void onBackPressed() {
boolean isPopFragment = false;
String currentTabTag = mTabHost.getCurrentTabTag();
if (currentTabTag.equals(Button_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Button_tab)).popFragment();
} else if (currentTabTag.equals(Image_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Image_tab)).popFragment();
} else if (currentTabTag.equals(Text_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(Text_tab)).popFragment();
} else if (currentTabTag.equals(line_tab)) {
isPopFragment = ((BaseContainerFragment)getSupportFragmentManager().findFragmentByTag(line_tab)).popFragment();
}
if (!isPopFragment) {
finish();
}
}
My XMl for HomeActivity:
<RelativeLayout 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"
tools:context=".HomeScreen" >
<RelativeLayout
android:id="#+id/header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="10dp"
android:orientation="horizontal" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:src="#drawable/krma" />
<Button
android:layout_width="30dp"
android:layout_marginTop="3dp"
android:layout_height="30dp"
android:layout_marginRight="10dp"
android:layout_alignParentRight="true"
android:background="#drawable/listmenu" />
</RelativeLayout>
<TabHost
android:id="#android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layout_weight="0"
android:background="#FF7519"
android:orientation="horizontal" />
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_weight="0" />
<android.support.v4.view.ViewPager
android:id="#+id/viewpager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom" />
</LinearLayout>
</TabHost>
</RelativeLayout>
My TabsPagerAdapter is :
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new Menu();
case 1:
return new Jobs();
case 2:
return new Applicant();
case 3:
return new Admin();
}
return null;
}
#Override
public int getCount() {
// get item count - equal to number of tabs
return 4;
}
}
my Job fragment is :
public class Jobs extends BaseContainerFragment implements OnItemClickListener {
ListView listView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_job, container,
false);
listView = (ListView) rootView.findViewById(R.id.list);
SharedPreferences sharedpreferences = getActivity()
.getSharedPreferences(LoginScreen.MyPREFERENCES,
Context.MODE_PRIVATE);
String loggedInEmail = sharedpreferences.getString("nameKey", "");
// String loggedInEmail="aditya.pratap#krmaa.com";
RestClient client = new RestClient(
"http://122.180.4.83:8080/krmaa/krmaa/joblist/" + loggedInEmail
+ "/1234");
client.AddHeader("GData-Version", "2");
try {
client.Execute(RequestMethod.GET);
} catch (Exception e) {
e.printStackTrace();
}
String response = client.getResponse();
Gson gson = new Gson();
String convertedStr = response.replace("\\\"", "\"");
String finalJson = convertedStr.substring(1, convertedStr.length() - 2);
JobDTO[] jobDTOList = gson.fromJson(finalJson, JobDTO[].class);
ItemAdapter adapter = new ItemAdapter(getActivity()
.getApplicationContext(), jobDTOList);
// Attach the adapter to a ListView
ListView listView = (ListView) rootView.findViewById(R.id.list);
listView.setAdapter(adapter);
// return list of jobDTO and iterate in view page.
return rootView;
}
public class JobDTOList {
List<JobDTO> jobDTOList;
public List<JobDTO> getJobDTOList() {
return jobDTOList;
}
public void setJobDTOList(List<JobDTO> jobDTOList) {
this.jobDTOList = jobDTOList;
}
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Here I want to switch from 1st Tab(Fragment1) to 2nd Tab(Fragment2)
// How can I switch from 1st tab to 2nd tab here???
// Below code is not worked for me.
fragment2 fr = new fragment2();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
transaction.replace(R.id.job,fr);
transaction.commit();
}
}
My xml for Job fragment is :
<?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"
android:id="#+id/job"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentTop="true"
android:orientation="horizontal" >
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="6"
android:background="#A3A385"
android:paddingBottom="10dp"
android:paddingLeft="10dp"
android:paddingTop="10dp"
android:text="Jobs"
android:textColor="#000000"
android:textSize="10pt" />
<Button
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="5dp"
android:layout_weight="1"
android:background="#A3A385"
android:text="Filter"`enter code here`
android:onClick="frag"
android:textSize="10pt" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >`enter code here`
<ListView`enter code here`
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</ListView>
</LinearLayout>
</LinearLayout>
I have this listview and it's coded in a fragment class. When selecting a listview item it goes to another fragment and displays the details . But it takes several seconds to load the data because the data i display is using AsyncTask,so it takes some time to get data from the JSON and display . So i need to use a progressBar when an item is clicked in the listview and it should close when the data is ready to display. How can i do this? I referred several tutorials and tried many of them. But i couldn't accomplish what i'm looking for.Hope some of you can help me.
NewsFragment class
private ListView listView;
private ArrayList<BaseElement> News;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.news_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
listView = (ListView) view.findViewById(R.id.list);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id){
android.support.v4.app.Fragment detail = new NewsDetailFragment();
android.support.v4.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.content_frame, detail).addToBackStack("back").commit();
}
});
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
News = JSONServices.getNewsDescription();
return null;
}
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setNewsDescription(News);
adapter = new LazyAdapter(News, activity,Element.NEWS_LIST.getType());
listView.setAdapter(adapter);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
}
NewsDetailFragment
public class NewsDetailFragment extends Fragment {
private View view1;
private ArrayList<BaseElement> newsdetail;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsdetail_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
view1 = (View) view.findViewById(R.id.list);
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
newsdetail = JSONServices.getNewsDescription();
return null;
}
#SuppressWarnings("unchecked")
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setTheater(newsdetail);
adapter = new LazyAdapter(newsdetail, activity,Element.NEWS_DETAIL.getType());
((AdapterView<ListAdapter>) view1).setAdapter(adapter);
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
}
}
NewsList layout
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/grey"
>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#drawable/listview" >
<ImageView
android:id="#+id/thumb_image"
android:layout_width="150dp"
android:layout_height="120dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
/>
<TextView
android:id="#+id/news_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:layout_toRightOf="#+id/thumb_image"
android:layout_marginTop="10dp"
android:layout_marginLeft="7dp"
android:textStyle="bold"
android:textSize="20dp" />
<!-- <TextView
android:id="#+id/news_description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textStyle="bold"
android:layout_below="#+id/news_title"
android:textSize="15dp" /> -->
</LinearLayout>
</RelativeLayout>
NewsFragment layout
<?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"
android:orientation="vertical"
android:background="#color/grey" >
<!-- <GridView
android:id="#+id/gridView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:numColumns="2"
android:stretchMode="columnWidth"
android:layout_margin="5dp"
android:columnWidth="100dp"/> -->
<ListView
android:id="#+id/list"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:dividerHeight="10dp"
android:layout_margin="6dp">
</ListView>
</LinearLayout>
Add ProgressBar to your NewsFragment layout:
<ProgressBar
android:id="#+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:indeterminate="true"
android:visibility="gone" />
Then in onItemClick method change it's visibility to true progressBar.setVisibility(View.VISIBLE) to show it and change it's visibility to false to hide it progressBar.setVisibility(View.GONE) in onPostExecute of AsyncTask.
Ok i got it now. I modified my 2nd fragment like this. When an item in the listview is clicked it goes to my second class.So i added a progressBar to my second class and it worked!
public class NewsDetailFragment extends Fragment {
private View view1;
private ArrayList<BaseElement> newsdetail;
private LazyAdapter adapter;
private Activity activity;
private CommonVariable commonVariable;
private ProgressDialog dialog;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.newsdetail_fragment, container,
false);
activity = this.getActivity();
commonVariable = (CommonVariable) activity.getApplication();
view1 = (View) view.findViewById(R.id.list);
dialog = new ProgressDialog(NewsDetailFragment.this.getActivity());
dialog.setMessage("Loading News");
dialog.setCancelable(true);
new BackGround().execute();
return view;
}
public class BackGround extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
newsdetail = JSONServices.getNewsDescription();
return null;
}
#SuppressWarnings("unchecked")
#Override
/* check again */
protected void onPostExecute(Void result) {
commonVariable.setTheater(newsdetail);
adapter = new LazyAdapter(newsdetail, activity,Element.NEWS_DETAIL.getType());
((AdapterView<ListAdapter>) view1).setAdapter(adapter);
dialog.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog.show();
super.onPreExecute();
}
}
}
I have a surfaceview class in which there is a method updateValue(). This surface view is inside a fragment(framelayout). I am trying to call the method updateValue() from the fragment class. But it is not working.
public class ImageSurface extends SurfaceView implements SurfaceHolder.Callback {
......
public void updateValue(int message){
.......
}
}
xml file in which this surfaceview is declared.
fragment_main.xml --->
<RelativeLayout 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"
tools:context="com.paint.drawx.MainActivity$PlaceholderFragment" >
<com.paint.drawx.ImageSurface
android:id ="#+id/imagesurface1"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="#+id/container"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</FrameLayout>
<fragment android:name="com.paint.drawx.DrawTools"
android:id="#+id/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:choiceMode="singleChoice"
android:divider="#android:color/transparent"
android:dividerHeight="0dp"
android:background="#FF889911"
/>
</android.support.v4.widget.DrawerLayout>
fragment class ----
public static class PlaceholderFragment extends Fragment {
ImageSurface imageSurface;
public PlaceholderFragment() {
//imageSurface = (ImageSurface)findViewById(R.id.imagesurface1);
}
#Override
public void onAttach(Activity activity){
super.onAttach(activity);
imageSurface = (ImageSurface)activity.findViewById(R.id.imagesurface1);
}
public void setMessage(int mess){
try{
imageSurface.updateValue(mess);////////this is not working. gives error nullpoint exception
}catch(Exception e){
Log.d("error","is"+e.toString());
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
setRetainInstance(true);
return rootView;
}
}
in the above class there is a method setMessage from which i call the method updateValue of the ImageSurface class but it gives null point exception. what am i doing wrong .
Thanks in advance.
I removed this line from onAttach() method
imageSurface = (ImageSurface)activity.findViewById(R.id.imagesurface1);
and inserted this line in onCreateView()
imageSurface = (ImageSurface) rootView.findViewById(R.id.imagesurface1);
and every thing is fine