NullPointerException in android while using actionLayout in menu.xml - java

I want to use custom SearchView in menu of my App but I'm encountering a NullPointerException in android while using actionLayout in menu.xml
I have custom layout for menu :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="#+id/search_btn"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#android:drawable/ic_menu_search"/>
<EditText
android:id="#+id/search_et"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/search_btn"
android:layout_toLeftOf="#+id/search_btn"
android:ems="10"
android:inputType="none" >
<requestFocus />
</EditText>
and my menu.xml is :
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/search_view"
android:icon="#android:drawable/ic_menu_search"
android:actionLayout="#layout/search_menu"
android:showAsAction="collapseActionView|ifRoom"
android:title="#string/search_title"/>
</menu>
Now I want to add OnClickListener on _search_btn_ So I did that likewise :
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
searchButton = (Button) menu.findItem(R.id.search_btn);
searchButton.setOnClickListener(new OnClickListener() { // SEE HERE I'M GETTING NullPointerException
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, ((EditText) findViewById(R.id.search_et)).getText().toString(), Toast.LENGTH_LONG).show();
}
});
return true;
}
but I'm getting my NullPointerException on above mentioned line. How can I add ClickListener to that button???

You're using the wrong id. Use the id for your menu item. You can use getActionView on the MenuItem to get the layout.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.search_view);
Button searchButton = searchItem.getActionView().findViewById(R.id.search_btn);
searchButton.setOnClickListener(new OnClickListener() { // SEE HERE I'M GETTING NullPointerException
#Override
public void onClick(View v) {
Toast.makeText(MainActivity.this, ((EditText) findViewById(R.id.search_et)).getText().toString(), Toast.LENGTH_LONG).show();
}
});
return true;
}

please try on onOptionsItemSelected method.
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.search_view:
//write your code here
return true;
default:
return super.onOptionsItemSelected(item);
}
}

Well your not getting a reference to your button. i.e in searchButton = (Button) menu.findItem(R.id.search_btn); you searchButton is null.
Your using a wrong id.

Related

Not able to set text in edit text from cloud firestore?

After opening notes I see textview of my note's title and content. I want to edit notes. But there is a problem with the edit note activity. It shows only the text of title in edittext. But below this content text not shown. I tried many ways like I tried to check what's a problem I put data of title. But it is also not showing the title. Means upper title edit text can show title data and content data but second edit text doesn't show title data and content data.
This is notes_open.class
public class notes_open extends AppCompatActivity {
Intent data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notes_open);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
data= getIntent();
TextView MyTitle = findViewById(R.id.notesopentitle);
TextView MyContent= findViewById(R.id.notesopencontent);
MyContent.setMovementMethod(new ScrollingMovementMethod());
MyTitle.setText(data.getStringExtra("ourtitle"));
MyContent.setText(data.getStringExtra("ourcontent"));
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater= getMenuInflater();
getMenuInflater().inflate(R.menu.notesopen, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch(item.getItemId()){
case android.R.id.home:
onBackPressed();
case R.id.edit_note:
Intent i = new Intent(getApplication(),edit_note.class);
i.putExtra("ourtitle",data.getStringExtra("ourtitle"));
i.putExtra("ourcontent",data.getStringExtra("ourcontent"));
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
}
Below is edit_note.class
public class edit_note extends AppCompatActivity {
Intent data;
EditText edit_title, edit_note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_note);
data = getIntent();
edit_title = findViewById(R.id.edit_ttile);
edit_note = findViewById(R.id.edit_note);
String edititle = data.getStringExtra("ourtitle");
String editcontent = data.getStringExtra("ourcontent");
try {
edit_title.setText(edititle);
edit_note.setText(editcontent);
}catch (NullPointerException ignore){}
}
}
Edit note xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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=".edit_note">
<com.google.android.material.appbar.AppBarLayout
android:id="#+id/appBarLayout2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay"
tools:ignore="MissingConstraints">
<androidx.appcompat.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</com.google.android.material.appbar.AppBarLayout>
<EditText
android:id="#+id/edit_ttile"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="Title"
android:layout_below="#id/appBarLayout2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="56dp" />
<EditText
android:id="#+id/edit_content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
android:hint="Content"
android:layout_below="#id/edit_ttile"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="56dp" />
</RelativeLayout>
Your edittext assigning is wrong :
edit_note = findViewById(R.id.edit_note);
Instead it needs :
edit_note = findViewById(R.id.edit_content);

