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.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
Working on an android project just for the fun of it. I am getting back the error after a user tries to log in. I did a try-catch around the line where the error is and the RecyclerView object itself is null. So now that I know that, I am trying to figure out why it isn't getting set when I do findViewById(). I will paste the relevant code down below.
java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.recyclerview.widget.RecyclerView.setAdapter(androidx.recyclerview.widget.RecyclerView$Adapter)' on a null object reference
MainActivity.java
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.SearchView;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.navigation.NavController;
import androidx.navigation.Navigation;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
MyProductAdapter myProductAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
BottomNavigationView navView = findViewById(R.id.nav_view);
// Passing each menu ID as a set of Ids because each
// menu should be considered as top level destinations.
AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder(R.id.navigation_home, R.id.navigation_dashboard, R.id.navigation_notifications).build();
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
NavigationUI.setupWithNavController(navView, navController);
RecyclerView recyclerView;
recyclerView = findViewById(R.id.listId);
System.out.println("This is recyclverView" + recyclerView);
try {
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setHasFixedSize(true);
} catch (NullPointerException e) {
System.out.println("null here" + e.getCause());
}
ArrayList<MyProduct> myProductData = new ArrayList<>();
myProductData.add(new MyProduct("Panadol", "Pill for headAche", "Price : $2.99", R.drawable.logo2));
myProductData.add(new MyProduct("Nyquill", "Pill for headAche", "Price : $2.99", R.drawable.logo2));
myProductData.add(new MyProduct("ZAck", "Pill for headAche", "Price : $2.99", R.drawable.logo2));
myProductData.add(new MyProduct("Codeine", "Pill for headAche", "Price : $2.99", R.drawable.logo2));
myProductAdapter = new MyProductAdapter(myProductData, MainActivity.this);
recyclerView.setAdapter(myProductAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_bar, menu);
MenuItem menuItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String s) {
myProductAdapter.getFilter().filter(s);
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
}
fragment_dashboard.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ui.dashboard.DashboardFragment">
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/listId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="2dp"
/>
</LinearLayout>
DashBoardFragment.java
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import com.example.medistak.R;
public class DashboardFragment extends Fragment {
private DashboardViewModel dashboardViewModel;
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
dashboardViewModel =
new ViewModelProvider(this).get(DashboardViewModel.class);
View root = inflater.inflate(R.layout.fragment_dashboard, container, false);
dashboardViewModel.getText().observe(getViewLifecycleOwner(), new Observer<String>() {
#Override
public void onChanged(#Nullable String s) {
}
});
return root;
}
}
Edit (after OP adds the DashboardFragment class)
Move your MyProductAdapter and recyclerView code from MainActivity to DashboardFragment onCreateView() method as follows:
RecyclerView recyclerView = findViewById(R.id.listId);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(myProductAdapter);
Your RecyclerView listId resides in your DashboardFragment whereas you are initializing and setting it up in your MainActivity class. The reason why Null Object Reference error is showing up is because of the order in which Activities and their underlying Fragments are added to the Backstack.
First your MainActivity is setup. Then follows the Fragments lying in MainActivity, in your case its the DashboardFragment. So if you will setup a recyclerView of the DashboardFragment which is not even in existence from MainActivity's point of view and yet to be created , of course it will lead to a NPE.
The solution to your problem will be to pluck out all the recyclerView setup code from MainActivity class and transfer it over to DashboardFragment.
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.
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))
I keep getting errors in code below, specifically the two pieces surrounded by asterisks (R.id.action_settings and fragment_display_message,)
package com.example.completelypointlessapp;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() { }
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.**fragment_display_message,**
container, false);
return rootView;
}
}
}
The errors state:"fragment_display_message cannot be resolved or is not a field" and "action_settings cannot be resolved or is not a field"
Can anyone help resolve this?
(Apology for certain incorrect formatting, I am new to this site)
View rootView = inflater.inflate(R.layout.fragment_display_message,
container, false);
Do you have fragment_display_message.xml layout file ?
if (id == R.id.action_settings)
Do you have the custom menu file for ActionBar ?
Example -
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/action_settings"
android:title="Settings"
android:showAsAction="never"
>
</item>
</menu>
If answer to both is NO, then error is obvious.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I just starting learning to develop an android app and for that i followed google's basic tutorial.
In the tutorial there is simply a textbox and a button. On pressing the button it takes the text from the textbox and displays it in another activity. But somehow the button isn't working for me.
Here is the code for the fragment_main.xml, MainActivity.java and DisplayMessageActivity.java. I just want to know if i am doing something wrong or if i am missing something.
fragmant_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
onClick="sendMessage" />
</LinearLayout>
MainActivity.java:
package com.example.first;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
DisplayMessageActivity.java
package com.example.first;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.display_message, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_display_message,
container, false);
return rootView;
}
}
}
EDIT **
In your fragment_main.xml file the the last line of your Button tag should be : android:onClick="sendMessage" instead of onClick="sendMessage"