"cannot resolve findviewbyid in fragment" error - java

I'm trying to move Floating Action Button into my Fragment. But I'm getting an error about findViewById. It's "Cannot resolve method 'findViewById'
I researched, i found so many things but i'm not good at this. Can anyone explain me how can i solve this error? I tried "Invalidate Caches/Restart" and "Clean and Rebuild Project", but it didn't work.
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Floating Action Button
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// intent
}
});
}

findviewById() do not belongs to Fragment class, but Activity.
You said you're inside a Fragment and want to access some view in the Activity, you must use getActivity().findViewById(R.id.fab).

Related

Floating Refresh-Button for WebView

I want to make a floating Refresh-Button for my WebView.
I did some research but I wasn't able to fix my problem.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
String url = "https://www.rtl.de/cms/sendungen/serie/alarm-fuer-cobra-11.html";
WebView view = (WebView) this.findViewById(R.id.WebView);
view.getSettings().setJavaScriptEnabled(true);
view.loadUrl(url);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.reload();
}
});
I also tried MainActivity.this.webView.loadUrl("https://www.rtl.de/cms/sendungen/serie/alarm-fuer-cobra-11.html"); instead of view.reload(); but there is always an error.
Cannot resolve method 'reload()'
or
Cannot resolve symbol 'WebView'
It would be very nice if anyone could help me.
You can actually just make an Intent and start your current activity as a new one. For example in your activity, make a button like this:
myButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MainActivity.class);
startActivity(intent);
}
});
Please tell me if it is ok.
Take care!

Change Pictures by clicking Button [duplicate]

This code, with the block at the top commented, runs successfully:
public class MainActivity extends AppCompatActivity {
/*
EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
TextView welcome = (TextView)findViewById(R.id.textView_Welcome);
Button login=(Button)findViewById(R.id.button_Login);
Button anotherLogin=(Button)findViewById(R.id.button_Login_Another);
*/
public void doLoginOnClick(View v)
{
String s1=username.getText().toString();
inputdata.setText(s1);
}
#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();
}
});
}
}
I am trying to capture id of component using
findViewById(R.id.***)
as you can see, I put this code in comment at the very beginning of the code.
EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
TextView welcome = (TextView)findViewById(R.id.textView_Welcome);
Button login=(Button)findViewById(R.id.button_Login);
Button anotherLogin=(Button)findViewById(R.id.button_Login_Another);
If I remove the comment above and run it (both in emulator and real device), the program crashes immediately, I am surprised what's wrong here?
even I have tried to initialize the same thing using constructor.
But if I put it inside onCreate() there's no crash? Why?
I was trying to fetch info of username and password and display it to the textview in textView_Inputdata using
EditText username = (EditText)findViewById(R.id.editText_Username);
EditText password = (EditText)findViewById(R.id.editText_Password);
TextView inputdata = (TextView)findViewById(R.id.textView_InputData);
inputdata.setText(username.getText.toString()+" "+password.getText.toString());
Is there better or easier way to do that?
Instance member variables are initialized when the instance itself is initialized. It's too early for findViewById()
Before onCreate() your activity does not yet have a Window that findViewById() needs internally. Before setContentView() (that you should be calling in onCreate()) there are no views to be found either.
Therefore init your view references in onCreate() and after setContentView().
Add this code
EditText username = findViewById(R.id.editText_Username);
EditText password = findViewById(R.id.editText_Password);
TextView inputdata = findViewById(R.id.textView_InputData);
TextView welcome = findViewById(R.id.textView_Welcome);
Button login = findViewById(R.id.button_Login);
Button anotherLogin = findViewById(R.id.button_Login_Another);
in
onCreate();
method after
setContentView(R.layout.activity_main);
Hey I see that you are defining and initialising the instance variables.
What I do is I define the the instance variables - EditText username and then in the onCreate method I initialise them - username = (EditText) findViewById(R.id.editText_Username);
The reason you don't initialize the instance variables is because the elements are not ready until after the setContentView in onCreate method - I could be wrong with this, but my best practice is define the instance variable and then initialize them in the onCreate method
Before setting setContentView() you are not able to initialize the view items.Because view will not be exists for activity at that time.
Keep the initializations in one separate method and call that method after setting the view to the activity.
You must call findViewById() after setContentView() in onCreate(), before that there isn't UI/Layout initialize thats why your findViewById() unable to find ids and throws NullPointerException.
public class MainActivity extends AppCompatActivity {
public void doLoginOnClick(View v){
String s1 = username . getText ().toString();
inputdata.setText(s1);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar =(Toolbar) findViewById (R.id.toolbar);
setSupportActionBar(toolbar);
EditText username =(EditText) findViewById (R.id.editText_Username);
EditText password =(EditText) findViewById (R.id.editText_Password);
TextView inputdata =(TextView) findViewById (R.id.textView_InputData);
TextView welcome =(TextView) findViewById (R.id.textView_Welcome);
Button login =(Button) findViewById (R.id.button_Login);
Button anotherLogin =(Button) findViewById (R.id.button_Login_Another);
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();
}
});
}
}
Initialize all your views after onCreate() Method
Read More about activity lifecycle here
Think of it this way - until you tell the activity which user interface layout(xml) to use, it will not know where to get those views from.
You would do setContentView(R.layout.your_xml) to tell the activity which layout to use as the user interface for the activity. You would do this in the onCreate callback because this is the callback to do 'one-time activity level set up' tasks. setContentView() is one such task.
Once you do this, you can begin to access the views that are present within the layout file R.layout.your_xml.
onCreate(...)
{
...
setContentView(R.layout.your_xml)
// Ready to use the views from above xml.
findViewById(R.id.your_view)
...
}
View Binding will help you prevent from these issues:
https://developer.android.com/topic/libraries/view-binding
Or declare the views on top, and initialize them after setContentView() in onCreate().
public class MainActivity extends AppCompatActivity {
//Declare view on top
EditText username, password;
TextView inputdata,welcome;
Button login,notherLogin;
public void doLoginOnClick(View v)
{
String s1=username.getText().toString();
inputdata.setText(s1);
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set view
username = findViewById(R.id.editText_Username);
password = findViewById(R.id.editText_Password);
inputdata = findViewById(R.id.textView_InputData);
welcome = findViewById(R.id.textView_Welcome);
login = findViewById(R.id.button_Login);
anotherLogin = findViewById(R.id.button_Login_Another);
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();
}
});
} }
setContentView() is responsible for inflating the layout of the activity. If any of the components are used before inflation of the layout, it will crash with a NullPointerException.
#Override
protected void onCreate(Bundle savedInstanceState)
{
setContentView(R.layout.activity_layout);
username = findViewById(R.id.editText_Username);
password = findViewById(R.id.editText_Password);
inputdata = findViewById(R.id.textView_InputData);
welcome = findViewById(R.id.textView_Welcome);
login = findViewById(R.id.button_Login);
anotherLogin = findViewById(R.id.button_Login_Another);
}
You can still declare the variable in the beginning of the class, but you have to initialize it in onCreate.