I Wanted to access my admin panel page through the menu item of my android app [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
In my android app I am having a menu item logout.I wanted to add another menu item My Panel which redirects into admin panel page gmumbai.co.in/admin.How to accomplish this.Please help me with a sample code.Thanks in advance.
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_overview, 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();
Intent intent;
switch (item.getItemId()) {
case R.id.action_logout:
app = ((MyApplication) getApplicationContext());
app.logOut();
intent = new Intent(overview.this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
overview.this.startActivity(intent);
overview.this.finish();
return true;
case R.id.action_MyPanel:
Uri uri=Uri.parse("http://gmumbai.co.in/admin");
overview.this.startActivity(new Intent (Intent.ACTION_VIEW,uri));
overview.this.finish();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
<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="com.gmumbai.gvendor.overview">
<item android:id="#+id/action_logout" android:title="#string/action_logout"
android:orderInCategory="100" app:showAsAction="never" />
<item android:id="#+id/action_MyPanel" android:title="#string/action_MyPanel"
android:orderInCategory="100" app:showAsAction="never" />
</menu>
For adding a menu entry, try this:
res/menu/main_menu.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/action_logout"
android:icon="#drawable/ic_logout"
android:title="Logout"
app:showAsAction="always|collapseActionView" />
<item
android:id="#+id/action_redirAdmin"
android:icon="#drawable/admin_console"
android:title="Admin Console"
app:showAsAction="always|collapseActionView">
</item>
</menu>
MainActivity.java
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.action_logout:
//Logout
return true;
case R.id.action_redirAdmin:
//Goto AdminConsole
//startActivity(new Intent(MainActivity.this, AdminConsole.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
If you are trying to display a webpage in your view, make sure you have a WebView in AdminConsole.java
For adding WebView, try this:
admin_console_activity.xml
<RelativeLayout 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"
tools:context=".MainActivity" >
<WebView
android:id="#+id/adminConsoleWebView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="42dp" />
</RelativeLayout>
AdminConsole.java
private WebView mWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.admin_console_activity);
mWebView = (WebView) findViewById(R.id.adminConsoleWebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://gmumbai.co.in/admin");
}

How to Set Icon to display on the far right in Java

getSupportActionBar().setLogo(R.drawable.addicon);
The code above seems to place my Icon in the Centre . I would like to place to the far right and make it clickable as well . At the moment it the image for the icon is in the project files as a drawable I have not included it in any xml files.
You can set android:layoutDirection="rtl" in your toolbar xml for place it to right and
set below code for clickable :
getSupportActionbar().setDisplayHomeAsUpEnabled(true);
and :
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
//Do stuff
return true;
default:
return super.onOptionsItemSelected(item);
}
}
There are 2 approaches for doing that.
Option Menus
Creating custom toolbar.
With Option Menus
create main.xml under res/menu.
<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="com.ioa.MainActivity" >
<item
android:id="#+id/action_addition"
android:icon="#drawable/addicon"
android:orderInCategory="100"
android:title="Addition"
app:showAsAction="always"/>
</menu>
and inside your activity create menu like,
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
you can perform Action on particular menu item.
#Override
public boolean onOptionsItemSelected(MenuItem Item) {
if (Item.getItemId() == R.id.action_addition) {
// perform action
}
return super.onOptionsItemSelected(paramMenuItem);
}
With custom toolbar
Create your ToolBar like this,
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/ColorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar"
app:popupTheme="#style/ThemeOverlay.AppCompat.Light" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<ImageView
android:id="#+id/add"
android:layout_width="46dp"
android:layout_height="46dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="4dp"
android:clickable="true"
android:src="#drawable/ic_launcher" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
and now you can perform click event of particular ImageView.
ImageView add = (ImageView) findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// do work.
}
});
happy Coding.
You Need 3 Things:
A Custom Toolbar Layout
Include the toolbar in your activity
Set the Logo to the toolbar
Create new Resource Layout:
include_toolbar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:background="?attr/colorPrimaryDark"
android:id="#+id/include_toolbar"
app:theme="#style/ThemeOverlay.AppCompat.Dark.ActionBar" />
Change Your Activity File: MainActivity.java
public class BaseActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar)findViewById(R.id.include_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.mipmap_ic_launcher);
}
}
And here's the styles.xml:
<!-- language: xml-->
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
</resources>

