Using buttons on android - newbie - java

I am a newbie to android development, trying to get buttons working. every time i use this code below, the error message "unfortunately the app has stopped". but when i remove the code the app runs but obviously the buttons do nothing. here is the code ive tried
public class MyActivity extends Activity {
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button button1 = (Button) findViewById(R.id.ExerciseButton);
button1.setOnClickListener (new View.OnClickListener(){
public void onClick(View v) {
setContentView(R.layout.exercises);
}
});
}
}
anybody able to help me out there? thanks

Don't try to load another View in the current activity. Navigate to a new ExercisesActivity.
Use:
public void onClick(View v) {
Intent intent = new Intent(ExercisesActivity.this, WcActivity.class);
startActivity(intent);
}

You can't call setContentView anymore after the view has loaded (which it obviously has to receive button clicks). Use a different approach, like showing and hiding views or using a ViewFlipper (see Calling setContentView() multiple times), using fragments (see Fragments) or starting a new activity.

Well, from your code, I see a couple of things:
I am usually familiar to using the onClickListener of the Button class if I want to use it for a button. Makes sense, doesn't it?
buttonOne.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
//Do stuff here
}
Second thing:
Start a new Activity (if that is what you want) by using an Intent:
Intent myIntent = new Intent(this, exercises.class);
startActivity(myIntent);

You CAN absolutaly call setContentView on any event, even after the view has loaded
I tried your code in a demo project and it is working fine. So, i think the error will be some where in your layout.(Let me know more if you need more help on this)

Related

multiple click on single button while opening from one fragment to another?

I have created an application which uses the fragment, I am opening a fragment on the click of the first fragment with custom animation, meanwhile the animation is going on I am able to click the button on the first fragment and it creates 2 fragments. how can I not click on my button while moving from one fragment to another, I just don't want double click of the same button.
can anyone help me?
Try below
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
view.setEnabled(false);
}
});
// on animation complete, enable it
// button.setEnabled(true);
You could try set android:clickable in your XML layout to determine whether a button can be clicked.
You could implement the following method into your code and call it when needed.
public void myMethod(boolean isLoading){
myButton.setEnabled(!isLoading);
}
button.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {view.setEnabled(false);}
});
Try using myButton.setEnabled(false) in your click callback function.
Try the below kotlin snippet
view.setOnClickListener {
val tag = "my_dialog"
val oldFragment: Fragment? = supportFragmentManager.findFragmentByTag(tag)
if(!(oldFragment?.isAdded == true)) {
val myDialogFragment = MyDialogFragment.newInstance()
myDialogFragment.show(supportFragmentManager, tag)
}
}
In case a fragment(with the tag specified) is already added to the activity then this code prevents new fragment creation and adding it to the activity.

Switching activities loses functionality

I have an app that consists of 3 Activities
MainActivity
CalculatorActivity
InformationActivity
My MainActivity has a confirm button that onClick starts the CalculatorActivity and everything is done correct and working as intended.
CalculatorActivity has 2 buttons, one calculateButton that checks something and shows a message and a learnMorebutton that starts the InformationActivity.
When I am on the
CalculatorActivity for the first time everything is fine and working.Pressing the learnMoreButton navigates me to the InformationActivity.That activity looks like this :
InformationActivity:
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switchActivity();
}
});
}
public void switchActivity(){
final Intent intentObj = new Intent(this,CalculatorActivity.class);
startActivity(intentObj);
}
A goBack button that gets me back to CalculatorActivity.Going back seems to break the functionality.Although the layout is there and everything looks as it should be, pressing the buttons (calculateButton,learnMoreButton) does nothing.
CalculatorActivity :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
final Button calculateButton = (Button) findViewById(R.id.calculateId);
final Button learnMoreButton = (Button) findViewById(R.id.learnMoreButtonId);
there are some more TextView and EditText that dont show up here but you get the point.Some more methods that do the calculations ,getters and setters.
This method
public void switchActivity(){
final Intent intentObj = new Intent(this,Information_activity.class);
startActivity(intentObj);
}
But I am not using onResume() , onPause() or any methods from the lifecycle apart from onCreate().
From some search that I have done I found out that I am doing something wrong with how I manage the activity lifecycle but I still can't find the solution.The dev documents didn't help me that much and a post with kinda the same problem as mine is old.
My question is, how the navigation from InformationActivity to CalculatorActivity should be done, so the functionality doesn't break when CalculatorActivity comes back to interact with the user.Which method should be called onResume()? , onRestart()? and how should it look like?
Thanks anyone who is willing to help.
P.S: As I mentioned , I have read the documents for the lifecycle of an Activity but I haven't found the solution.
instead of starting new activity everytime, finish the informationactivity.
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
You are creating too much activities moving going back and forth this way. You can use either destroy the activity with finish(); or you can also go back to previous activity using onBackPressed();
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
Try this out
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
InformationActivity.this.finish();
}
});
}
Instead of saying where to go back, you can just finish the activity and it will automatically switch you to the previous one.
I think your activities are hierarchical thus you should be able to do the following from your main calculator activity:
Intent i = new Intent(this, InformationActivity.class);
startActivityForResult(i);
Your back button add this code:
goBackButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setResult(Result.OK);
finish();
}
});
You are all suggesting the same thing.Adding
Information_Activity.this.finish()
fixed the broken functionality , though you are all correct I can pick only one answer.
Thanks

