Using Android menu code in common Utils File - java

I am trying to implement my menu in a Utils.java file. Well, so far so good, the menu is appearing as it should although when I click on any menu item, the application stops working. I don't seem to find where the issue is and I would be grateful for your advice. The code for my menu, utils and activity files is as below:
Utils.java
package com.package.name;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
public class Utils extends Activity{
private Context _context;
public Utils(Context context){
this._context = context;
}
public void menuSwitch(int item) {
switch (item) {
case R.id.menu_one:
startActivity(new Intent(getApplicationContext(),
MainActivity.class));
case R.id.menu_two:
startActivity(new Intent(getApplicationContext(),
MessageActivity.class));
case R.id.menu_three:
startActivity(new Intent(getApplicationContext(),
LocateActivity.class));
case R.id.menu_four:
startActivity(new Intent(this,
AboutActivity.class));
}
}
}
menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
<item android:id="#+id/menu_one" android:title="#string/menu_one" />
<item android:id="#+id/menu_two" android:title="#string/menu_two" />
<item android:id="#+id/menu_three" android:title="#string/menu_three" />
<item android:id="#+id/menu_four" android:title="#string/menu_four" />
</menu>
menuActivity.java
package com.package.name;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
public class DatabaseActivity extends ListActivity {
Utils util;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_database);
util = new Utils(this);
}
#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) {
util.menuSwitch(item.getItemId());
return true;
}
}

You should not extend your Utils class. Replace your codes by this one.
public class Utils{
private Context _context;
public Utils(Context context){
this._context = context;
}
public void menuSwitch(int item) {
switch (item) {
case R.id.menu_one:
_context.startActivity(new Intent(_context.getApplicationContext(),
MainActivity.class));
case R.id.menu_two:
_context.startActivity(new Intent(_context.getApplicationContext(),
MessageActivity.class));
case R.id.menu_three:
_context.startActivity(new Intent(_context.getApplicationContext(),
LocateActivity.class));
case R.id.menu_four:
_context.startActivity(new Intent(_context.getApplicationContext(),
AboutActivity.class));
}
}
}

you are using startactivity of Util class , but it should be of the class in which menu is there, thus you should use
_context.startactivity(new Intent(_context,wahteverclass.class))

Related

(ActionMenu)W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed

I made Action Bar Menu App. But If I click menuitem, Toast Message is not shown.
I run the emulator and my phone. But It doesn't work.
when I click menuitem, logcat is show error message:
W/InputEventReceiver: Attempted to finish an input event but the input event receiver has already been disposed.
This is MY CODE:
MainActivity.java
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mymenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.info:
Toast.makeText(this,"짠",Toast.LENGTH_SHORT);
return true;
case R.id.support:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
res/menu/mymenu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="#+id/help"
android:title="help"/>
<item
android:id="#+id/support"
android:title="support"/>
</menu>
you Toast.makeText(this,"짠",Toast.LENGTH_SHORT); should Toast.makeText(this,"짠",Toast.LENGTH_SHORT).show(); invoke show() method.Hope help you.

share action provider is not showing

