I am writing a mobile application and have attached a popup menu to an ImageButton through that button's OnClick method.
menu_lilac.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
showPopup(view);
}
});
I am trying to make it so pressing the menu item redirects to the relevant Activity (in the switch statement at the end).
The error I get is Error:(23, 8) error: MainActivity is not abstract and does not override abstract method onMenuItemClick(MenuItem) in OnMenuItemClickListener.
public void showPopup(View view) {
PopupMenu popup = new PopupMenu(this, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.mainmenu, popup.getMenu());
MenuItem item = (MenuItem) popup.getMenu();
popup.show();
//Intent to Tasks Activity
final Intent toTasks = new Intent(this, TasksActivity.class);
//Intent to Distractions Activity
final Intent toDist = new Intent(this, DistractionsActivity.class);
//Intent to Settings Activity
final Intent toSett = new Intent(this, SettingsActivity.class);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.Home:
return true;
case R.id.Tasks:
startActivity(toTasks);
return true;
case R.id.Distractions:
startActivity(toDist);
return true;
case R.id.Settings:
startActivity(toSett);
return true;
default:
return false;
}
}
});
}
What am I doing wrong? I tried initialising the OnMenuItemClickListener in a different way such as
PopupMenu.OnMenuItemClickListener listener = PopupMenu.OnMenuItemClickListener(){
}
but listener is never used and the app crashes when any of the menu buttons are pressed.
Full MainActivity class:
import android.app.Activity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.NumberPicker;
import android.widget.PopupMenu;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ListView;
public class MainActivity extends Activity implements PopupMenu.OnMenuItemClickListener {
//Creation of used objects
//Button, Button, TextView, Handler, AlarmManager, NumberPicker, Pending Intent
//Context, TextView, Button
Button startButton;
Button stopButton;
TextView timerValue;
Handler customHandler = new Handler();
NumberPicker interval_length;
PendingIntent pending_intent;
Context context;
TextView checker;
ImageButton menu_lilac;
Intent toDist;
Intent toSett;
Intent toTasks;
//Creation of variables
long timeInMilliseconds = 0L;
long updatedTime = 0L;
long startTime = 0L;
int picked_value;
private static int minValueInterval = 1;
private static int maxValueInterval = 60;
int final_interval;
//On create function initialises the layout
#Override
protected void onCreate(Bundle savedInstanceState) {
//Creation of main GUI layout
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context = this;
}
#Override
protected void onStart() {
super.onStart();
//Initialise number picker
interval_length = (NumberPicker) findViewById(R.id.interval_length);
//Set minimum value (minutes)
interval_length.setMinValue(minValueInterval);
//Set maximum value (minutes)
interval_length.setMaxValue(maxValueInterval);
//Set currently displayed value (minutes)
interval_length.setValue(20);
//Initialise listener to listen for a value change on the number picker
interval_length.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
//Replace variable picked_value with the new value of the number picker
picked_value = interval_length.getValue() - 1;
}
});
//Initialise timerValue text box
timerValue = (TextView) findViewById(R.id.timerValue);
//Initialise start button
startButton = (Button) findViewById(R.id.startButton);
//Initialise instance of stop button
stopButton = (Button) findViewById(R.id.stopButton);
//Initialise instance of menu button
menu_lilac = (ImageButton) findViewById(R.id.menu_lilac);
//Initialise checker text box
checker = (TextView) findViewById(R.id.checker);
//Menu button onClickListener
menu_lilac.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
showPopup(view);
}
});
//Start button OnClickListener
startButton.setOnClickListener(new View.OnClickListener() {
//On start begin counting up in milliseconds.
//Reset timer every time Start button is pressed.
public void onClick(View view) {
timerValue.setText("00:00");
startTime = SystemClock.uptimeMillis();
customHandler.postDelayed(updateTimerThread, 0);
//Set text box to print a message displaying when the alarm is for
checker.setText("The alarm has been set for " + picked_value + " minutes from now!");
//Make pop-up toast notification
Toast.makeText(context,"Alarm on!", Toast.LENGTH_LONG).show();
}
});
//Calculation of picked interval length (from minutes) to milliseconds
final_interval = picked_value * 60 * 1000;
if (timerValue.equals(picked_value+":00")) {
alarm_manager.set(AlarmManager.RTC_WAKEUP, timeInMilliseconds, pending_intent);
}
//Initialise Stop button OnClickListener
stopButton.setOnClickListener(new View.OnClickListener() {
//On click stop updating timer thread and reset value to 00:00
public void onClick(View view) {
customHandler.removeCallbacks(updateTimerThread);
timerValue.setText("00:00");
//print message to notify user of alarm being cancelled
checker.setText("The alarm has been cancelled!");
//Make toast notification to say alarm cancelled
Toast.makeText(context,"Alarm off!", Toast.LENGTH_LONG).show();
}
});
}
//Creates a runnable to update the timer
private Runnable updateTimerThread = new Runnable() {
public void run() {
//Takes time in milliseconds from the system clock
timeInMilliseconds = SystemClock.uptimeMillis() - startTime;
updatedTime = timeInMilliseconds;
//Converts milliseconds to seconds and minutes
int secs = (int) (updatedTime / 1000);
int mins = secs / 60;
secs = secs % 60;
int milliseconds = (int) (updatedTime % 1000);
//Updates timerValue to the formatted 00:00 (minutes:seconds)
timerValue.setText(String.format("%02d", mins) + ":"
+ String.format("%02d", secs));
customHandler.postDelayed(this, 0);
}
};
public Runnable showPopup(View view) {
PopupMenu popup = new PopupMenu(this, view);
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.mainmenu, popup.getMenu());
MenuItem item = (MenuItem) popup.getMenu();
popup.show();
//Intent to Tasks Activity
final Intent toTasks = new Intent(this, TasksActivity.class);
//Intent to Distractions Activity
final Intent toDist = new Intent(this, DistractionsActivity.class);
//Intent to Settings Activity
final Intent toSett = new Intent(this, SettingsActivity.class);
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener(){
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.Home:
return true;
case R.id.Tasks:
startActivity(toTasks);
return true;
case R.id.Distractions:
startActivity(toDist);
return true;
case R.id.Settings:
startActivity(toSett);
return true;
default:
return false;
}
}
});
}
}
Fixed! I removed the "implements PopupMenu.OnMenuItemClickListener" from my class declaration and re-did the PopupMenu all over again. This time I used if statements instead of a switch statement and instead of calling MenuInflater I just used inflate() on popup.
These are the needed imports:
import android.view.MenuItem;
import android.widget.PopupMenu;
My class declaration:
public class MainActivity extends Activity {
These are my intents:
//Intent to Tasks Activity
final Intent toTasks = new Intent(this, TasksActivity.class);
//Intent to Distractions Activity
final Intent toDist = new Intent(this, DistractionsActivity.class);
//Intent to Settings Activity
final Intent toSett = new Intent(this, SettingsActivity.class);
And this is my popup menu.
//Menu button onClickListener
menu_lilac.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//create instance of PopupMenu
PopupMenu popup = new PopupMenu(getApplicationContext(), view);
//inflate menu with layout mainmenu
popup.inflate(R.menu.mainmenu);
popup.show();
//Set on click listener for the menu
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
if (item.getItemId()== R.id.Home){
Toast.makeText(context, "At home!", Toast.LENGTH_LONG).show();
}
if (item.getItemId() == R.id.Tasks){
startActivity(toTasks);
}
if (item.getItemId() == R.id.Distractions){
startActivity(toDist);
}
if (item.getItemId() == R.id.Settings){
startActivity(toSett);
}
return false;
}
});
}
});
I don't see reason why you actually implement interface PopupMenu.OnMenuItemClickListener in your activity, but if there is reason, you must implement methods of that interface.
So basically you must have implementation of that method in MainActivity:
#Override
public boolean onMenuItemClick(MenuItem item) {
return false;
}
Also hopefully you use Android Studio. It should say you about error and if you will put pointer on error and click "ALT+ENTER" you will see Implement methods item in menu, clicking on which will solve that problem.
May be helpful for late visitors
public class MainActivity extends AppCompatActivity implements PopupMenu.OnMenuItemClickListener {
ImageButton mainMenu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainMenu = findViewById(R.id.ibtn_menu);
mainMenu.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showMenu(view);
}
});
}
public void showMenu(View v) {
PopupMenu popup = new PopupMenu(this, v);
// This activity implements OnMenuItemClickListener
popup.setOnMenuItemClickListener(this);
popup.inflate(R.menu.main_menue);
popup.show();
}
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_day_view_about: {
Toast.makeText(MainActivity.this,"Clicked on the action", Toast.LENGTH_LONG).show();
return true;
}
}
return true;
}
}
My problem was that I implemented wrong OnMenuItemClickListener,
I needed:
PopupMenu.OnMenuItemClickListener
and I had:
MenuItem.OnMenuItemClickListener
Related
I have an android app in which I have an activity and a service.
The service is supposed to play music and switch between four songs (depends on what button you press)
The problem is that a few minutes/seconds (it's not always at the same time) after you start the service by playing a song a notification pop ups which claims that the 'app has stopped responding' (with the option to wait and the option to exit). If you press the wait button the notification just goes away and the app and music continues the same. The notification will keep coming back though and unfortunately I am not sure why.
Should probably mention that this only happens to me when the service is on. I have tested this app many times. Never have a notification like that. Only when music is played.
My service:
package com.example.project25112021;
import android.app.Service;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class MyService extends Service {
MediaPlayer mediaPlayer;
MediaPlayer mediaPlayer2;
MediaPlayer mediaPlayer3;
MediaPlayer mediaPlayer4;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.stronger);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
mediaPlayer2 = MediaPlayer.create(this, R.raw.silksonic);
mediaPlayer2.setLooping(true); // Set looping
mediaPlayer2.setVolume(100, 100);
mediaPlayer3 = MediaPlayer.create(this, R.raw.davidguetta);
mediaPlayer3.setLooping(true); // Set looping
mediaPlayer3.setVolume(100, 100);
mediaPlayer4 = MediaPlayer.create(this, R.raw.beatit);
mediaPlayer4.setLooping(true); // Set looping
mediaPlayer4.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
int number = intent.getIntExtra("key", 0);
mediaPlayer.start();
mediaPlayer2.start();
mediaPlayer3.start();
mediaPlayer4.start();
mediaPlayer.seekTo(0);
mediaPlayer2.seekTo(0);
mediaPlayer3.seekTo(0);
mediaPlayer4.seekTo(0);
mediaPlayer.pause();
mediaPlayer2.pause();
mediaPlayer3.pause();
mediaPlayer4.pause();
if (number == 0){
mediaPlayer.start();
}
if (number == 1){
mediaPlayer2.start();
}
if (number == 2){
mediaPlayer3.start();
}
if (number == 3){
mediaPlayer4.start();
}
return startId;
}
//public void onStart(Intent intent, int startId) { }
#Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public void onLowMemory() {
}
}
The activity in which you choose what song to play:
package com.example.project25112021;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
public class SettingsMain extends AppCompatActivity {
Button button;
Button song1;
Button song2;
Button song3;
Button song4;
ImageView album1;
ImageView album2;
ImageView album3;
ImageView album4;
Drawable drawable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_main);
drawable = CameraBackground.getInstance().getBitmap();
LinearLayout relative = (LinearLayout) findViewById(R.id.ButtonFinBack);
if(drawable!= null) {
relative.setBackgroundDrawable(drawable);
}
else
relative.setBackgroundResource(R.drawable.bacckga1);
button = findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(SettingsMain.this, MainActivity.class);
startActivity(intent);
}
});
song1 = findViewById(R.id.song1);
song2 = findViewById(R.id.song2);
song3 = findViewById(R.id.song3);
song4 = findViewById(R.id.song4);
album1 = findViewById(R.id.album1);
album2 = findViewById(R.id.album2);
album3 = findViewById(R.id.album3);
album4 = findViewById(R.id.album4);
album1.setImageResource(R.drawable.kanye);
album2.setImageResource(R.drawable.silksonic);
album3.setImageResource(R.drawable.davidguetta);
album4.setImageResource(R.drawable.mjthriller);
song1.setText("Play");
song2.setText("Play");
song3.setText("Play");
song4.setText("Play");
song1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",0);
startService(intent);
}
});
song2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",1);
startService(intent);
}
});
song3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",2);
startService(intent);
}
});
song4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SettingsMain.this, MyService.class);
intent.putExtra("key",3);
startService(intent);
}
});
}
}
Thanks
So here is the link of the application:-Nearpeer-Offline messenger
So After integrating firebase, sometimes while i am restarting this application i got stuck at first activity (mainactivity), its hang and after 10-20 sec later, error comes "application not responding" and app closes.
I already ask question before here :- link
But didn't get good response response.
Here i am providing an MainActivity code:-
package com.nearpeer.app;
/**
*
* Wifi-Direct based multi-user chat application
*
*/
import java.util.Locale;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.Secure;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.analytics.FirebaseAnalytics;
/**
* The app's main entry point. Holds 2 fragments: {#link ChatSearchScreenFrag} and {#link ChatHistoryScreenFrag}.
* The 1st fragment offers to scan for new chat groups and users. The 2nd offers to view chat history.
*/
public class MainScreenActivity extends FragmentActivity implements ActionBar.TabListener
{
private AlertDialog mDialog=null;
private OnClickListener AlertCheckBoxClickListener=null; //used to handle check-box click events for a dialog
SectionsPagerAdapter mSectionsPagerAdapter; //adapter for the tab view. Contains all the frags
ViewPager mViewPager; //a layout widget in which each child view is a separate page (a separate tab) in the layout.
//both fragment will initialize these references when they're created:
public ChatHistoryScreenFrag mHistoryFrag = null;
public ChatSearchScreenFrag mSearchFrag = null;
boolean isServiceStarted = false;
boolean wasWifiDialogShown = false;
static int mDisplayedFragIndex = 0;
public static long ChatRoomAccumulatingSerialNumber=0;
public static String UniqueID=null;
public static String UserName = ":>~"; //setting a default user name
static boolean isToNotifyOnNewMsg = false; //defines if notifications should be shown on arrival of new messages
static int RefreshPeriodInMs = 30000; //defines the peer refresh period
private boolean mIsRunForTheFirstTime=false;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
//FirebaseAnalytics mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
/*Bundle bundle = new Bundle();
bundle.putString(FirebaseAnalytics.Param.ITEM_ID, id);
bundle.putString(FirebaseAnalytics.Param.ITEM_NAME, name);
bundle.putString(FirebaseAnalytics.Param.CONTENT_TYPE, "image");
mFirebaseAnalytics.logEvent(FirebaseAnalytics.Event.SELECT_CONTENT, bundle);*/
try {
InitializeTabHandlerAndAdapter();
if (!isServiceStarted && ChatSearchScreenFrag.mService == null) {
startService(new Intent(this, LocalService.class));
isServiceStarted = true;
}
getPrefs(); //get the shared prefs
//Happens only when the app is run for the very 1st time on a device
if (MainScreenActivity.UniqueID == null) {
UserName = new String(Secure.getString(getContentResolver(), Secure.ANDROID_ID)); //get a unique id
UniqueID = new String(UserName);
}//if
//Remove the title bar for out entire app
getActionBar().setDisplayShowTitleEnabled(false);
getActionBar().setDisplayShowHomeEnabled(false);
}catch (Exception e){
Toast toast = Toast.makeText(getApplicationContext(), "Soory! Try after some time.",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 10);
toast.show();
}
}//end of onCreate()
#Override
protected void onResume()
{
super.onResume();
//check if this activity was launched by the b-cast receiver after a wifi shutdown
try {
boolean isToDisplayWifiDialog = getIntent()
.getBooleanExtra(Constants.WIFI_BCAST_RCVR_WIFI_OFF_EVENT_INTENT_EXTRA_KEY, false);
if (isToDisplayWifiDialog && !wasWifiDialogShown) {
new EnableWifiDirectDialog().show(getSupportFragmentManager(), "MyDialog"); //show a dialog
wasWifiDialogShown = true;
}
//if this app is run for the very 1st time, we want to launch the settings activity first.
if (mIsRunForTheFirstTime) {
//launch the preferences activity
startActivity(new Intent(this, QuickPrefsActivity.class));
mIsRunForTheFirstTime = false;
}
}catch (Exception e){
Toast toast = Toast.makeText(getApplicationContext(), "Soory! Try after some time.",
Toast.LENGTH_SHORT);
toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 10);
toast.show();
}
}
#Override
protected void onPause()
{
super.onPause();
savePrefs(); //save the preferences
}//end of onPause()
private void InitializeTabHandlerAndAdapter()
{
// Set up the action bar (enable tab display).
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the two
// primary sections of the app.
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
//if a tab was changed by a swipe gesture
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position); //update the tab bar to match the selected page
mDisplayedFragIndex=position; //update the index of the currently displayed frag
if (position==1) //if the view has moved to the history fragment:
{
mHistoryFrag.loadHistory(); //reload the history list view
}
invalidateOptionsMenu();
}
});
// 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));
}//for
}//end of InitializeTabHandlerAndAdapter()
/**
* Used to modify menu item according to the app's state
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
super.onPrepareOptionsMenu(menu);
//Check wifi state.
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
if(mWifi.isConnected()||wifi.isWifiEnabled()) {
ChatSearchScreenFrag.mIsWifiDirectEnabled = true;
}
//if the wifi-direct is disabled, we want to disable the chat room creation option
menu.getItem(0).setEnabled(ChatSearchScreenFrag.mIsWifiDirectEnabled);
//if this menu is opened when the chat search is active:
if (mDisplayedFragIndex==0)
{
//hide the 'delete history option:
menu.findItem(R.id.action_delete_all_history).setVisible(false);
}
else //history frag is active:
{
//show the 'delete history option:
menu.findItem(R.id.action_delete_all_history).setVisible(true);
menu.findItem( R.id.clear_ignore_list).setVisible(false);
}
return true;
}
#SuppressLint("HandlerLeak")
Handler FirstTimeMenuUpdater = new Handler()
{
#Override
public void handleMessage(Message msg)
{
MainScreenActivity.this.invalidateOptionsMenu();
}
};
/**
* Called only once when the app starts
*/
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_screen_menu, menu);
FirstTimeMenuUpdater.sendEmptyMessageDelayed(0, 500);
return true;
}//end of onCreateOptionsMenu()
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_settings://setting was clicked
{
startActivity(new Intent(this, QuickPrefsActivity.class));
break;
}
case R.id.action_create_new_chat_room: //exit app was clicked
{
mDialog =CreatePublicChatCreationDialog();
mDialog.show();
AlertCheckBoxClickListener= new OnClickListener()
{
#Override
public void onClick(View v)
{
AlertDialog dialog = MainScreenActivity.this.mDialog;
EditText ed = (EditText) dialog.findViewById(R.id.choosePassword);
boolean b= !ed.isEnabled();
ed.setEnabled(b);
}
};
CheckBox ch = (CheckBox) mDialog.findViewById(R.id.checkBoxSetPassword);
ch.setOnClickListener(AlertCheckBoxClickListener);
break;
}
case R.id.clear_ignore_list: //exit app was clicked
{
if (mSearchFrag!=null)
mSearchFrag.ClearIgnoredUsersList();
break;
}
case R.id.feedback: //exit app was clicked
{
startActivity(new Intent(this, FeedbackActivity.class));
break;
}
case R.id.about: //exit app was clicked
{
startActivity(new Intent(this, AboutusActivity.class));
break;
}
case R.id.action_exit: //exit app was clicked
{
kill();
break;
}
case R.id.action_delete_all_history: //delete all history was clicked
{
mHistoryFrag.DeleteAllHistory();
break;
}
}//switch
return true;
}//end of onOptionsItemSelected()
#Override
public void onTabSelected(ActionBar.Tab tab,FragmentTransaction fragmentTransaction)
{
// When the given tab is selected, switch to the corresponding page in
// the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}//end of onTabSelected()
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction)
{
}
/**
* A FragmentPagerAdapter that returns a fragment corresponding to
* one of the sections/tabs/pages.
*/
public class SectionsPagerAdapter extends FragmentPagerAdapter
{
public SectionsPagerAdapter(FragmentManager fm)
{
super(fm);
}
#Override
public Fragment getItem(int position)
{
// getItem is called to instantiate the fragment for the given page.
Fragment fragment=null; //will hold the relevant fragment to be returned
switch (position)
{
case 0:
fragment = new ChatSearchScreenFrag(); //create a new chat search fragment
break;
case 1:
fragment = new ChatHistoryScreenFrag(); //create a new history display fragment
break;
}
return fragment;
}//end of getItem()
#Override
public int getCount()
{
return 2; // Show 2 total pages.
}
//Returns the title for each tab
#Override
public CharSequence getPageTitle(int position)
{
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.main_screen_tab1_title).toUpperCase(l);
case 1:
return getString(R.string.main_screen_tab2_title).toUpperCase(l);
}
return null;
}
}//end of class
/**
* Called when the refresh button in the chat search fragment is clicked
*/
public void onRefreshButtonClicked (View v)
{
mSearchFrag.onRefreshButtonClicked(v); //call the frag's method
}//end of onRefreshButtonClicked()
/**
* Reads the saved preferences
*/
protected void getPrefs()
{
SharedPreferences prefs = getPreferences(0);
ChatRoomAccumulatingSerialNumber = prefs.getLong(Constants.SHARED_PREF_CHAT_ROOM_SERIAL_NUM, 0);
UserName = prefs.getString(Constants.SHARED_PREF_USER_NAME, null);
UniqueID = prefs.getString(Constants.SHARED_PREF_UNIQUE_ID, null);
isToNotifyOnNewMsg = prefs.getBoolean(Constants.SHARED_PREF_ENABLE_NOTIFICATION, false);
RefreshPeriodInMs = prefs.getInt(Constants.SHARED_PREF_REFRESH_PERIOD, 10000);
mIsRunForTheFirstTime = prefs.getBoolean(Constants.SHARED_PREF_IS_FIRST_RUN, true);
}//end of getPrefs(){
/**
* Saved the shared preferences
*/
protected void savePrefs()
{
SharedPreferences.Editor editor = getPreferences(0).edit();
editor.putLong(Constants.SHARED_PREF_CHAT_ROOM_SERIAL_NUM, ChatRoomAccumulatingSerialNumber); //save to current SN
editor.putString(Constants.SHARED_PREF_USER_NAME, UserName);
editor.putString(Constants.SHARED_PREF_UNIQUE_ID, UniqueID);
editor.putBoolean(Constants.SHARED_PREF_ENABLE_NOTIFICATION, isToNotifyOnNewMsg);
editor.putInt(Constants.SHARED_PREF_REFRESH_PERIOD, RefreshPeriodInMs);
editor.putBoolean(Constants.SHARED_PREF_IS_FIRST_RUN, false);
editor.commit();
}//end of savePrefs()
/**
* Calls the kill() method of {#link ChatSearchScreenFrag}, resets all static variables,
* calls the system's garbage collector and finishes.
*/
public void kill(){
savePrefs();
mSearchFrag.kill(); //close the entire app (service and welcome socket)
//we'de like to reset all static variables in our app:
ChatActivity.mIsActive=false;
ChatActivity.mMsgsWaitingForSendResult=null;
ChatSearchScreenFrag.mService=null;
ChatSearchScreenFrag.mIsWifiDirectEnabled=false;
ChatSearchScreenFrag.mIsConnectedToGroup=false;
ChatSearchScreenFrag.mManager = null;
ChatSearchScreenFrag.mChannel = null;
LocalService.mNotificationManager=null;
//Indicates to the VM that it would be a good time to run the garbage collector
System.gc();
finish(); //close this activity
}//kill()
private AlertDialog CreatePublicChatCreationDialog()
{
// This example shows how to add a custom layout to an AlertDialog
LayoutInflater factory = LayoutInflater.from(this);
final View textEntryView = factory.inflate(R.layout.public_chat_creation_dialog, null);
return new AlertDialog.Builder(this)
.setTitle("Create A New Room")
.setView(textEntryView)
.setIcon(R.drawable.settings_icon)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
boolean isPassword=false;
String password="";
String roomName=null;
EditText ed = (EditText) mDialog.findViewById(R.id.choosePassword);
//gets password if exists
isPassword= ed.isEnabled();
if(isPassword){password=ed.getText().toString();}
//gets rooms name
ed = (EditText) mDialog.findViewById(R.id.chooseRoomsName);
roomName=ed.getText().toString();
//if the room's name is invalid:
if(roomName==null || roomName.length()<1){
// pop alert dialog and reload this dialog
new AlertDialog.Builder(MainScreenActivity.this)
.setTitle("Missing name error")
.setMessage("A room must have a name")
//yes button setter
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {mDialog.show();}})//setPositive
.setOnCancelListener(new OnCancelListener(){
public void onCancel(DialogInterface dialog){mDialog.show();}})
.show();
//end of alert dialog
}//if
else{//there is a room name
//the room is ready to be created
//call the service and create a new public chat room
if (password.equalsIgnoreCase(""))
password=null;
ChatSearchScreenFrag.mService.CreateNewHostedPublicChatRoom(roomName,password);
}//else
}//onClick dialog listener
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {}
}).create();
}//end of ShowPublicChatCreationDialog()
}//end of class
Though it is commercial application but i have to share this because this issue must be solve by any how.
Here is the log cat what i got while stucking at screen:-
logcat
For a school project I am creating a simple app. However, I run into one problem to finalize the app.
I've been trying to make two buttons on my main layout. The buttons are supposed to open a second layout, one called barcode_scanner.xml and another called vragen.xml
However, only the first button opens the scanner. The second button does not do anything.
This is my current code from MainActivity.java
package com.kvprasad.zbarbarcodescanner;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button scannerButton;
#Override
//Barcodescanner knop
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.scannerButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), BarcodeScanner.class);
startActivityForResult(myIntent, 0);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public class bovenbouw extends MainActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.bovenbutton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Vragen.class);
startActivityForResult(myIntent, 0);}});}}}
I don't see any problems in the code. What am I possibly doing wrong?
Thank you.
Do not make multiple onCreate methods for the same activity. Handle all your button clicks in the same onCreate method. What you can do is this:
package com.kvprasad.zbarbarcodescanner;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private Button scannerButton;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, 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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
//Barcodescanner knop
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next1 = (Button) findViewById(R.id.scannerButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), BarcodeScanner.class);
startActivityForResult(myIntent, 0);
}
});
Button next2 = (Button) findViewById(R.id.bovenbutton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Vragen.class);
startActivityForResult(myIntent, 0);}
});
}
}
You don't need 2 onCreate() methods for two buttons. As both of them are in the same layout, you can set onClickListener on both of them in one method only.
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.scannerButton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(this, BarcodeScanner.class);
startActivityForResult(myIntent, 0);
}
});
Button next1 = (Button) findViewById(R.id.bovenbutton);
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(this, Vragen.class);
startActivityForResult(myIntent, 1);
//Make sure the second parameter is not 0, so that you can differentiate between them in onActivityReult method.
}
});
}
}
You don't have to create another class for vragen.class after bovenbutton is pressed.
just create another button for bovenbutton in the main class oncreate method besides the scanner_button
#Override
//Barcodescanner knop
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button next = (Button) findViewById(R.id.scannerButton);
Button vragen = (Button) findViewById(R.id.bovenbutton);//button for vragen
next.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), BarcodeScanner.class);
startActivityForResult(myIntent, 0);
}
});
//here goes the onclicklistener for vragen button
vragen.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent myIntent = new Intent(view.getContext(), Vragen.class);
startActivityForResult(myIntent, 0);
}
});
}
You're not supposed to register two Activities in single .java file. You must create separate Activity.
package com.example.photosapp
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
so I'm fairly new to Android. Lemme just explain first:
I'm trying to make a small portable music app, just for my phone and to test my skills/review what I've learned. I have the mainactivity setup to pick a song with 1 of 4 buttons, and it'll start another activity with buttons to pause, resume, and go back to the song selection screen (MainActivity). I'm trying to get the back button to both release the player and finish the activity, and I've tried many different things but nothing seems to work; the app closes due to some exception (a common one being NullPointerException).
So here's MainActivity:
package me.lemmy.portablemusic.app;
import android.media.MediaPlayer;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
Button wreckingBall, happy, lig, ligMulti;
Intent songPickedActivity = new Intent("me.lemmy.portablemusic.app.SONGPICKED");
public static MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set buttons
wreckingBall = (Button) findViewById(R.id.song_wreck);
happy = (Button) findViewById(R.id.song_happy);
lig = (Button) findViewById(R.id.song_lig);
ligMulti = (Button) findViewById(R.id.song_lig_multi);
//listeners
wreckingBall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(songPickedActivity);
player = MediaPlayer.create(MainActivity.this, R.raw.wrecking_ball);
player.start();
}
});
happy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(songPickedActivity);
player = MediaPlayer.create(MainActivity.this, R.raw.happy);
player.start();
}
});
lig.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(songPickedActivity);
player = MediaPlayer.create(MainActivity.this, R.raw.let_it_go);
player.start();
}
});
ligMulti.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(songPickedActivity);
player = MediaPlayer.create(MainActivity.this, R.raw.let_it_go_multi);
player.start();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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);
}
public static MediaPlayer getPlayer(){
return player;
}
}
and here's my SongPicked activity:
package me.lemmy.portablemusic.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.media.MediaPlayer;
import android.widget.TextView;
/**
* Created by Lemuel on 6/20/14.
*/
public class SongPicked extends Activity {
TextView text;
Button pause, resume, back;
MediaPlayer player;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_songpicked);
text = (TextView) findViewById(R.id.tvPlaying);
pause = (Button) findViewById(R.id.buttonPause);
resume = (Button) findViewById(R.id.buttonResume);
back = (Button) findViewById(R.id.buttonBack);
player = MainActivity.getPlayer();
pause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
player.pause();
}
});
resume.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
player.start();
}
});
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view){
player.release();
}
});
}
#Override
protected void onPause(){
super.onPause();
finish();
}
}
Any help is appreciated, thanks!
P.S. I know I can't use copyrighted music in my apps, this is just a test.
I suggest to first make sure the activity is in the AndroidManifest file. Second is to change your intent from this:
Intent songPickedActivity = new Intent("me.lemmy.portablemusic.app.SONGPICKED");
into:
Intent songPickedActivity = new Intent(this, SongPicked.class);
Do it as well on the songPickedActivity when going back to MainActivity. You can use putExtra to send data to next intent. For more information click this link.
I am creating a Bluetooth app that requires a log in and/or sign up. I use a button click to switch to new layout xml file, but I need to not use buttons and figure out how to use fragments! When I have a button on the second page that gets clicked it crashes the app. Help :(
MainActivity.java
package com.example.chirp;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.bluetooth.BluetoothAdapter;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter() ;
bluetooth.setName("Chirp Bluetooth");
String status; {
if (bluetooth != null)
{
if (bluetooth.isEnabled())
{
String mydeviceaddress = bluetooth.getAddress();
String mydevicename = bluetooth.getName();
// String state = bluetooth.getState();
// status = mydevicename + ":" + mydeviceaddress + ":" + state;
}
else
{
status = "Bluetooth is not Enabled.";
}
}
// Toast.makeText(this, status, Toast.LENGTH_LONG).show();
}
// Configuration config = getResources().getConfiguration();
//
// FragmentManager fragmentManager = getFragmentManager();
// FragmentTransaction fragmentTransaction =
// fragmentManager.beginTransaction();
//
Button quickfindbutton = (Button) findViewById(R.id.qfbutton);
quickfindbutton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
}
});
Button loginbutton = (Button) findViewById(R.id.button1);
loginbutton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
setContentView(R.layout.loginscreen);
};
});
Button signupbutton = (Button) findViewById(R.id.button2);
signupbutton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
setContentView(R.layout.signupscreen);
}
});
// Button login = (Button) findViewById(R.id.login);
// login.setOnClickListener(new OnClickListener(){
// public void onClick(View v){
// setContentView(R.layout.devicepage);
// }
// });
}
public void showToast(String message) {
Toast toast = Toast.makeText(getApplicationContext(), message,
Toast.LENGTH_SHORT);
toast.show();
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
setContentView(R.layout.activity_main);
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// public void newMessage(View v){
// Intent intent = new Intent(this,loginscreen.class);
// startActivity(intent);
// }
}
setContentView() should be in onCreate() method within first few lines. Otherwise it will not work. If you need to change the layout after click on the button what you can do is, use SharedPreferences.
Check the saved item in shared Preferences before and then use setContentView() method in onCreate(). Inside the button onClick () method save the wanted layout in SharedPreferences. Then write the code to restart the application.
Check out this link:
http://developer.android.com/guide/components/fragments.html
And also check if your second activity is registered in the manifest.xml.