OnClickListener Android Studio

Hi I'm trying to create an application for Android, but when I try to start it with 2 setOnClickListener, it crashes,
Infact if i delete one of the two events it doesen't crash
how can I do?
P.S. Sorry for my bad english, but im italian
MainActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Create the adapter that wil return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
// Set up the ViewPager with the sections adapter.
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mSectionsPagerAdapter);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.FeedBackHome);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.contact);
}
});
Button button= (Button) findViewById(R.id.NotReg);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, Register.class));
}
});
}
first illegal code :
you can't set new Content View onClick like you do here :
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
setContentView(R.layout.contact); // <-- this is wrong
}
});
be sure that Register.class contain layout and able to open from another activity.

Trying to execute multiple layout from single class

I'm trying to execute more then one layout screens from single class using onClick() method
Here goes my code
Button bt1,bt2;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button)findViewById(R.id.button);
bt2 = (Button)findViewById(R.id.button1);
onClick(); //onClick(View) in MainActivity cannot be applied to ()
}
public void onClick(View v){
if(v.getId()==R.id.button){
setContentView(R.layout.next1);
}
else if(v.getId()==R.id.button){
setContentView(R.layout.next1);
}
}
Kindly help me out, Thank you
Fragment is what you have to use, in this case. Load either of the fragment based on button click.
If you go for setContentView in this scenario, then your code will be clumsy and it will be very tedious for you to keep track on view.

Android setOnClickListener crashes my app on avd

I am new to android dev, I created a new project with NavigationDrawer activity, I use Android Studio. The problem is when I add a button and create OnClickListener, the app crushes, but without it, it launches fine. Please look at my code below.
I tried adding setContentView(View) but doesn't help
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //comes by default
setContentView(R.layout.fragment_main); //added by me, but doesnt help
//referencing my button
btnTest = (Button)findViewById(R.id.btnTest);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getSupportFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
//my event listeners
//when i highlight the below code everythin works..these block cause the crash
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
}
I know others have had these issue and solved it, but I'm not able to solve mine, please help, Thank You
setContentView(R.layout.activity_main); //comes by default
setContentView(R.layout.fragment_main); //added by me, but doesnt help
Don't call setContentView twice. The one that "comes by default" is provided for your convenience when the IDE is generating the Activity class, if you don't need it, delete it.
Secondly, you are setting a fragment layout as View for your Activity. So unless R.id.btnTest is included in that layout, btnTest will be null, hence causing a NullPointerException when calling setOnClickListener.
delete this :
setContentView(R.layout.fragment_main);
and here
setContentView(R.layout.activity_main);
make sure you have a layout file for your Activity that is named activity_main.xml or replace that reference with the name of your layout file.
EDIT : I'm guessing you chose the option in AS to generate a placeholder in your Activity and a Fragment to be added to it. You need to handle the button in the Fragment class, and more importantly, you need to add the Fragment to your Activity.
In your Activity (in OnCreate, after the setup of the nav drawer) :
Fragment newFragment = new ExampleFragment(); // replace ExampleFragment by your Fragment's class name
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.add(CONTENT_VIEW_ID, newFragment).commit(); // CONTENT_VIEW_ID is the id of the View in your Activity that should contain the Fragment.
And then in your Fragment, move this to onActivityCreated :
btnTest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
You will need to inflate R.layout.fragment_main in onCreateView in your Fragment, and get a reference to btnTest from the View you inflate.
Without Logcat I would say that your problem is one of the following:
btnTest is not defined in your ActivityLayout (activity_main). If this is the case check your XML.
Is your btnTest inside your Fragment? If so you should put the OnClickListener in your Fragment class instead of your Activity class.
BTW, the second setContentView doesnt make any sense you should use only one.
Hope it helps

Categories