Here is my menu resource file
<item
android:id="#+id/action_share"
android:title="#string/action_share"
android:orderInCategory="2"
app:showAsAction="ifRoom"
android:actionProviderClass="android.widget.ShareActionProvider">
</item>
</menu>
And here is my java code
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main,menu);
MenuItem menuItem = menu.findItem(R.id.action_share);
shareActionProvider =(ShareActionProvider)menuItem.getActionProvider();
// setIntent("COOL NIKS");
return super.onCreateOptionsMenu(menu);
}
This is not showing share action provider. How do I fix it?
Here is how full working example should look like.This uses AppCompat library.
You need to add http://schemas.android.com/apk/res-auto schema to your menu items XML.
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="#+id/action_share"
app:actionProviderClass="android.support.v7.widget.ShareActionProvider"
app:showAsAction="always"
android:title="Share" />
</menu>
Now you will have to update your MainActivity to use ShareActionProvider
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.MenuItemCompat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.ShareActionProvider;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends ActionBarActivity {
private ShareActionProvider mShareActionProvider;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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);
// Get the menu item.
MenuItem menuItem = menu.findItem(R.id.action_share);
// Get the provider and hold onto it to set/change the share intent.
mShareActionProvider = (ShareActionProvider) MenuItemCompat.getActionProvider(menuItem);
// Set share Intent.
// Note: You can set the share Intent afterwords if you don't want to set it right now.
mShareActionProvider.setShareIntent(createShareIntent());
return true;
}
// Create and return the Share Intent
private Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, "http://google.com");
return shareIntent;
}
// Sets new share Intent.
// Use this method to change or set Share Intent in your Activity Lifecycle.
private void changeShareIntent(Intent shareIntent) {
mShareActionProvider.setShareIntent(shareIntent);
}
}

My ActionBar icon isn't clickable

