'How can i get my buttons working for Android Studio?
I have an Activity which has two buttons on it. The first button adds the user data to a database and the second takes us to a different activity. The buttons in my main activity are working but not in this activity. The code seems to be correct.
Activity:
public class addData extends AppCompatActivity {
EditText addName, addAge, addWeight;
Button addDatatoDB, goToCalcIntake;
personInfo personInfodDB;
final int ltrPerKg = 30;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.add_data);
addName = (EditText) findViewById(R.id.addName);
addWeight = (EditText) findViewById(R.id.addWeight);
addAge = (EditText) findViewById(R.id.addAge);
addDatatoDB = (Button) findViewById(R.id.addDatatoDatabase);
goToCalcIntake = (Button) findViewById(R.id.goTo);
personInfodDB = new personInfo(getApplicationContext());
addDatatoDB.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String name = addName.getText().toString().trim();
int weight = Integer.valueOf(addWeight.getText().toString().trim());
int age = Integer.valueOf(addAge.getText().toString().trim());
int intake = weight/ltrPerKg;
personInfodDB.addInfo(name,weight,age,intake);
}
});
goToCalcIntake.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
setContentView(R.layout.show_intake);
}
});;
}
}
<Button
android:id="@+id/goTo"
android:layout_width="168dp"
android:layout_height="77dp"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_marginEnd="16dp"
android:layout_marginBottom="22dp"
android:text="Calculate your intake here" />
Solution 1:[1]
Try this.
goToCalcIntake.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
Intent i = new Intent(MainActivity.this, show_intake.class);
startActivity(i);
}
});;
I assume that your next activity is called "show_intake" I cut the code my own working project.
Solution 2:[2]
make sure you declare and initialize.
declare
Button goToCalcIntake;
initialize
goToCalcIntake= findViewById(R.id.btnaddStudent);
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Isaiah Donkor |
Solution 2 | Isaiah Donkor |