Need to Navigate to next page Android Bluetooth

I am very new to Andriod Programming and this is probably very basic question.
In my Application, the first page contains just button (for simplicity) login button.
After the user clicks login button it displays the toast and then I need to navigate to new class(page B) where I want to connect to a specific health sensor.
Problem
1. I tried implementing the just the basic part with onClickListener for button and then when clicked, go to next page, where enable Bluetooth,etc. I could not get to next page
MainActivity.java :
public class MainActivity extends AppCompatActivity {
Button button;
PollingTest pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button)findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getBaseContext(),"Logged In",Toast.LENGTH_SHORT).show();
pd = new PollingTest();
pd.call();
}
});
}
}
Second Page (Where wanted to Control BT). Never got to this page while testing on the tablet: -
For now just included if I could get a Toast atleast from this page: -
public class PollingTest extends Activity {
BluetoothAdapter btAdapter;
Button btn2;
protected void call() {
//super.onCreate(savedInstanceState);
//setContentView(R.layout.pairinglistactivity);
btn2 = (Button)findViewById(R.id.pollB);
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "hello", Toast.LENGTH_LONG).show();
}
});
}
}
Here app crashes after clicking on Login button in first page.
I have actually got some different errors with different code, I was not able to make proper Toast or turn BT on in the second page as it was trying them in static method.( very Confusing:( )
Please help me. I know this v v basic Q..
EDIT:
Sorry, this Q is already answered here: -
Moving from one activity to another Activity in Android
You don't start an activity by instantiating it like a normal Java class. So this is wrong
pd = new PollingTest();
pd.call();
you should be using an Intent
and follow the Activity Lifecycle
so you would want something like
Intent i = new Intent(MainActivity.this, PollingTest.class);
startActivity(i);
then override onCreate() in PollingTest.java and put what is in call() in there or call that method from onCreate().
Also, a Toast should use Activity Context

Placement of OnActivityResult with OnClicklistener

I have implemented a 3rd party camera scanning app within a project of mine
I have an adaptor that extends a viewholder so i can have a custom layout
Within a view i have a button
When i create the view i add an OnclickListener to the image which i want to make clickable
i want this OnclickListener to call the camera but i need to call an startActivityForResult
i am confused about the placement of the onActivityResult when calling in this way.
my current attempts have been to create a seperate class(scan_activity) which extends activity but i couldnt get the onclicklistener to start the class
i have then attempted to declare it within the setOnClickListener, which as you can guess also failed.
Im guessing the call to the class is the way forward.im sure its an easy fix, but im not seeing it
please help
thanks in advance
imgCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ScanActivity.class);
intent.putExtra(ScanConstants.OPEN_INTENT_PREFERENCE, 1);
((Activity) context).startActivityForResult(intent,99);
}
}
);
and the class
imgCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ScanActivity
}
}
);
The first option should work. You create an Intent object and you specify activity component as a parameter. Android will create an Activity object for you, so, never do that manually. Android should manage the lifecycle of activity.
By starting activity for result you tell Android that it should call onActivityResult callback with request code 99 on your first activity when ScanActivity will be closed.
Handling onActivityResult in your Activity:
#Override
public void onActivityResult (int requestCode, int resultCode, Intent data) {
if (requestCode == 99) {
// handle your result here
}
}

Opening Android system apps/utilities

I am learning Android. I learned to use my app to start another app I wrote. Using this code below:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button appOpener = (Button) findViewById(R.id.button1);
appOpener.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent i = new Intent(Intent.ACTION_MAIN);
PackageManager firstApp = getPackageManager();
i = firstApp.getLaunchIntentForPackage("com.assignment.projecttomiko");
}
});
}
It's pretty straight-forward and I am happy wit it. But now I want to start apps already on the Android platform itself, like browser, calender, calculator, etc. From the above, I see I just have to put in the package name of my other apps. I am assuming I can do the same thing to say start a calculator. Or maybe not. What is the best way to do this? If I can use package names, then what are the package names of these in-built apps. If there's a better way I would like someone to help me out.
I read this: Opening System Application Using Intent and realised there's an introduction of an extra LaunchComponent I don't know what that is but the main thing is I see on that thread that they are also putting in some package names to call system apps. What'll be your best way to get this done? :)
EDIT:
I searched for hours and tried this code but doesn't work :(
// activity name and package for stock calculator
private static final String CALCULATOR_PACKAGE_NAME = "com.android.calculator2";
private static final String CALCULATOR_CLASS_NAME = "com.android.calculator2.Calculator";
public void launchCalculator() {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setComponent(new ComponentName(CALCULATOR_PACKAGE_NAME,
CALCULATOR_CLASS_NAME));
try {
this.startActivity(intent);
} catch (ActivityNotFoundException noSuchActivity) {
// handle exception where calculator intent filter is not registered
}
}

Categories