Android Studio's navigation problem throws error java.lang.IllegalArgumentException - java

So i have been trying to get a button to work and navigate through to another fragment but only accessible from that button, which i want separate from my bottom nav bar, that one works
the main issue i find is that when trying to add these actions just like i would with the bottom navigation it throws an java.lang.IllegalArgumentException: ID does not reference a View inside this Activity
can anyone point me in the right direction and tell me what I'm doing wrong?
I think its to do with confusion with the navhost fragments? MAybe they think it's the same and overwriting eachother? Idk, ive been going in circles, and disabling my bottom navigation bar doesnt fix it either.
Heres my Main Activity Code, along with the java fragment with the button i want to have this action.
public class MainActivity extends AppCompatActivity {
private AppBarConfiguration appBarConfiguration;
ActivityMainBinding binding;
BottomNavigationView bottomNavigationView; //initializing the bottom nav bar from activity_main again
#Override
protected void onCreate(Bundle savedInstanceState) {//changing content which is based on the activity_main class, think of activity_main as the main driver class, where everything is activated at
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
//FROM HERE
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
appBarConfiguration = new AppBarConfiguration.Builder(navController.getGraph()).build();
NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration);
//TO HERE THESE PARTS THROW THE EXCEPTIONS
#Override
public boolean onSupportNavigateUp() {
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment_content_main);
return NavigationUI.navigateUp(navController, appBarConfiguration)
|| super.onSupportNavigateUp();
}
}
Along with the code for my navigation graph, the other actions in there, are for my bottom navigation, which is why one fragment has 2 actions, 1 foor that button, shared with the same nav _graph,
<navigation 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/my_nav"
app:startDestination="#id/fl1">
<fragment
android:id="#+id/fl1"
android:name="com.example.appnav.FirstFragment"
android:label="fragment_first"
tools:layout="#layout/fragment_first" >
<action
android:id="#+id/action_firstFragment_to_secondFragment"
app:destination="#id/fl2" />
<!--These fragments (pages) are all linked by the action button with where they end up on click -->
</fragment>
<fragment
android:id="#+id/fl2"
android:name="com.example.appnav.SecondFragment"
android:label="fragment_second"
tools:layout="#layout/fragment_second" >
<action
android:id="#+id/action_secondFragment_to_frag3"
app:destination="#id/fl3" />
<action
android:id="#+id/action_fl2_to_flp"
app:destination="#id/flp" />
</fragment>
<fragment
android:id="#+id/fl3"
android:name="com.example.appnav.frag3"
android:label="fragment_frag3"
tools:layout="#layout/fragment_frag3" >
<action
android:id="#+id/action_fl3_to_fl4"
app:destination="#id/fl4" />
</fragment>
<fragment
android:id="#+id/fl4"
android:name="com.example.appnav.frag4"
android:label="fragment_frag4"
tools:layout="#layout/fragment_frag4" >
<action
android:id="#+id/action_fl4_to_fl5"
app:destination="#id/fl5" />
</fragment>
<fragment
android:id="#+id/fl5"
android:name="com.example.appnav.fragt"
android:label="fragment_fragt"
tools:layout="#layout/fragment_temp"/>
<fragment
android:id="#+id/flp"
android:name="com.example.appnav.pay_frag"
android:label="pay_frag"
tools:layout="#layout/pay_frag" >
<action
android:id="#+id/action_flp_to_fl_pdone"
app:destination="#id/fl_pdone" />
</fragment>
<fragment
android:id="#+id/fl_pdone"
android:name="com.example.appnav.fl_pdone"
android:label="fragment_fl_pdone"
tools:layout="#layout/fragment_fl_pdone" />
</navigation>
This is the fragment with the button involved
basically trying to use the action from the nav_graph, and take u to the next fragment, in this case a fragment which is not on the bottom navigation
public class SecondFragment extends Fragment {
private FragmentSecondBinding binding;
#Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState
) {
binding = FragmentSecondBinding.inflate(inflater, container, false);
return binding.getRoot();
}
public void onViewCreated(#NonNull View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
binding.buttonSecond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(SecondFragment.this)
.navigate(R.id.action_fl2_to_flp);
}
});
}
#Override
public void onDestroyView() {
super.onDestroyView();
binding = null;
}

NavController wants view not context. Just change your context to view as below.
binding.buttonSecond.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
NavHostFragment.findNavController(view)
.navigate(R.id.action_fl2_to_flp);
}
});
If not solved, let me know.

Related

How to display ActionBar in the entire App Android

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.

How to link local HTML pages with strings in a navigation drawer?

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();
}
});

Android SearchView Widget With List Item as a Result

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...

