This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I've spent my last 8 hours to solve this simple dumb NPE(about to go mentally blind).Almost read everything about this issue,tried everything possible but same result,so I'll be posting every code related,I hope someone can help !
First of all this is the full error I get through logcat;
2019-03-12 11:16:56.130 23426-23426/com.demotxt.myapp.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.demotxt.myapp.myapplication, PID: 23426
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setSearchableInfo(android.app.SearchableInfo)' on a null object reference
at com.demotxt.myapp.myapplication.activities.Main3Activity.onCreateOptionsMenu(Main3Activity.java:130)
at android.app.Activity.onCreatePanelMenu(Activity.java:3317)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:340)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:93)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:332)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:93)
at android.support.v7.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:454)
at android.support.v7.app.ToolbarActionBar$1.run(ToolbarActionBar.java:55)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
My Main3Activity which I do stuff about searching;
public class Main3Activity extends AppCompatActivity {
private final String JSON_URL = "https://MYURLXX" ;
private JsonArrayRequest request ;
private RequestQueue requestQueue ;
private List<Anime> lstAnime ;
private RecyclerView recyclerView ;
RecyclerViewLiveAdapter adapter;
RecyclerView.LayoutManager layoutManager;
Toolbar toolbar;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
lstAnime = new ArrayList<>() ;
recyclerView = findViewById(R.id.recyclerviewid);
jsonrequest();
}
private void jsonrequest() {
request = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null ;
for (int i = 0 ; i < response.length(); i++ ) {
try {
jsonObject = response.getJSONObject(i) ;
Anime anime = new Anime() ;
anime.setName(jsonObject.getString("name"));
anime.setDescription(jsonObject.getString("description"));
anime.setRating(jsonObject.getString("Rating"));
anime.setCategorie(jsonObject.getString("categorie"));
anime.setStudio(jsonObject.getString("studio"));
anime.setImage_url(jsonObject.getString("img"));
anime.setLink(jsonObject.getString("link"));
anime.setDrm_scheme(jsonObject.getString("drm_scheme"));
anime.setDrm_license_url(jsonObject.getString("drm_license_url"));
anime.setDrm(jsonObject.getString("drm"));
anime.setSubtitle(jsonObject.getString("subtitle"));
anime.setSubtitle1(jsonObject.getString("subtitle1"));
anime.setSubtitle2(jsonObject.getString("subtitle2"));
lstAnime.add(anime);
} catch (JSONException e) {
e.printStackTrace();
}
}
setuprecyclerview(lstAnime);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(Main3Activity.this);
requestQueue.add(request) ;
}
private void setuprecyclerview(List<Anime> lstAnime) {
RecyclerViewLiveAdapter myadapter = new RecyclerViewLiveAdapter(this,lstAnime) ;
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(myadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_item,menu);
MenuItem searchItem =menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
SearchManager searchManager=(SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
newText=newText.toLowerCase();
List<Anime> myList=new ArrayList<>();
for (Anime anime:lstAnime){
String moviename =anime.getName().toLowerCase();
if (moviename.contains(newText))
myList.add(anime);
}
adapter.setSearchOperation(myList);
return false;
}
});
return true;
}
}
Related part in my RecyclerViewAdapter;
public void setSearchOperation(List<Anime> newList) {
mData=new ArrayList<>();
mData.addAll(newList);
notifyDataSetChanged();
}
My searchable.xml in res/xml;
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="#string/search" >
</searchable>
Related part of Main3Activity in AndroidManifest.xml;
<activity android:name=".activities.Main3Activity">
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable"
android:value=".activities.Main3Activity"/>
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
</intent-filter>
</activity>
And this is the toolbar's layout in layouts which is called by RecyclerView's layout like this "include layout ="#layout/toolbar_layout">
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark"></android.support.v7.widget.Toolbar>
And this is the menu_item xml file in menu folder;
<?xml version="1.0" encoding="utf-8"?>
<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_search"
android:icon="#drawable/ic_action_search"
android:title="Search Test"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView"/>
</menu>
I don't use pro-guard so it's not the case and I always used app:showAsAction and app:actionViewClass but as I said all I get that nullpointerexception on same line,thanks in advance!
Replace your initialization of SearchView with this line
SearchView searchView = new SearchView(this.getSupportActionBar().getThemedContext());
Replace:
SearchView searchView = (SearchView) searchItem.getActionView();
With:
MenuItem searchItem =menu.findItem(R.id.action_search);
mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
Also make sure your menu.xml file should look like below:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item android:id="#+id/action_search"
android:title="#string/action_search"
android:icon="#drawable/action_search"
yourapp:showAsAction="always|collapseActionView"
yourapp:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
Related
I want to load an activity and have the search bar visible right away with a magnifying glass available to click/search based on the term entered. Here is what I want to see when I load the activity:
Code:
public class FlickRActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_flick_r);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
MenuItem searchItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
Toast.makeText(getApplicationContext(),newText,Toast.LENGTH_SHORT).show();
return false;
}
});
return true;
}
}
Menu.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/search"
android:title="#string/hint_search"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="collapseActionView|ifRoom"
app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
Just call searchItem.expandActionView();
I am having problems implementing the actionbar (which I think is now replaced by toolbar). What I want is a small drop down menu with the 3 dots where I can have a few options such as settings and credits. I have tried to set it up so that the menu appears on the homelistview.java page. I feel like I have been going in circles trying different solutions and getting a new error each time and it always points back to the same location mentioned below.
setSupportActionBar(toolbar);
I had originally thought it was because I didn't include setContentView(R.layout.activity_main); but it was not happy including 2 content views. Any help would be appreciated.
Here is my code.
styles.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
--------------- 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="cs495capstone.edu.bsu.myapplication.MainActivity">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
<item
android:id="#+id/action_credits"
android:orderInCategory="100"
android:title="#string/action_credits"
app:showAsAction="never" />
<item
android:id="#+id/action_lovely"
android:orderInCategory="100"
android:title="#string/action_lovely"
app:showAsAction="never" />
</menu>
--------------activity_main.xml ----------------
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
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"
android:fitsSystemWindows="true"
tools:context="cs495capstone.edu.bsu.myapplication.HomeActivityListview">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.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" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/activity_add_appointment" />
<include layout="#layout/activity_add_history" />
<include layout="#layout/activity_appointments" />
<include layout="#layout/activity_dog_profile" />
<include layout="#layout/activity_history" />
<include layout="#layout/activity_home" />
<include layout="#layout/activity_home_activity_listview" />
<include layout="#layout/activity_login" />
<include layout="#layout/activity_new_dog" />
<include layout="#layout/activity_registration" />
<include layout="#layout/activity_splash_screen" />
<include layout="#layout/activity_update_dog" />
</android.support.design.widget.CoordinatorLayout>
----------------------- homeactivitylistview.xml-------------------------
public class HomeActivityListview extends AppCompatActivity {
ListView lv;
Context context;
ArrayList dogName;
ArrayList dogID;
public static int [] dogImages={R.drawable.dogpic};
public static String [] dogNames={};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_activity_listview);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
context=this;
lv=(ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, dogImages));
}
#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 void sendProfile(View view) {
Intent intent = new Intent(getApplicationContext(), DogProfileActivity.class);
startActivity(intent);
}
public void NumberOne(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number one");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void NumberTwo(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number two");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void AddNewDog(View view) {
Intent intent = new Intent(getApplicationContext(), NewDogActivity.class);
startActivity(intent);
}
}
------------------ main_activity.java -----------------
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#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);
}
}
--------------homelistview.java------------------
public class HomeActivityListview extends AppCompatActivity {
ListView lv;
Context context;
ArrayList dogName;
ArrayList dogID;
public static int [] dogImages={R.drawable.dogpic};
public static String [] dogNames={};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_activity_listview);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
context=this;
lv=(ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, dogImages));
}
#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 void sendProfile(View view) {
Intent intent = new Intent(getApplicationContext(), DogProfileActivity.class);
startActivity(intent);
}
public void NumberOne(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number one");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void NumberTwo(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number two");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void AddNewDog(View view) {
Intent intent = new Intent(getApplicationContext(), NewDogActivity.class);
startActivity(intent);
}
}
---------------androidmanifest-----------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cs495capstone.edu.bsu.doggydid" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".SplashScreenActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".RegistrationActivity"
android:label="Registration" />
<activity
android:name=".NewDogActivity"
android:label="Dog Information" />
<activity
android:name=".LoginActivity"
android:label="Login" />
<activity
android:name=".HomeActivity"
android:label="#string/title_activity_home" />
<activity
android:name=".DogProfileActivity"
android:label="#string/title_activity_dog_profile" />
<activity
android:name=".HistoryActivity"
android:label="#string/title_activity_records" />
<activity
android:name=".addHistoryActivity"
android:label="#string/title_activity_add_record" />
<activity
android:name=".EventsActivity"
android:label="#string/title_activity_events" />
<activity
android:name=".addEventsActivity"
android:label="#string/title_activity_add_events" />
<activity
android:name=".UpdateDogActivity"
android:label="#string/title_activity_update_dog" />
<activity
android:name=".HomeActivityListview"
android:label="#string/title_activity_home_activity_listview"
android:theme="#style/AppTheme.NoActionBar">
</activity>
</application>
</manifest>
-----------------------Error Readout--------------------
04-14 13:35:36.905 3117-3117/cs495capstone.edu.bsu.doggydid E/AndroidRuntime: FATAL EXCEPTION: main
Process: cs495capstone.edu.bsu.doggydid, PID: 3117
java.lang.RuntimeException: Unable to start activity ComponentInfo{cs495capstone.edu.bsu.doggydid/cs495capstone.edu.bsu.doggydid.HomeActivityListview}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
at android.support.v7.widget.ToolbarWidgetWrapper.(ToolbarWidgetWrapper.java:98)
at android.support.v7.widget.ToolbarWidgetWrapper.(ToolbarWidgetWrapper.java:91)
at android.support.v7.app.ToolbarActionBar.(ToolbarActionBar.java:73)
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:205)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:99)
at cs495capstone.edu.bsu.doggydid.HomeActivityListview.onCreate(HomeActivityListview.java:31)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Your Toolbar toolbar is declared/ initialized in the onCreate only, hence the scope is gone out of that method...
define the object as an activity variable and initialize it in the onCreate
public class HomeActivityListview extends AppCompatActivity {
ListView lv;
Context context;
ArrayList dogName;
ArrayList dogID;
public static int [] dogImages={R.drawable.dogpic};
public static String [] dogNames={};
private Toolbar toolbar; //define it here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_activity_listview);
toolbar = (Toolbar) findViewById(R.id.toolbar); //but init here
setSupportActionBar(toolbar);
context=this;
lv=(ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, dogImages));
}
I am having trouble setting the menu item text. I want when I start the activity to see the price of all my items in the basket. But whenever I start the shopping list activity I get below error:
java.lang.NullPointerException: Attempt to invoke interface method 'android.view.MenuItem android.view.Menu.findItem(int)' on a null object reference
This is the code:
public class Shopping_list_activity extends AppCompatActivity{
private Menu menu;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopping_list_activity);
updateMenuTitles();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.menu_shopping_list, menu);
this.menu = menu;
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.menu_shopping_list_saveList) {
Toast.makeText(Shopping_list_activity.this, " Clicked", Toast.LENGTH_SHORT).show();
}
// else if (id == R.id.menu_shopping_list_total){
// Toast.makeText(Shopping_list_activity.this, getPriceOfDisplayedItems() + " total", Toast.LENGTH_SHORT).show();
// }
return super.onOptionsItemSelected(item);
}
private void updateMenuTitles() {
MenuItem menuItem = menu.findItem(R.id.menu_shopping_list_total);
if (getPriceOfDisplayedItems() > 0) {
menuItem.setTitle(String.valueOf(getPriceOfDisplayedItems()));
} else {
menuItem.setTitle("Total: 0.00");
}
}
The getPriceOfDisplayedItems() displays the correct price.
And the XML file :
<?xml version="1.0" encoding="utf-8"?>
<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/menu_shopping_list_total"
android:title="#string/total"
app:showAsAction="always" />
</menu>
Can anyone help me with this problem?
I think onCreate method is called before onCreateOptions menu. That's why this.menu is null. Try moving invocation of updateMenuTitles to onCreateOptionsMenu.
You should add menu_shopping_list_saveList item in your xml:
<?xml version="1.0" encoding="utf-8"?>
<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/menu_shopping_list_total"
android:title="#string/total"
app:showAsAction="always" />
<item
android:id="#+id/menu_shopping_list_saveList"
android:title="#string/total"
app:showAsAction="always" />
</menu>
I have a simple app with a webview to load local HTML pages, I put all my files inside assets, now in my navigation drawer I want to have some text/links that open these pages, I tried to follow some tuts on the web but somehow I can't make it happen.
Any help would be greatly appreciated!
My code on android studio:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
activity_main.xml
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#ffffffff">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="History Of S.Johnson High School"
android:textSize="24sp"
android:gravity="center"
android:layout_marginTop="100dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/sjohnson"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"/>
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<!-- Side navigation drawer UI -->
<ListView
android:id="#+id/navList"
android:layout_width="250dp"
android:layout_height="match_parent"
android:layout_gravity="left|start"
android:background="#ffeeeeee"/>
MainActivity.java
public class MainActivity extends ActionBarActivity {
private WebView mWebView;
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
private ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.setWebViewClient(new MyAppWebViewClient());
mWebView.loadUrl("file:///android_asset/www/index.html");
}
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
} else {
super.onBackPressed();
}
}
private void addDrawerItems() {
String[] osArray = { "Android", "iOS", "Windows", "OS X", "Linux" };
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, osArray);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Navigation!");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#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;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
MyAppWebViewClient.java
public class MyAppWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(Uri.parse(url).getHost().length() == 0) {
return false;
}
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
view.getContext().startActivity(intent);
return true;
}
themes.xml
<resources>
<!-- Base application theme. -->
<style name="AppTheme"
parent="#style/Theme.AppCompat.Light.DarkActionBar">
<item name="android:actionBarStyle">#style/MyActionBar</item>
<!-- Support library compatibility -->
<item name="actionBarStyle">#style/MyActionBar</item>
</style>
<!-- ActionBar styles -->
<style name="MyActionBar"
parent="#style/Widget.AppCompat.Light.ActionBar.Solid.Inverse">
<item name="android:background">#drawable/actionbar_background</item>
<!-- Support library compatibility -->
<item name="background">#drawable/actionbar_background</item>
</style>
strings.xml
<?xml version="1.0" encoding="utf-8"?>
<string name="app_name">Info</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="drawer_open">Open navigation drawer</string>
<string name="drawer_close">Close navigation drawer</string>
As I understand you want to load yours html file from assets into WebView by clicking items in drawerMenu? If it's so you you need to add this lines to onClickListener of yours listView in drawer:
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Time for an upgrade!", Toast.LENGTH_SHORT).show();
//load file to webView
mWebView.loadUrl("REPLACE_IT_WITH_PATH_TO_FILE");
//close drawer
mDrawerLayout.closeDrawers();
}
});
anyone can give me a solution on how to use searchView widget(not in action bar) to show a list of result base on what the user type in searchView.
i am very new in developing android application and it happen that i want to try to create a simple application that can retrieve a data from the database.
i try to search from the internet and i found 'searchView' which i am able to search a data. i copy the code from the internet and modify some part. i read the code, i actually understand some code but not all, now from the MainActivity, i see that the 'onSearchRequested();' is called and then an intent is start with a searchView in action bar.
i try to modify the code with putting a searchView widget at the layout, i want to use this instead of 'onSearchRequested();' but im stock, dont know how show the 'ListView' as the result.
this what the run looks like:
a searchview in actionbar
and i want to change it like:
a searchView with result of list item but not in action bar
the code::
'MainActivity.java' // The original
public class MainActivity extends FragmentActivity{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn_search);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onSearchRequested(); // This will start eveything on button click
}
});
}
}
'MainActivity.java' // I already Modify
public class MainActivity extends FragmentActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btn = (Button) findViewById(R.id.btn_search);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
onSearchRequested();
}
});
SearchView searchView = (SearchView)findViewById(R.id.searchView1);
//This is just some code trying to customize the SearchView
searchView.setQueryHint("Type Word...");
int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
View searchPlate = searchView.findViewById(searchPlateId);
if (searchPlate!=null) {
searchPlate.setBackgroundColor(Color.WHITE);
int searchTextId = searchPlate.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
TextView searchText = (TextView) searchPlate.findViewById(searchTextId);
if (searchText!=null) {
searchText.setTextColor(Color.DKGRAY);
searchText.setHintTextColor(Color.LTGRAY);
}
}
// and im stock here, dont now what next to do
}
}
SearchableActivity.java //Nothings modify here
public class SearchableActivity extends FragmentActivity implements LoaderCallbacks<Cursor> {
ListView mLVCountries;
SimpleCursorAdapter mCursorAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchable);
// Getting reference to Country List
mLVCountries = (ListView)findViewById(R.id.lv_countries);
// Setting item click listener
mLVCountries.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent countryIntent = new Intent(getApplicationContext(), CountryActivity.class);
// Creating a uri to fetch country details corresponding to selected listview item
Uri data = Uri.withAppendedPath(CountryContentProvider.CONTENT_URI, String.valueOf(id));
// Setting uri to the data on the intent
countryIntent.setData(data);
// Open the activity
startActivity(countryIntent);
}
});
// Defining CursorAdapter for the ListView
mCursorAdapter = new SimpleCursorAdapter(getBaseContext(),
android.R.layout.simple_list_item_1,
null,
new String[] { SearchManager.SUGGEST_COLUMN_TEXT_1},
new int[] { android.R.id.text1}, 0);
// Setting the cursor adapter for the country listview
mLVCountries.setAdapter(mCursorAdapter);
// Getting the intent that invoked this activity
Intent intent = getIntent();
// If this activity is invoked by selecting an item from Suggestion of Search dialog or
// from listview of SearchActivity
if(intent.getAction().equals(Intent.ACTION_VIEW)){
Intent countryIntent = new Intent(this, CountryActivity.class);
countryIntent.setData(intent.getData());
startActivity(countryIntent);
finish();
}else if(intent.getAction().equals(Intent.ACTION_SEARCH)){ // If this activity is invoked, when user presses "Go" in the Keyboard of Search Dialog
String query = intent.getStringExtra(SearchManager.QUERY);
doSearch(query);
}
}
private void doSearch(String query){
Bundle data = new Bundle();
data.putString("query", query);
// Invoking onCreateLoader() in non-ui thread
getSupportLoaderManager().initLoader(1, data, this);
}
/** This method is invoked by initLoader() */
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle data) {
Uri uri = CountryContentProvider.CONTENT_URI;
return new CursorLoader(getBaseContext(), uri, null, null , new String[]{data.getString("query")}, null);
}
/** This method is executed in ui thread, after onCreateLoader() */
#Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor c) {
mCursorAdapter.swapCursor(c);
}
#Override
public void onLoaderReset(Loader<Cursor> arg0) {
// TODO Auto-generated method stub
}
}
activity_searchable.xml
//This is the list item result i want to show this under the searchView as the result
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lv_countries"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</LinearLayout>
searchable.xml
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="#string/search_hint"
android:searchSettingsDescription="#string/search_settings"
android:searchSuggestAuthority="in.wptrafficanalyzer.searchdialogdemo.CountryContentProvider"
android:searchSuggestIntentAction="android.intent.action.VIEW"
android:searchSuggestIntentData="content://in.wptrafficanalyzer.searchdialogdemo.CountryContentProvider/countries"
android:searchSuggestSelection=" ?"
android:searchSuggestThreshold="1"
android:includeInGlobalSearch="true" >
</searchable>
activity_main.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" >
<SearchView
android:id="#+id/searchView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:iconifiedByDefault="false"
android:imeOptions="actionSearch" >
</SearchView>
<Button
android:id="#+id/btn_search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/searchView1"
android:text="#string/search" />
</RelativeLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="in.wptrafficanalyzer.searchdialogdemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<!-- Activity with SearchDialog enabled -->
<activity
android:name="in.wptrafficanalyzer.searchdialogdemo.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Enabling Search Dialog -->
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchableActivity" />
</activity>
<!-- A Searchable activity, that handles the searches -->
<activity
android:name=".SearchableActivity" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable"/>
</activity>
<!-- Activity that shows the country details -->
<activity android:name=".CountryActivity" />
<!-- Content Provider to query sqlite database -->
<provider
android:name=".CountryContentProvider"
android:authorities="in.wptrafficanalyzer.searchdialogdemo.CountryContentProvider"
android:exported="true" />
</application>
</manifest>
Again, Please im just a newbie, if there's something wrong on my question im really sorry, i love programming and im just trying to learn. anyway, thank you very much!!! any help will be appreciated!
Just refer this link ..
http://wptrafficanalyzer.in/blog/customizing-autocompletetextview-to-display-images-and-text-in-the-suggestion-list-using-simpleadapter-in-android/
It's not a big deal. If You know the CustomListView then it's easy for you.
Did not understand the whole question, but maybe you want to forget the onSearchRequested(); and change it with your customize searchView. try this,
you dont need to change anything on your code except in MainActivity. if you don't want onSearchRequested(); for some reason... here..
If you have a custom searchView in your actionbar and use it instead of searchView in your layout you may use this code:
public class MainActivity extends FragmentActivity{
static SearchView searchView;
#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.main, menu);
//Your design here
MenuItem menuItem = menu.findItem(R.id.search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setIconifiedByDefault(false);
searchView.setQueryHint("Type something...");
int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
View searchPlate = searchView.findViewById(searchPlateId);
if (searchPlate!=null) {
searchPlate.setBackgroundColor(Color.DKGRAY);
int searchTextId = searchPlate.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
TextView searchText = (TextView) searchPlate.findViewById(searchTextId);
if (searchText!=null) {
searchText.setTextColor(Color.WHITE);
searchText.setHintTextColor(Color.WHITE);
}
}
//Maybe this is what you want
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
return true;
}
}
and in you res/menu/main.xml add this
<item android:id="#+id/search"
android:title="#string/search_title"
android:icon="#drawable/ic_search"
android:showAsAction="collapseActionView|ifRoom"
android:actionViewClass="android.widget.SearchView" />
and try to execute your project
or if you really want to use your custom searchView in your layout then this:
public class MainActivity extends FragmentActivity{
static SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchView = (SearchView)findViewById(R.id.searchView1);
searchView.setQueryHint("Type Word...");
int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_plate", null, null);
View searchPlate = searchView.findViewById(searchPlateId);
if (searchPlate!=null) {
searchPlate.setBackgroundColor(Color.WHITE);
int searchTextId = searchPlate.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
TextView searchText = (TextView) searchPlate.findViewById(searchTextId);
if (searchText!=null) {
searchText.setTextColor(Color.DKGRAY);
searchText.setHintTextColor(Color.LTGRAY);
//This is what you want?
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.getRootView();//Notice that i change this
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
}
}
}
reference:: Setting Up the Search...