Handling click event of switch widget on action bar

This is how I added a switch widget to the action bar. I'm already playing with it. But I'm not knowing how to respond to the click events.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.map, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
System.out.println("actionbar clicked");
// Handle item selection
if (item.getItemId()==R.id.myswitch) {
Switch actionView = (Switch)item.getActionView();
actionView.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView, final boolean isChecked) {
status = isChecked;
System.out.println(status);
}
});
return true;
}
return super.onOptionsItemSelected(item);
}
This is my switch layout and map resource file
switch_status.xml
<?xml version="1.0" encoding="utf-8"?>
<Switch
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:showText="true"
android:textOff="Free"
android:textOn="Booked" />
map.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" >
<item
android:id="#+id/myswitch"
android:showAsAction="always"
android:title=""
android:actionLayout="#layout/switch_status" />
</menu>
While clicking the switch, It is changing its state, but I cannot see even one msg on the console like "actionbar clicked" & "true" / "false". And there is no error either.
I'm not sure weather this is the correct way of handling clicks on actionbar. If any one can help me with this code, it will be really nice.
Thankyou
Best way for do this using Toolbar .
In Toolbar you can add any view and control this.
You don't need to set a OnCheckedChangeListener, onOptionsItemSelected is a "onClickListener"
use switch for this:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
System.out.println("actionbar clicked");
// Handle item selection
switch (item.getItemId()) {
case R.id.myswitch:
System.out.println(((Switch)item.getActionView()).isChecked());
break;
}
return super.onOptionsItemSelected(item);
}
I had the same issue and achieved by following below technique
Added onClick method for switch like below
<Switch
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/switch1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:showText="true"
android:textOff="Free"
android:textOn="Booked"
android:onClick="onSwitch"
/>
Implement onSwitch method in Activity as below:
public void onSwitch(View view) {
Switch androidSwitch = findViewById(R.id.switch1);
if(androidSwitch.isChecked()){
Log.i("Test","enabled");
}else{
Log.i("Test","disabled");
}
}

Android onCreateOptionMenu not being called

I am implementing an Android Activity from which other Activities will be derived from. So basically I have this setup of an InventoryActivity and its parent class, ListActivity:
public class MyListActivity extends Activity {
protected Context mContext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this.getBaseContext();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options, menu);
Log.d("Creating options menu", "True");
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
Log.d("Preparing options menu", "True");
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
return(true);
case R.id.revert:
return(true);
}
return(super.onOptionsItemSelected(item));
}
}
public class InventoryActivity extends MyListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.inventory);
}
}
And I also have this in options.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/card_list_save"
android:icon="#drawable/ic_menu_save"
android:title="Save"/>
<item android:id="#+id/card_list_revert"
android:icon="#drawable/ic_menu_revert"
android:title="Revert" />
</menu>
If necessary, this is my layout for inventory.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/callSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Search"/>
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:id="#+id/inventory"/>
</ScrollView>
</LinearLayout>
However, when I press the menu button, nothing happens. The Log messages in the onCreateOptionsMenu method does not appear. Instead all I can see is the following:
02-04 11:36:58.313: W/KeyCharacterMap(31464): No keyboard for id 0
02-04 11:36:58.313: W/KeyCharacterMap(31464): Using default keymap: /system/usr/keychars/qwerty.kcm.bin
But what baffles me the most is that this code works in other Activities, such as my launcher Activity. But by the concept of object oriented programming, the InventoryActivity should call the overriding methods in the MyListActivity. I am completely stuck and I need help.
ListActivity is already a class in the Android SDK. My guess is that you're importing android.app.ListActivity, and not your package.
Hmm...don't know why but removing the onCreate method in MyListActivity fixed the problem. So the class now looks like this:
public class MyListActivity extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options, menu);
Log.d("Creating options menu", "True");
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
Log.d("Preparing options menu", "True");
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save:
return(true);
case R.id.revert:
return(true);
}
return(super.onOptionsItemSelected(item));
}
}

Categories