"Unfortunately -app- has stopped" on my fist android app ever [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 8 years ago.
I've been having this issue, this is my first android app and I probably did something stupid. I am a total noob at this and this has been driving me insane. Running the app will give me the error, "Unfortunately -app- has stopped working." Help would be appreciated
Fragment Main:
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.gmail.sherwoodax.appone.MainActivity$PlaceholderFragment" >
<Button
android:id="#+id/dBID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Dead Button"
android:layout_centerInParent="true"
/>
<TextView
android:id="#+id/tView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="The Button is below me"
android:layout_above="#+id/dBID"
android:gravity="center"
android:textSize="20sp"
/>
</RelativeLayout>
Main Class:
package com.gmail.sherwoodax.appone;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
testMethod();
}
}
private void testMethod() {
Button b = (Button) findViewById(R.id.dBID);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, "text", Toast.LENGTH_LONG).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.gmail.sherwoodax.appone"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.gmail.sherwoodax.appone.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>
</manifest>
LogCat stacktrace:
05-28 11:15:54.977: E/AndroidRuntime(31586): Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.gmail.sherwoodax.appone:id/container) for fragment PlaceholderFragment{41c157b0 #0 id=0x7f05003c}
05-28 11:20:47.344: E/AndroidRuntime(32409): Caused by: java.lang.IllegalArgumentException: No view found for id 0x7f05003c (com.gmail.sherwoodax.appone:id/container) for fragment PlaceholderFragment{41c10d00 #0 id=0x7f05003c}
Thank you
Please post the logcat stacktrace for the crash so we can help pinpoint the exact problem. However, I would guess that it has to do with your Button.
In your testMethod() you declare:
Button b = (Button) findViewById(R.id.dBID);
But because it is declared inside this method it is not within scope for your activity and exists only inside that single method call and is lost afterwards.
You should declare your button as a class level variable in your Activity/Fragment:
public class MainActivity extends ActionBarActivity {
private Button myButton;
...
then assign the Button in your onCreate() (or onViewCreate() for a Fragment):
public void onCreate(...) {
myButton = (Button) findViewById(...);
...
and then anywhere else in your class you want to use that Button you can refer to it without needing to pull and cast it again from your view:
button.setText(newButtonText);

Set GoogleMaps inside Fragment

I have a FragmentActivity with a lateral bar (like a menu bar), and a container to put fragments there.
From this FragmentActivity I call to other fragments using onClickListener of each button (from the lateral bar).
So for example, FragmentActivity is called MenuViewActivity. This calls Navigation fragment and sets it's layout on the container.
In Navigation Fragment, I have a button that starts GoogleMaps (or that is what I need to get)
[MenuViewActivity(FragmentActivity)] >> [NavigationFragment(Fragment)] >> [GoogleMapsFragment(Fragment)]
The idea is to fit the GoogleMaps windows in the same container that I set the other Fragments (like navigationFragment)
This is the code of NavigationFragment.java:
public class NavigationFragment extends Fragment implements OnClickListener {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**Inflate the layout for this fragment*/
View mainView = inflater.inflate(R.layout.navegacion, container, false);
mapBtn = (ImageView) mainView.findViewById(R.id.mapsButton);
navBtn = (ImageView) mainView.findViewById(R.id.navigatorButton);
mapBtn.setOnClickListener(this);
navBtn.setOnClickListener(this);
return mainView;
}
#Override
public void onClick(View v) {
switch (v.getId()){
case R.id.mapsButton:
GoogleMapsFragment fragment_maps = new GoogleMapsFragment();
FragmentTransaction ft = getFragmentManager().beginTransaction();
ft.replace(R.id.fragment_container, fragment_maps).commit();
break;
}
}
This is the code of GoogleMapsFragment.java:
public class GoogleMapsFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**Inflate the layout for this fragment*/
View mainView = inflater.inflate(R.layout.google_maps, container, false);
SupportMapFragment fm = (SupportMapFragment) getFragmentManager().findFragmentById(R.id.map);
mMap = fm.getMap();
return mainView;
}
And the code of the google_maps.xml:
<fragment
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:name="com.google.android.gms.maps.MapFragment"
map:cameraTilt="45"
map:cameraZoom="14"
class="com.google.android.gms.maps.SupportMapFragment" />
I think that I'm not calling right the GoogleMapsFragment on the onClick, or that I cannot call maybe to the *fragment_container* from other fragment like I do in NavigationFragment because this id belongs to the layout of MenuViewActivity.
The logCat output's this:
android.view.InflateException: Binary XML file line #3: Error inflating class fragment
at com.example.GoogleMapsFragment.onCreateView(GoogleMapsFragment.java:47)
Caused by: java.lang.IllegalStateException: A required meta-data tag in your app's
AndroidManifest.xml does not exist. You must have the following declaration within the <application> element:
<meta-data android:name="com.google.android.gms.version" android:value="#integer/google_play_services_version" />
The Exception is telling you exactly what the problem is. Since the last update of the google-play-services_lib you need to add the following to the AndroidManifest.xml within the application tag:
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
Also, you have:
android:name="com.google.android.gms.maps.MapFragment"
class="com.google.android.gms.maps.SupportMapFragment"
You should only have one of this attributes. Here you have two and they are pointing to two different classes. If you want backwards compatibility you should use com.google.android.gms.maps.SupportMapFragment.
One suggestion. If you only need to display a map why not extends SupportMapFragment or MapFragment instead of Fragment?

Categories

Resources