Why are my buttons not working in Android Studio? - java

I am doing A Level computing and I'm trying to make an app for my Comp 4 project. All the other classes i have done with buttons seem to be working fine but the buttons on my main menu are not working.
public class MainActivity extends AppCompatActivity {
Button bLogin;
Button bProducts;
EditText etName, etAge, etUsername;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onStart() {
super.onStart();
}
#Override
public boolean onCreateOptionsMenu (Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id= item.getItemId();
switch (id) {
case R.id.bLogin:
break;
case R.id.bProducts:
break;
}
return super.onOptionsItemSelected(item);
}
public void ProductsOnClick(View b) {
startActivity(new Intent(".Products"));
switch (b.getId()) {
case R.id.bProducts:
}
}
public void LoginOnClick(View a) {
startActivity(new Intent(".Login"));
switch (a.getId()){
case R.id.bLogin:
}
}
}
This Activity runs but the buttons on the Options Menu don't work.
I am using Android Studio to program this.

Because there is nothing to execute when the menu item is selected, change your code like that:
#Override
public boolean onOptionsItemSelected(MenuItem item){
int id= item.getItemId();
switch (id) {
case R.id.bLogin:
startActivity(new Intent(".Login"));
break;
case R.id.bProducts:
startActivity(new Intent(".Products"));
break;
}
return super.onOptionsItemSelected(item);
}
PS:
Make sure that you're using the right Intent constructor, because with Intent(String) you need an action as parameter not an activity name or something else.

You can use OnClickListener instead. Put this in your onCreate:
bProducts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(".Products"));
}
});
bLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(".Login"));
}
});

Related

Creating a reusable class

I have an application running in Android, i wanna create a Menu and repeat in some activities, that menu calls Intent for open others activities.
How can i do this?
Think maybe i can create a class, but i getting errors. Where can i create a class for that? Inside onCreate method or not?
And how can i reuse the menu in another activity?
Thanks!!
Here is my menu code:
menu_button = (Button) findViewById(R.id.menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(MainActivity.this, menu_button);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
Intent vista = new Intent(MainActivity.this, openCamera.class);
MainActivity.this.startActivity(vista);
}
return true;
/*
Toast.makeText(MainActivity.this, "" + item.getTitle(), Toast.LENGTH_SHORT).show();
return true;
*/
}
});
popupMenu.show();
}
});
If the menu is always the same and you want to reuse it in more than one activity, you just define it like this:
public class TestMenu {
private final PopupMenu popupMenu;
public TestMenu(final Activity activity, View anchor) {
popupMenu = new PopupMenu(activity, anchor);
popupMenu.getMenuInflater().inflate(R.menu.popup_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.one:
Intent vista = new Intent(activity, openCamera.class);
activity.startActivity(vista);
}
return true;
}
});
}
public void show() {
popupMenu.show();
}
}
And then use it in your activity like this:
public class TestActivity extends Activity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button menu_button = (Button) findViewById(R.id.menu_button);
TestMenu myMenu = new TestMenu(this, menu_button);
menu_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
myMenu.show();
}
});
}
}

onSupportNavigateUp() is not fired anymore after I override onOptionsItemSelected(MenuItem item)

(Sorry for changing the whole question as I found the actual problem after troubleshooting)I have my activity as followed:
public class MyAppActivity extends AppCompatActivity{
#Override
protected void onCreate(...)
{
//...
this.setContentView(contentViewResID);
Toolbar toolbar = (Toolbar) this.findViewById(toolbarResID);
this.setSupportActionBar(toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
#Override
protected void onPause() {...}
#Override
protected void onResume() {...}
#Override
public boolean onSupportNavigateUp() {
Log.d("onSupportNavigateUp()", "pressed");
finish();
return super.onSupportNavigateUp();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {...}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {...}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item == menuAddFood) {
Intent intent = new Intent(this, ActivityAddFood.class);
this.startActivity(intent);
}
if (item == menuSettings){
Intent intent = new Intent(this, ActivitySetting.class);
this.startActivity(intent);
}
if(item == menuUsername){
}
return true;
}
}
EDIT:
After my troubleshooting, I found out after override the onOptionsItemSelected(), onSupportNavigateUp() no longer fired anymore when I pressed the top left BACK / UP / HOME button. I want to do finish() inside onSupportNavigateUp() How to solve this?
You have to override the method in your current Activity and call the super:
public class ActivityExample extends MyAppActivity {
Context context = this;
AppCompatActivity activity = this;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.createMyView(R.layout.activity_log_in, R.id.toolbar);
// ...
}
#Override
public boolean onSupportNavigateUp() {
finish();
return true;
}
}
Also, if you override onOptionsItemSelected, then onSupportNavigateUp will not be called.
//DONT OVERRIDE THIS METHOD
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
break;
}
return true;
}

