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.
Related
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!
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.
This is my code by the way the Context Compat can not resolve
private FloatingActionButton getFAB() {
FloatingActionButton fab = new FloatingActionButton(this);
fab.setImageDrawable(ContextCompat.getDrawable(getContext(), R.drawable.fire));
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//"insert into Checks (ID,CheckSerail,CheckTitel,CheckType,Covers,MyTable,MyStatus,Splited,RefranceTo,myDateTime,OpenIn,ClosedIn,Cust_ID,Server_ID,Casher_ID,Admin_ID,OutLet_ID,Rest_ID_Active,WS,CreateDate,ModifiedDate,Num_Fired,User_ID,Voided,Voided_Time,Voided_Reason,Order_No,ReOpen,Table_ID,Num_Print,Lvl_Split,ChangeAfterSplit,Combined,Combined_To,ChangeAfterCombine,Received,Received_Time,Point_ID,Meal_ID,Voided_By,Catering_ID,Pick_Up,Pick_Up_Time,Officer) values (#ID,#CheckSerail,#CheckTitel,'DinIn',#Covers,#MyTable,'Open',0,0,GetDate(),#OpenIn,#ClosedIn,#Cust_ID,#Server_ID,#Casher_ID,#Admin_ID,#OutLet_ID,#Rest_ID_Active,#WS,#CreateDate,#ModifiedDate,#Num_Fired,#User_ID,#Voided,#Voided_Time,#Voided_Reason,#Order_No,#ReOpen,#Table_ID,#Num_Print,#Lvl_Split,#ChangeAfterSplit,#Combined,#Combined_To,#ChangeAfterCombine,#Received,#Received_Time,#Point_ID,#Meal_ID,#Voided_By,#Catering_ID,#Pick_Up,#Pick_Up_Time,#Officer)";
}
});
return fab;
}
Add this line on top of Activity class
import android.support.v4.content.ContextCompat;
change getContext() to YourActivityClassName.this
I'm getting a NullException error on my Button setOnClickListener() method. I'm a bit flabbergasted as to why this is happening. Please bear in my mind that this is my first Android app, and I assume that there are bound to be some runtime errors (there are no compilation errors).
btnNaira.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dollarToNaira();
}
});
The dollarToNaira() method can be found here:
public void dollarToNaira() {
try {
dollarAmt = txtAmount.getText().toString();
nairaAmt = (Double.parseDouble(dollarAmt) * 199.00);
lblOutput.setText(dollarAmt + "U.S. Dollars = " + nairaAmt + " Nigerian Naira.");
}catch(Exception ex) {
message = "Please enter a valid numerical amount";
lblOutput.setText(message);
}finally {
txtAmount.requestFocus();
txtAmount.selectAll();
}
}
Please tell me what I am doing wrong I would like to know what causes the setOnClickListener method to return NULL. Thanks!
EDIT: this is the entire onCreate() method, I don't believe that I made an error:
protected void onCreate(Bundle savedInstanceState) {
txtAmount = (EditText) findViewById(R.id.txtAmount);
btnNaira = (Button) findViewById(R.id.btnNaira);
btnCFA = (Button) findViewById(R.id.btnCFA);
lblOutput = (TextView) findViewById(R.id.lblOutput);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//set up event listener on btnNaira and btnCFA
btnNaira.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dollarToNaira();
}
});
btnCFA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dollarToCFA();
}
});
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();
}
});
}
there is no problem in your code.
i guess you've made a mistake in initializing buttons and text views.
1- make sure that you define your listener inside a method, like onCreate(),
i think you had defined that in class body.
2- i guess that you had defined your button or text views,
but you did not initialized them , so they are null.
here is an example of initializing a Button
Button btnDoSomething = (Button)findViewById(R.id.idOfButton);
now you can setOnClickListener for it .
You should write in this way
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtAmount = (EditText) findViewById(R.id.txtAmount);
btnNaira = (Button) findViewById(R.id.btnNaira);
btnCFA = (Button) findViewById(R.id.btnCFA);
lblOutput = (TextView) findViewById(R.id.lblOutput);
Make sure you call setContentView(R.layout.activity_main); before initialize your button View.
Hope it helps.
I have a main activity that extents ActionBarActivity and implements ActionBar.TabListener
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
View mView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set up the action bar.
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will 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.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding
// tab. We can also use ActionBar.Tab#select() to do this if we have
// a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by
// the adapter. Also specify this Activity object, which implements
// the TabListener interface, as the callback (listener) for when
// this tab is selected.
actionBar.addTab(
actionBar.newTab()
.setText(mSectionsPagerAdapter.getPageTitle(i))
.setTabListener(this));
}
}
}
When a button is clicked on one of the fragments controlled by MainActivity, I have to create an intent and start another activity:
public void goToHighScore(View view) {
Intent intent = new Intent(this, DisplayScoreActivity.class);
//TextView nView = (TextView) mViewPager.getChildAt(2).findViewById(R.id.label);
TextView nView = (TextView) findViewById(R.id.label);
String highScore = nView.getText().toString();
intent.putExtra(HIGH_SCORE, highScore);
startActivity(intent);
}
However the "highScore" value is always the one equal to the fragment proceeding it?
All answers are appreciated. Thank you for bearing with me.
-Paul T.
You can get the current fragment by:
Fragment currentFragment = mSectionsPagerAdapter.getItem(mViewPager.getCurrentItem());
Update your fragment to get the score:
Class CustomFragment extends Fragment{
private TextView nView;
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
nView = view.findViewById(R.id.label);
}
public String getScore(){
return nView.getText().toString();
}
}
And function will look like:
public void goToHighScore(View view) {
Intent intent = new Intent(this, DisplayScoreActivity.class);
Fragment currentFragment = mSectionsPagerAdapter.getItem(mViewPager.getCurrentItem());
String highScore = currentFragment.getScore();
intent.putExtra(HIGH_SCORE, highScore);
startActivity(intent);
}
However, I will suggest you to handle the onClick event in your fragment to provide better encapsulation. Update your fragment as follows:
Class CustomFragment extends Fragment{
private TextView nView;
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
nView = view.findViewById(R.id.label);
Button button = (Button)findViewByid(R.id.button)
button.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
String highScore = nView.getText().toString()
intent.putExtra(HIGH_SCORE, highScore);
startActivity(intent);
}
});
}
}
By doing this your Fragment can be attached to different activity without functionality broke down.