Here's my code:
public class ScoreFragment extends Fragment {
public static final String TAG ="ScoreFragment";
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
Log.d(TAG, "onAttach");
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(savedInstanceState==null)
{
Log.d(TAG,"onCreate FIRST TIME");
}
else
{
Log.d(TAG,"onCreate SUBSEQUENT TIME");
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater,container,savedInstanceState);
final View v = inflater.inflate(R.layout.score_collection, container, false);
final TextView sliderText = (TextView) v.findViewById(R.id.score_number);
sliderText.setTextSize(48);
//TODO: Find solution to find known bug in Android
/* ActionBar actionBar = ((ActionBarActivity) getActivity()).getSupportActionBar();
actionBar.hide();*/
SeekBar seekbar = (SeekBar) v.findViewById(R.id.seekBar);
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
sliderText.setText("" + progress);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Log.d(TAG,"onCreateView");
return inflater.inflate(R.layout.score_collection, container, false);
}
The seekBar is displayed but it does not increment or show any text in my view.
Here's how I set it up in my view (inside a RelativeLayout):
<SeekBar
android:layout_width="300sp"
android:layout_height="wrap_content"
android:id="#+id/seekBar"
android:progress="0"
android:max="10"
android:minHeight="30sp"
android:maxHeight="30sp"
android:layout_below="#+id/score_number"
android:layout_centerHorizontal="true"/>
It actually worked before I placed it into Fragment, so I think it has to do with it being inside a Fragment but I'm not entirely sure.
It's suppose to increment by 1, on a scale of 0 to 10.
So I figured out what I was doing wrong. It's really a silly mistake. I apologize.
Here's the solution for those interested:
Original code:
return inflater.inflate(R.layout.score_collection, container, false);
I was returning the view all over again when I should have just returned v (View v).
So I changed the return statement above to
return v;
instead and it works. Silly me.
Related
why the "view" in this lane is always red..
final TextView username = (TextView) view.findViewById(R.id.profile_username);
I always get this error like below:
"error: cannot find symbol variable view"
Sample code which I tried:
ProfileFragment class:
public class ProfileFragment extends Fragment {
MyBroadcastReceiver myReceiver = new MyBroadcastReceiver();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_profile, container, false);
ImageView profilsettings = (ImageView) view.findViewById(R.id.profile_toolbar_image);
profilsettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog();
bottomSheetDialog.show(getFragmentManager(), bottomSheetDialog.getTag());
}
});
return view;
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("my_broadcast")){
final TextView username = (TextView) view.findViewById(R.id.profile_username);
username.setText(intent.getStringExtra("name"));
}
}
}
#Override
public void onResume() {
super.onResume();
getActivity().registerReceiver(myReceiver, new IntentFilter("my_broadcast"));
}
#Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(myReceiver);
}
}
Can anyone help me what do I have to change?
Thanks a lot!
It is happening because the variable view is not accessible to your BroadcastReceiver. So the compiler is saying error: cannot find symbol variable view
To make view accessible to BroadcastReceiver you can follow #Amine answer or you can easily make view asmember variable.
Make view object as a member variable like below
public class ProfileFragment extends Fragment {
MyBroadcastReceiver myReceiver = new MyBroadcastReceiver();
private View view;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_profile, container, false);
ImageView profilsettings = (ImageView) view.findViewById(R.id.profile_toolbar_image);
profilsettings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetDialog bottomSheetDialog = new BottomSheetDialog();
bottomSheetDialog.show(getFragmentManager(), bottomSheetDialog.getTag());
}
});
return view;
}
public class MyBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("my_broadcast")){
final TextView username = (TextView) view.findViewById(R.id.profile_username);
username.setText(intent.getStringExtra("name"));
}
}
}
#Override
public void onResume() {
super.onResume();
getActivity().registerReceiver(myReceiver, new IntentFilter("my_broadcast"));
}
#Override
public void onPause() {
super.onPause();
getActivity().unregisterReceiver(myReceiver);
}
}
Happy coding!!
You need to get the TextView using the available context like this
final TextView username = (TextView) ((Activity) context).findViewById(R.id.profile_username);
I am making a program that will include a Spinner within a fragment rather than an activity. I have researched why this may be crashing, but to no avail. My initial concern was a .getView().findViewById(), but now I'm not so sure that's the problem because . Here's the code.
public class Add extends Fragment {
public Add() {
// Required empty public constructor
}
ArrayList<String> ingredients = new ArrayList<>();
SpinnerDialog spinnerDialog;
Button add;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
add = (Button) getView().findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinnerDialog.showSpinerDialog();
}
});
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_add, container, false);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
spinnerDialog = new SpinnerDialog(getActivity(), ingredients, "Select An Ingredient");
spinnerDialog.bindOnSpinerListener(new OnSpinerItemClick() {
#Override
public void onClick(String Ingredient, int i) {
Toast.makeText(Add.super.getContext(), "Selected ", Toast.LENGTH_SHORT).show();
}
});
Without seeing the stack trace I cannot say for sure, but I suspect this line is crashing:
add = (Button) getView().findViewById(R.id.add);
This is because getView() will return the View instance returned by onCreateView()... but you're currently inside onCreateView(), so getView() will return null.
You can re-write your onCreateView() as follows and it should work.
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_add, container, false);
add = (Button) root.findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
spinnerDialog.showSpinerDialog();
}
});
return root;
}
Got two empty Activites(A and B), which just hold two fragments inside ViewPager of Activity A.
I do not have code errors, everything seems fine.
When I lunch my app and click on button, nothing happens.I was trying just to log something, but still nothing is happening.
I am using ButterKnife, and so far everything was perfect.I got almost same Fragment and it is performing fine, but OnClick inside Fragment B is not working.I tried to add some more OnClick methods, but none of them worked for me.XML looks good,looks almost same as fragment A.
Fragment B is not complex, it just three TextViews and Button.
Here is code for my fragment B:
public class ForgotPasswordFragmentComplete extends BaseFragment
implements BaseView {
private Realm realm;
private Email model;
#Bind(R.id.btn_resend)
AppCompatButton resendEmail;
#Inject
ForgotPasswordPresenter presenter;
#OnClick(R.id.btn_resend)
public void resendButton() {
Log.d("ResendOnclick", "Checking OnClickMethod ");
Realm realm2 = getRealm();
RealmQuery<Email> queryUserResend = realm2.where(Email.class);
Email resultResend = queryUserResend.findFirst();
ForgotPasswordPayload forgotPayload = new ForgotPasswordPayload(resultResend.getUsername());
this.presenter.subscribe(forgotPayload);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
DaggerForgotPasswordCompletedComponent.builder()
.applicationComponent(
((AndroidApplication) getActivity().getApplication()).getApplicationComponent())
.forgotPasswordCompletedModule(new ForgotPasswordCompletedModule())
.build()
.inject(this);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
}
#Override
protected void onCreateViewWidgetInitialization(View view) {
super.onCreateViewWidgetInitialization(view);
}
#Override
public void onStart() {
super.onStart();
getEmail();
}
public void getEmail(){
Realm realm = getRealm();
RealmQuery<Email> queryUser = realm.where(Email.class);
Email result1 = queryUser.findFirst();
resendEmailTxt = (AutoResizeTextView) getView().findViewById(R.id.resend_user_email);
if (resendEmailTxt != null) {
this.resendEmailTxt.setText(result1.getUsername());
}
}
#Override
public void onDestroy() {
super.onDestroy();
realm.close();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_forgot_password_fragment_complete, container, false);
}
#Override
protected int getFragmentLayoutId() {
return R.layout.fragment_forgot_password_fragment_complete;
}
You need to bind the fragment's view object before you can use it. Try putting the following code inside onCreateView() :
View rootView = inflater.inflate(R.layout.fragment_forgot_password_fragment_complete, container, false);
ButterKnife.bind(this, rootView);
return rootView;
I have a Activity with 3 tabs, inside first a fragment with listview. The listview has custom adapter. There is not problem when I start and when i go to second tab and come back. But when I go to 3th tab and come back to first one, the fragment execute onCreateView and crash with nullpointerexception, this is my code:
The fragment:
List<Post> rings;
View headerView;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragment_within_ring, container, false);
headerView = getActivity().getLayoutInflater().inflate(R.layout.header_list_view, null);
new consultarRing().execute(); //This get the Array from web service to rings
return rootView;
}
private void fullyAdapter() {
if (rings != null) {
adapter = new PostsAdapter(getActivity(), R.layout.item_row_show_ring, rings, false, null);
lyt = (PullAndLoadListView) getActivity().findViewById(R.id.listView_withinring);
lyt.addHeaderView(headerView); //crash here
lyt.setAdapter(adapter); //crash here
//crash all down
lyt.setOnRefreshListener(new OnRefreshListener() {
//OnRefreshListener
#Override
public void onRefresh() {
// TODO Auto-generated method stub
new PullToRefreshDataTask().execute();
}
});
lyt.setOnLoadMoreListener(new OnLoadMoreListener() {
#Override
public void onLoadMore() {
// TODO Auto-generated method stub
new LoadMoreDataTask().execute();
}
});
lyt.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
switch (firstVisibleItem) {
case 1:
Main.isScrolling = false;
break;
case 2:
Main.isScrolling = true;
break;
default:
break;
}
}
});
}
}
private class consultarRing extends AsyncTask<String, String, CollectionResponsePost> {
#Override
protected void onPreExecute() {
//do staff
}
#Override
protected CollectionResponsePost doInBackground(String... args) {
//do staff, get rings
}
#Override
protected void onPostExecute(CollectionResponsePost responsePost) {
//call fullyAdapter() method
fullyAdapter();
}
}
My problem is when the listview tray setAdapter for second time, I dont know how reset listview for start like new. Please help.
You execute your AsyncTask inside of onCreateView. At that moment the fragment's view hierarchy is not yet added to the activity's, therefore getActivity().findViewById() will return null if you search for fragment's views.
Try starting the AsyncTask later:
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new consultarRing().execute();
}
How can I set an onClick listener for a button in layout_one? Where do I put the code? when I put it in the onCreateView it gives me an error.
public class LayoutOne extends Fragment {
Button button;
public static Fragment newInstance(Context context) {
LayoutOne f = new LayoutOne();
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater.inflate(R.layout.layout_one, null);
return root;
}
set Layout attribute android:clickable="true", android:focusable="true" and android:focusableInTouchMode="true" from xml or setClickable(true) from code. set onClickListener as:
((LinearLayout)findViewById(R.id.layout_one_id)).setClickable(true); ((LinearLayout)findViewById(R.id.layout_one_id)).setOnClickListener(layoutOnClickListener);
private OnClickListener layoutOnClickListener = new OnClickListener() {
public void onClick(View v) {
//Get Click here
}
};
It wont give any error if You will do it something like this
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
ViewGroup root = (ViewGroup) inflater
.inflate(R.layout.layout_one, null);
Button button_one=(Button)root.findViewById(R.id.button_one);// button_one is the id of the button in your xml file
button_one.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
return root;
}
Don't know what your button is called, but in onCreateView() you do:
button = (Button)root.findViewById(R.id.layout_one_id);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//stuff goes in here
}
});
Your other option is to do it in xml and just make a method that uses it. For example, setting the Buttons android:onClick="onButtonClicked" attribute, in code your method would look like this
public void onButtonClicked(View v) { /*Stuff*/ }