Handle SettingsActivity onBackpressed() the same way as top bar back button

I have a SettingsActivity that has an "up" button included on the top bar. My AettingsActivity also has headers, that load proper settings fragments. By default, when I press the top bar "up" button, it closes the visible fragment and returns to headers, and closes activity if pressed on header view. Howeer, my phone "back" button works different - it just closes the activity. How ca i make "up" arrow and back button work the same way to keep my app consistent? Should I add onBackPressed to my activity, and if so, what should I put there?
My SettingsActivity:
public class SettingsActivity extends AppCompatPreferenceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setupActionBar();
}
private void setupActionBar() {
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
if (!super.onMenuItemSelected(featureId, item)) {
NavUtils.navigateUpFromSameTask(this);
}
return true;
}
return super.onMenuItemSelected(featureId, item);
}
#Override
public void onBuildHeaders(List<Header> target) {
loadHeadersFromResource(R.xml.pref_headers, target);
}
protected boolean isValidFragment(String fragmentName) {
return PreferenceFragment.class.getName().equals(fragmentName)
|| NewsPreferenceFragment.class.getName().equals(fragmentName)
|| OtherPreferenceFragment.class.getName().equals(fragmentName);
}
public static class NewsPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_news);
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
public static class OtherPreferenceFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_other);
setHasOptionsMenu(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
startActivity(new Intent(getActivity(), SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
}
}
This is a default code generated from Android Studio when creating new SettingsActivity, just with some changes made to suit my app
You just need to override onBackPressed() method:
#Override
public void onBackPressed() {
NavUtils.navigateUpFromSameTask(this);
}

Eclipse, new activity on button click

I'm a beginner but I would like to modify an older project.
On the Preferences Activity, there are already few buttons, but I would like to add a new button, which, when clicked, opens a new Activity and shows an image only.
For this I declared this new activity in the Manifest:
<activity
android:name=".VisualHelpActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme" >
</activity>
I declared the button on the associated xml layout:
<Button
android:id="#+id/button_visualhelp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="visual_help"
android:text="Visual Help" />
I created the new VisualHelp layout xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:id="#+id/visualhelp_image"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY"
android:src="#drawable/guide" />
Declared its new VisualHelpActivity java file:
public class VisualHelpActivity extends TranslatableActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visualhelp);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.visual_help, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void refreshLanguage() {
}
}
… and now I’m supposed to connect it all together in the "main" PreferencesActivity, which looks as follows:
public class PreferencesActivity extends TranslatableActivity {
public static String url = "https://www.paypal.com/cgi-bin....";
ImageView donate;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_preferences);
donate = (ImageView) findViewById(R.id.button_donate);
donate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
donate(v);
}
});
Spinner s = (Spinner) findViewById(R.id.combo_language);
Lang[] languages = LanguageUtil.Lang.values();
s.setAdapter(new ArrayAdapter<Lang>(this,
android.R.layout.simple_dropdown_item_1line, languages));
s.setSelection(getPosition(languages, LanguageUtil.getLanguage()), true);
}
private int getPosition(Object[] objs, Object item) {
for (int i = 0; i < objs.length; i++) {
if (objs[i] == item)
return i;
}
return -1;
}
public void update(View v) {
Maintenance.downloadDB(this, new onFinishListener() {
#Override
public void onFinish() {
LanguageUtil.loadLanguage(PreferencesActivity.this);
}
});
}
public void copy(View v) {
Maintenance.copyDB(this, new onFinishListener() {
#Override
public void onFinish() {
LanguageUtil.loadLanguage(PreferencesActivity.this);
}
});
}
public void save(View v) {
LanguageUtil.saveLanguage(this,
(Lang) ((Spinner) findViewById(R.id.combo_language))
.getSelectedItem());
LanguageUtil.loadLanguage(this);
setResult(RESULT_OK);
finish();
}
public void donate(View v) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
}
public void cancel(View v) {
finish();
}
#Override
protected void refreshLanguage() {
((Button) findViewById(R.id.button_update)).setText(LanguageUtil
.getDeviceLabel(LanguageUtil.dev_update));
((TextView) findViewById(R.id.language_label))
.setText(LanguageUtil.getDeviceLabel(LanguageUtil.dev_language));
}
}
According to androidbegin.com, I should add this code into the PreferencesActivity java file (code above):
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_visualhelp);
button = (Button) findViewById(R.id.button_visualhelp);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(PreferencesAtivity.this,
VisualHelpActivity.class);
startActivity(myIntent);
}
});
}
The only problem is that if I try to add this new public void, multiple marker errors pop up, and if I try to include all below somewhere else, my app fails to work. So, can anyone help me out where and how to include this code part to make it work?
add the code inside oncreate method like this in your PreferencesActivity class:-
Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_preferences);
donate = (ImageView) findViewById(R.id.button_donate);
donate.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
donate(v);
}
});
button = (Button) findViewById(R.id.button_visualhelp);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent myIntent = new Intent(PreferencesAtivity.this,
VisualHelpActivity.class);
startActivity(myIntent);
}
});
Spinner s = (Spinner) findViewById(R.id.combo_language);
Lang[] languages = LanguageUtil.Lang.values();
s.setAdapter(new ArrayAdapter<Lang>(this,
android.R.layout.simple_dropdown_item_1line, languages));
s.setSelection(getPosition(languages, LanguageUtil.getLanguage()), true);
}

