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();
}
});
Related
I'm trying to use a navigation drawer in my Main activity.
when i run it in API 23 Emulator , everything looks fine.
But when I run it in API 16 Emulator, my action bar goes away!
Here is my manifest file :
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Here is my styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/line1</item>
<item name="colorPrimaryDark">#color/line1_dark</item>
<item name="colorAccent">#color/isbc</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
Here is my v21/styles.xml
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">#android:color/transparent</item>
</style>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/line1</item>
<item name="colorPrimaryDark">#color/line1_dark</item>
<item name="colorAccent">#color/isbc</item>
</style>
And this is my Mainactivity.java
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
NavigationView navigationView = null;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) 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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
changeTypeface(navigationView);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#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;
}
private void applyFontToItem(MenuItem item, Typeface font) {
SpannableString mNewTitle = new SpannableString(item.getTitle());
mNewTitle.setSpan(new CustomTypefaceSpan("", font, 16), 0 ,
mNewTitle.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
item.setTitle(mNewTitle);
}
private void changeTypeface(NavigationView navigationView) {
FontTypeface fontTypeface = new FontTypeface(this);
Typeface typeface = fontTypeface.getTypefaceAndroid();
MenuItem item;
item = navigationView.getMenu().findItem(R.id.nav_camera);
item.setTitle("لیست ایستگاه ها");
item.setIcon(R.drawable.ic_action_stations);
applyFontToItem(item, typeface);
item = navigationView.getMenu().findItem(R.id.nav_gallery);
item.setTitle("نقشه");
item.setIcon(R.drawable.ic_action_map);
applyFontToItem(item, typeface);
item = navigationView.getMenu().findItem(R.id.nav_slideshow);
item.setTitle("درباره ما");
item.setIcon(R.drawable.ic_action_us);
applyFontToItem(item, typeface);
}
#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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_camera) {
MainFragment fragment = new MainFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit(); }
else if (id == R.id.nav_gallery) {
MapFragment fragment = new MapFragment();
android.support.v4.app.FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
} else if (id == R.id.nav_slideshow) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
Here is my app_bar_main :
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
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/fragment_main" />
<FrameLayout
android:id="#+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="match_parent"></FrameLayout>
Here is my activity_main.xml
<android.support.v4.widget.DrawerLayout 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:id="#+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:openDrawer="start">
<include
layout="#layout/app_bar_main"
android:id="#+id/app_bar"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<android.support.design.widget.NavigationView
android:id="#+id/nav_view"
android:layout_width="220dp"
android:layout_height="match_parent"
android:layout_gravity="start"
android:fitsSystemWindows="true"
app:headerLayout="#layout/nav_header_main"
app:menu="#menu/activity_main_drawer" />
When I run this code in emulator API 21, everything looks fine.
But when I run it in API 16, i get this error:
"This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead."
I guess it's telling me not to use actionbar, but how can i actually display my navigation drawer if i set windowActionBar to false?
i've tried this topic but it didn't work
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));
}
Hello i'm making an application for Android and I added an ActionBarDrawerToggle to the app. When i select an item, the ActionBarDrawerToggle disappear.
What I want to do :
Create the ActionBarDrawerToggle in MainWindow.java [Done]
Create Profil.java and Planning.java and extend MainWindow into Profil and Planning to display the ActionBarDrawerToggle. [Problem]
I'm using :
UPDATE
Mainactivity :
public class MainWindow extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTheme(R.style.AppTheme_NoActionBar);
setContentView(R.layout.activity_mainwindow);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) 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();
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.mainwindow, 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.nav_profil) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_profil) {
Intent intent = new Intent(this, Profil.class);
startActivity(intent);
} else if (id == R.id.nav_planning) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
the Profil :
public class Profil extends MainWindow {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_profil);
System.out.println("Profil");
}
}
AndroidManifest.xml :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.main">
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".Login"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainWindow"
android:label="#string/title_activity_mainwindow"></activity>
<activity
android:name=".Connection"></activity>
<activity
android:name=".Profil"></activity>
</application>
</manifest>
if you are using a material support lib you will have to add the action bar manually in the XML file
<android.support.design.widget.AppBarLayout
android:id="#+id/appbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingTop="#dimen/appbar_padding_top"
android:theme="#style/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:layout_scrollFlags="scroll|enterAlways"
app:popupTheme="#style/PopupOverlay"/>
</android.support.design.widget.AppBarLayout>
and in the java Activity file in onCreate() method add the following lines
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Hope this works for you
Be sure #style/AppTheme theme not NoActionBar.
so I've decided to make an android application for my website (not many people read it, however I think it'll look good on my Ucas!
My problem is that after the splash screen is displayed on my phone the app crashes, I'm quite new to android app development so I'm unsure about what I'm doing wrong.
I've uploaded my sourcecode on to Github so that you can have a better look at it!
Heres some of my code:
MainActivity.java
package com.alffiw.alffisblog;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
public class MainActivity extends Activity {
private WebView mWebView;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://www.coderefer.com");
mWebView.setWebViewClient(new HelloWebViewClient());
}
private class HelloWebViewClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url)
{
webView.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(view.GONE);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{ //if back key is pressed
if((keyCode == KeyEvent.KEYCODE_BACK)&& mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.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 onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
}
SplashScreen.java
package com.alffiw.alffisblog;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
public class SplashScreen extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
Thread timerThread = new Thread(){
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent intent = new Intent(SplashScreen.this,MainActivity.class);
startActivity(intent);
}
}
};
timerThread.start();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
finish();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<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" 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">
<ProgressBar
android:layout_centerHorizontal="true"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:id="#+id/progressBar1"/>
<TextView
android:layout_below="#+id/progressBar1"
android:layout_height="wrap_content"
android:id="#+id/LoadingText"
android:layout_width="fill_parent"
android:text="Loading, Please Wait.."
android:textSize="20sp"
android:gravity="center_horizontal">
</TextView>
<WebView
android:id="#+id/activity_main_webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
content_main.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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.alffiw.alffisblog.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!" />
</RelativeLayout>
splash.xml
<?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:background="#drawable/splash_image"
android:orientation="vertical">
</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.alffiw.alffisblog">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SplashScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.coderefer.androidsplashscreenexample.MAINACTIVITY" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
Thank you for any help in advance!
Instead of calling from thread use Handler
protected void onCreate(Bundle savedInstanceState) {
//your stuff.....
new android.os.Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (!isFinishing()) {//just to make sure user didn,t press back button
Intent mainIntent = new Intent(Splashscreen.this, MainActivity.class);
startActivity(mainIntent);
finish();
}
}
}, 3000);//waiting time
}
You can't call startActivity(intent) form inside the thread you've created. Firstly because startActivity(...) is a Context method and secondly, you need to execute this statement on the UI thread.
Try this:
#Override
protected void onCreate(Bundle savedInstanceState) {
...
final Context activity = this;
Thread timerThread = new Thread(new Runnable(
public void run(){
try{
sleep(3000);
}catch(InterruptedException e){
e.printStackTrace();
}finally{
activity.runOnUiThread(new Runnable() {
public void run(){
Intent intent = new Intent(SplashScreen.this,MainActivity.class);
activity.startActivity(intent);
}
});
}
}
));
timerThread.start();
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...