I'm having some issues with this icon, the thing is that I can do an onLongPress then it shows a toast with the text of this item.
My menu "new_offer_menu.xml"
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/newOffer"
android:icon="#drawable/ic_action_new"
android:title="#string/nueva_lista"
android:alphabeticShortcut="r"
android:orderInCategory="200"
android:showAsAction="ifRoom" />
</menu>
This icon isn't in all of my fragments, but when I go to the correct fragment (where it has to be shown), when I click it doesn't do nothing. In my ListaProductosFragment.java I have :
package info.androidhive.slidingmenu;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ListFragment;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class ListaProductosFragment extends ListFragment {
private List<ListViewItem> mItems; // ListView items list
private Menu optionsMenu;
public ListaProductosFragment(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// initialize the items list
mItems = new ArrayList<ListViewItem>();
Resources resources = getResources();
mItems.add(new ListViewItem(resources.getDrawable(R.drawable.tomate_oferta), getString(R.string.aim), getString(R.string.aim_precio), getString(R.string.aim_descuento), getString(R.string.aim_data)));
mItems.add(new ListViewItem(resources.getDrawable(R.drawable.levadura_oferta), getString(R.string.youtube), getString(R.string.youtube_precio), getString(R.string.youtube_descuento), getString(R.string.youtube_data)));
mItems.add(new ListViewItem(resources.getDrawable(R.drawable.sopa_oferta), getString(R.string.bebo), getString(R.string.bebo_precio), getString(R.string.bebo_descuento), getString(R.string.aim_data)));
mItems.add(new ListViewItem(resources.getDrawable(R.drawable.zumo_oferta), getString(R.string.pew), getString(R.string.pew_precio), getString(R.string.pew_descuento), getString(R.string.aim_data)));
mItems.add(new ListViewItem(resources.getDrawable(R.drawable.tomate_oferta), getString(R.string.aim), getString(R.string.aim_precio), getString(R.string.aim_descuento), getString(R.string.aim_data)));
// initialize and set the list adapter
setListAdapter(new ListViewDemoAdapterListaProductos(getActivity(), mItems));
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// remove the dividers from the ListView of the ListFragment
getListView().setDivider(null);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
// retrieve theListView item
ListViewItem item = mItems.get(position);
// do something
Toast.makeText(getActivity(), item.title, Toast.LENGTH_SHORT).show();
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.new_offer_menu,menu );
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.newOffer:
Toast.makeText(getActivity(), "this is my Toast message!!! =)",
Toast.LENGTH_LONG).show();
Intent intent = new Intent(getActivity(), TipusNouProducte.class);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
I've created a toast to see if the problem is the Intent but it doesn't appears anyways, it only do something when I do a LongPress on this item.
What I'm doing wrong?
I believe you should change
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/newOffer"
android:icon="#drawable/ic_action_new"
android:title="#string/nueva_lista"
android:alphabeticShortcut="r"
android:orderInCategory="200"
android:showAsAction="ifRoom" />
</menu>
to
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourAppName="http://schemas.android.com/apk/res-auto"> <--
<item android:id="#+id/newOffer"
android:icon="#drawable/ic_action_new"
android:title="#string/nueva_lista"
android:alphabeticShortcut="r"
android:orderInCategory="200"
--> yourAppName:showAsAction="ifRoom" />
</menu>
The LongPress behavior, if I'm not mistaken, is a regular behaviour where the system explains to the user the meaning of the menuItem, getting the string from the title tag
android:title="#string/nueva_lista"
You are not managing it directly, it's Android itself that can manage it, giving you the wrong feeling.

Make a Preference (inside a PreferenceFragment) responds to a click

I'm trying to make a preference react to a user-input but with no luck. I'm using PreferenceFragment and seems that not a single code I found so far can help me.
Here is my preferences.xml:
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen " >
<PreferenceCategory
"
" >
<CheckBoxPreference
"
"
o aplicativo para uso"
aplicativo" />
</PreferenceCategory>
</PreferenceScreen>
And here is my screen code:
package com.gh0st.gerenciador;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.preference.PreferenceFragment;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
public class TelaPreferencias extends PreferenceActivity implements
OnSharedPreferenceChangeListener {
public static final String KEY_PREF_SYNC_CONN = "prefs_ativar";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment()).commit();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tela_preferencias, menu);
return true;
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (key.equals(KEY_PREF_SYNC_CONN)) {
Toast.makeText(this, "Teste", Toast.LENGTH_SHORT).show();
}
}
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 class SettingsFragment extends PreferenceFragment {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
}
}
}
I want that, when I touch on the preference, it shows a toast. The code seems to be fine (no errors), but it doesn't work. I think I didn't get the idea behind the listener. Can somebody help me out?
Thanks!
Before I forget, I'm using API level 19 (Android 4.4). I don't know if this changes something.
Missing the registration of the listener? This is how I do that:
// Register the listener
#Override
protected void onResume()
{
// Register OnSharedPreferenceChangeListener
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).
registerOnSharedPreferenceChangeListener(this);
// Fire the base method
super.onResume();
}
// Unregister the listener
#Override
protected void onPause()
{
// Unregister OnSharedPreferenceChangeListener
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()).
unregisterOnSharedPreferenceChangeListener(this);
// Fire the base method
super.onPause();
}
I suggest you make use of the
Preference.OnPreferenceClickListener
You can find more about it here: http://developer.android.com/reference/android/preference/Preference.OnPreferenceClickListener.html
Example:
Preference p = findPreference("yourkey");
p.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference p) {
// TODO stuff
return true;
}
});
Edit concerning deprecation:
PreferenceActivity.findPreference("key") --> deprecated
PreferenceFragment.findPreference("key") --> not deprecated

Onclick imagebutton-action (menu)

I'm making an app and when it launches it starts Mainactivity.java
Mainactivity.java opens a layout with 9 Imagebuttons.
How can I implement in my code in Mainactivity.java that once one is clicked it opens another activity (like telefoonnummers.java)?
Sorry for my bad English but I'm dutch and a non-native speaker.
I have this code in Mainactivity.java:
package com.example.rome;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.EditText;
import android.widget.Button;
import android.view.View;
import android.widget.Toast;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Very clean as you see, but how can I add the implementation, would you guys please help???
My Imagebuttons are all just called imagebutton1, imagebuttton2 etc. btw.
After
setContentView(R.layout.activity_main);
add for each ImageButton:
findViewById(R.id.imagebutton1).setOnClickListener(this);
Make class implement OnClickListener
class MainActivity extends Activity implements View.OnClickListener {
and add this method:
#Override
public void onClick(View v){
switch(v.getId()){
case R.id.R.id.imagebutton1:
startActivity(new Intent(telefoonnummers.class));
break;
case R.id.R.id.imagebutton2:
startActivity(new Intent(telefoonnummers.class));
break;
//-- more cases --
}
}

Categories