onBackPressed() doesn't work for me

I have a problem, which is also discussed here:
onBackPressed never gets called
I'm trying to cancel a CountDownTimer when pressing the native back button from an android phone. So I would like to overrite the onBackPressed method, to cancel the timer and return to another activity, but only once. (to return to the main activity, like a home button).
This is a part of the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (getResources().getConfiguration().orientation== Configuration.ORIENTATION_LANDSCAPE){
ImageView und1=(ImageView)findViewById(R.id.undita1);
ViewGroup.LayoutParams params = (ViewGroup.LayoutParams) und1.getLayoutParams();
params.height=150;
und1.setLayoutParams(params);
ImageView und2=(ImageView)findViewById(R.id.undita2);
ViewGroup.LayoutParams params2 = (ViewGroup.LayoutParams) und2.getLayoutParams();
params2.height=150;
und2.setLayoutParams(params2);
ImageView und3=(ImageView)findViewById(R.id.undita3);
ViewGroup.LayoutParams params3 = (ViewGroup.LayoutParams) und3.getLayoutParams();
params3.height=150;
und3.setLayoutParams(params3);
}
mProgressBar=(ProgressBar)findViewById(R.id.progressBar);
mProgressBar.setProgress(0);
mCountDownTimer=new CountDownTimer(90000,1000) {
int i=0;
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress" + i + millisUntilFinished);
i++;
mProgressBar.setProgress(i); }
#Override
public void onFinish() {
i++;
mProgressBar.setProgress(i);
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
}
};
mCountDownTimer.start();
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
Bundle b;
b = getIntent().getExtras();
nivel= b.getInt("level");
TextView niv=(TextView) findViewById(R.id.Nivel);
niv.setText("Level: "+ nivel);
generare_3_diferente(nivel);}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my, menu);
return true;}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) { //Back key pressed
mCountDownTimer.cancel();
Intent in = new Intent(getApplicationContext(), MyActivity2.class);
startActivity(in);
mCountDownTimer.cancel();
return true;
}else{
return super.onKeyDown(keyCode, event);
}
}
#Override
public void onBackPressed(){
mCountDownTimer.cancel();
Intent in = new Intent(this, MyActivity2.class);
startActivity(in);
super.onBackPressed();
}
}
the onBackPressed should be in the main activity class
Also try to specify the parent and child activities in the manifest file of the app e.g
android:parentActivityName
and try to use something like this and rebuild your App
#Override
public void onBackPressed() {
super.onBackPressed();
i = new Intent(CurrentActivity.this, NextActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
finish();
}
if it still doesn't work try to make a new application and import your files

Categories