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...
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I've spent my last 8 hours to solve this simple dumb NPE(about to go mentally blind).Almost read everything about this issue,tried everything possible but same result,so I'll be posting every code related,I hope someone can help !
First of all this is the full error I get through logcat;
2019-03-12 11:16:56.130 23426-23426/com.demotxt.myapp.myapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.demotxt.myapp.myapplication, PID: 23426
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v7.widget.SearchView.setSearchableInfo(android.app.SearchableInfo)' on a null object reference
at com.demotxt.myapp.myapplication.activities.Main3Activity.onCreateOptionsMenu(Main3Activity.java:130)
at android.app.Activity.onCreatePanelMenu(Activity.java:3317)
at android.support.v4.app.FragmentActivity.onCreatePanelMenu(FragmentActivity.java:340)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:93)
at android.support.v7.app.AppCompatDelegateImplBase$AppCompatWindowCallbackBase.onCreatePanelMenu(AppCompatDelegateImplBase.java:332)
at android.support.v7.view.WindowCallbackWrapper.onCreatePanelMenu(WindowCallbackWrapper.java:93)
at android.support.v7.app.ToolbarActionBar.populateOptionsMenu(ToolbarActionBar.java:454)
at android.support.v7.app.ToolbarActionBar$1.run(ToolbarActionBar.java:55)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6682)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)
My Main3Activity which I do stuff about searching;
public class Main3Activity extends AppCompatActivity {
private final String JSON_URL = "https://MYURLXX" ;
private JsonArrayRequest request ;
private RequestQueue requestQueue ;
private List<Anime> lstAnime ;
private RecyclerView recyclerView ;
RecyclerViewLiveAdapter adapter;
RecyclerView.LayoutManager layoutManager;
Toolbar toolbar;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
toolbar=findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
lstAnime = new ArrayList<>() ;
recyclerView = findViewById(R.id.recyclerviewid);
jsonrequest();
}
private void jsonrequest() {
request = new JsonArrayRequest(JSON_URL, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSONObject jsonObject = null ;
for (int i = 0 ; i < response.length(); i++ ) {
try {
jsonObject = response.getJSONObject(i) ;
Anime anime = new Anime() ;
anime.setName(jsonObject.getString("name"));
anime.setDescription(jsonObject.getString("description"));
anime.setRating(jsonObject.getString("Rating"));
anime.setCategorie(jsonObject.getString("categorie"));
anime.setStudio(jsonObject.getString("studio"));
anime.setImage_url(jsonObject.getString("img"));
anime.setLink(jsonObject.getString("link"));
anime.setDrm_scheme(jsonObject.getString("drm_scheme"));
anime.setDrm_license_url(jsonObject.getString("drm_license_url"));
anime.setDrm(jsonObject.getString("drm"));
anime.setSubtitle(jsonObject.getString("subtitle"));
anime.setSubtitle1(jsonObject.getString("subtitle1"));
anime.setSubtitle2(jsonObject.getString("subtitle2"));
lstAnime.add(anime);
} catch (JSONException e) {
e.printStackTrace();
}
}
setuprecyclerview(lstAnime);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(Main3Activity.this);
requestQueue.add(request) ;
}
private void setuprecyclerview(List<Anime> lstAnime) {
RecyclerViewLiveAdapter myadapter = new RecyclerViewLiveAdapter(this,lstAnime) ;
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setAdapter(myadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_item,menu);
MenuItem searchItem =menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) searchItem.getActionView();
SearchManager searchManager=(SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
newText=newText.toLowerCase();
List<Anime> myList=new ArrayList<>();
for (Anime anime:lstAnime){
String moviename =anime.getName().toLowerCase();
if (moviename.contains(newText))
myList.add(anime);
}
adapter.setSearchOperation(myList);
return false;
}
});
return true;
}
}
Related part in my RecyclerViewAdapter;
public void setSearchOperation(List<Anime> newList) {
mData=new ArrayList<>();
mData.addAll(newList);
notifyDataSetChanged();
}
My searchable.xml in res/xml;
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="#string/search" >
</searchable>
Related part of Main3Activity in AndroidManifest.xml;
<activity android:name=".activities.Main3Activity">
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable"
android:value=".activities.Main3Activity"/>
<intent-filter>
<action android:name="android.intent.action.SEARCH"/>
</intent-filter>
</activity>
And this is the toolbar's layout in layouts which is called by RecyclerView's layout like this "include layout ="#layout/toolbar_layout">
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="#color/colorPrimary"
android:theme="#style/ThemeOverlay.AppCompat.Dark"></android.support.v7.widget.Toolbar>
And this is the menu_item xml file in menu folder;
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
<item
android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="Search Test"
app:actionViewClass="android.support.v7.widget.SearchView"
app:showAsAction="ifRoom|collapseActionView"/>
</menu>
I don't use pro-guard so it's not the case and I always used app:showAsAction and app:actionViewClass but as I said all I get that nullpointerexception on same line,thanks in advance!
Replace your initialization of SearchView with this line
SearchView searchView = new SearchView(this.getSupportActionBar().getThemedContext());
Replace:
SearchView searchView = (SearchView) searchItem.getActionView();
With:
MenuItem searchItem =menu.findItem(R.id.action_search);
mSearchView = (SearchView) MenuItemCompat.getActionView(searchItem);
Also make sure your menu.xml file should look like below:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:yourapp="http://schemas.android.com/apk/res-auto" >
<item android:id="#+id/action_search"
android:title="#string/action_search"
android:icon="#drawable/action_search"
yourapp:showAsAction="always|collapseActionView"
yourapp:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
I am having problems implementing the actionbar (which I think is now replaced by toolbar). What I want is a small drop down menu with the 3 dots where I can have a few options such as settings and credits. I have tried to set it up so that the menu appears on the homelistview.java page. I feel like I have been going in circles trying different solutions and getting a new error each time and it always points back to the same location mentioned below.
setSupportActionBar(toolbar);
I had originally thought it was because I didn't include setContentView(R.layout.activity_main); but it was not happy including 2 content views. Any help would be appreciated.
Here is my code.
styles.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
--------------- menu_main.xml-------------------
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="cs495capstone.edu.bsu.myapplication.MainActivity">
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never" />
<item
android:id="#+id/action_credits"
android:orderInCategory="100"
android:title="#string/action_credits"
app:showAsAction="never" />
<item
android:id="#+id/action_lovely"
android:orderInCategory="100"
android:title="#string/action_lovely"
app:showAsAction="never" />
</menu>
--------------activity_main.xml ----------------
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="cs495capstone.edu.bsu.myapplication.HomeActivityListview">
<android.support.design.widget.AppBarLayout
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/activity_add_appointment" />
<include layout="#layout/activity_add_history" />
<include layout="#layout/activity_appointments" />
<include layout="#layout/activity_dog_profile" />
<include layout="#layout/activity_history" />
<include layout="#layout/activity_home" />
<include layout="#layout/activity_home_activity_listview" />
<include layout="#layout/activity_login" />
<include layout="#layout/activity_new_dog" />
<include layout="#layout/activity_registration" />
<include layout="#layout/activity_splash_screen" />
<include layout="#layout/activity_update_dog" />
</android.support.design.widget.CoordinatorLayout>
----------------------- homeactivitylistview.xml-------------------------
public class HomeActivityListview extends AppCompatActivity {
ListView lv;
Context context;
ArrayList dogName;
ArrayList dogID;
public static int [] dogImages={R.drawable.dogpic};
public static String [] dogNames={};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_activity_listview);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
context=this;
lv=(ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, dogImages));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendProfile(View view) {
Intent intent = new Intent(getApplicationContext(), DogProfileActivity.class);
startActivity(intent);
}
public void NumberOne(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number one");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void NumberTwo(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number two");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void AddNewDog(View view) {
Intent intent = new Intent(getApplicationContext(), NewDogActivity.class);
startActivity(intent);
}
}
------------------ main_activity.java -----------------
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
--------------homelistview.java------------------
public class HomeActivityListview extends AppCompatActivity {
ListView lv;
Context context;
ArrayList dogName;
ArrayList dogID;
public static int [] dogImages={R.drawable.dogpic};
public static String [] dogNames={};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_activity_listview);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
context=this;
lv=(ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, dogImages));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendProfile(View view) {
Intent intent = new Intent(getApplicationContext(), DogProfileActivity.class);
startActivity(intent);
}
public void NumberOne(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number one");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void NumberTwo(View view) {
AlertDialog.Builder alertDlg = new AlertDialog.Builder(this);
alertDlg.setMessage("Confirm Dog went number two");
alertDlg.setCancelable(false);
alertDlg.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.setNegativeButton("Change", new DialogInterface.OnClickListener(){
#Override
public void onClick(DialogInterface dialog, int which) {
//HomeActivity.super.onBackPressed();
}
});
alertDlg.create().show();
}
public void AddNewDog(View view) {
Intent intent = new Intent(getApplicationContext(), NewDogActivity.class);
startActivity(intent);
}
}
---------------androidmanifest-----------------
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cs495capstone.edu.bsu.doggydid" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme" >
<activity android:name=".SplashScreenActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".RegistrationActivity"
android:label="Registration" />
<activity
android:name=".NewDogActivity"
android:label="Dog Information" />
<activity
android:name=".LoginActivity"
android:label="Login" />
<activity
android:name=".HomeActivity"
android:label="#string/title_activity_home" />
<activity
android:name=".DogProfileActivity"
android:label="#string/title_activity_dog_profile" />
<activity
android:name=".HistoryActivity"
android:label="#string/title_activity_records" />
<activity
android:name=".addHistoryActivity"
android:label="#string/title_activity_add_record" />
<activity
android:name=".EventsActivity"
android:label="#string/title_activity_events" />
<activity
android:name=".addEventsActivity"
android:label="#string/title_activity_add_events" />
<activity
android:name=".UpdateDogActivity"
android:label="#string/title_activity_update_dog" />
<activity
android:name=".HomeActivityListview"
android:label="#string/title_activity_home_activity_listview"
android:theme="#style/AppTheme.NoActionBar">
</activity>
</application>
</manifest>
-----------------------Error Readout--------------------
04-14 13:35:36.905 3117-3117/cs495capstone.edu.bsu.doggydid E/AndroidRuntime: FATAL EXCEPTION: main
Process: cs495capstone.edu.bsu.doggydid, PID: 3117
java.lang.RuntimeException: Unable to start activity ComponentInfo{cs495capstone.edu.bsu.doggydid/cs495capstone.edu.bsu.doggydid.HomeActivityListview}: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2298)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference
at android.support.v7.widget.ToolbarWidgetWrapper.(ToolbarWidgetWrapper.java:98)
at android.support.v7.widget.ToolbarWidgetWrapper.(ToolbarWidgetWrapper.java:91)
at android.support.v7.app.ToolbarActionBar.(ToolbarActionBar.java:73)
at android.support.v7.app.AppCompatDelegateImplV7.setSupportActionBar(AppCompatDelegateImplV7.java:205)
at android.support.v7.app.AppCompatActivity.setSupportActionBar(AppCompatActivity.java:99)
at cs495capstone.edu.bsu.doggydid.HomeActivityListview.onCreate(HomeActivityListview.java:31)
at android.app.Activity.performCreate(Activity.java:5933)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
at android.app.ActivityThread.access$800(ActivityThread.java:144)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5221)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
Your Toolbar toolbar is declared/ initialized in the onCreate only, hence the scope is gone out of that method...
define the object as an activity variable and initialize it in the onCreate
public class HomeActivityListview extends AppCompatActivity {
ListView lv;
Context context;
ArrayList dogName;
ArrayList dogID;
public static int [] dogImages={R.drawable.dogpic};
public static String [] dogNames={};
private Toolbar toolbar; //define it here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_activity_listview);
toolbar = (Toolbar) findViewById(R.id.toolbar); //but init here
setSupportActionBar(toolbar);
context=this;
lv=(ListView) findViewById(R.id.listView);
lv.setAdapter(new CustomAdapter(this, dogImages));
}
I 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();
}
});
I have an Activity (MainActivity) with a search button in the action bar. It searches by some input string and shows the results in a ListView in another Activity (SearchResultsActivity). The user might click in any result to select it.
I want to return the value selected by the user to the main activity, but it's not working. I looked in the documentation but I didn't find anything related.
I tried to use setResult(Intent) in the results activity but the onActivityResult() from the main activity never gets called.
What am I doing wrong? How can I do it?
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="foo.bar" >
<!-- ... -->
<uses-sdk android:minSdkVersion="11" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name">
<!-- Main Activity -->
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main">
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResultsActivity" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- Search results activity -->
<activity android:name=".SearchResultsActivity"
android:parentActivityName=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
</application>
</manifest>
Menu.xml:
<menu xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
tools:context=".MainActivity">
<!-- Search -->
<item android:id="#+id/action_search"
android:icon="#drawable/ic_action_search"
android:title="#string/action_search"
android:showAsAction="always"
android:actionViewClass="android.widget.SearchView" />
<!-- ... -->
</menu>
MainActivity:
public class MainActivity extends FragmentActivity {
// ...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
final MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.activity_main_menu, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// never gets called!
super.onActivityResult(requestCode, resultCode, data);
}
// ...
}
SearchResultsActivity:
public class SearchResultsActivity extends Activity {
private ListView listResults;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_results);
// get the action bar
ActionBar actionBar = getActionBar();
// Enabling Back navigation on Action Bar icon
actionBar.setDisplayHomeAsUpEnabled(true);
listResults = (ListView) findViewById(R.id.listResults);
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
/**
* Handling intent data
*/
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
final Serializable[] results = find(query);
listResults.setAdapter(new ArrayAdapter<BusLine>(this, R.layout.list_view, busLines));
listResults.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Serializable selectedResult = (Serializable) parent.getItemAtPosition(position);
setResult(RESULT_OK, new Intent().putExtra("result", selectedResult));
finish();
}
});
}
}
}
I can understand why you might think that you would use setResult and onActivityResult to handle clicks in your search results activity, but that is not how it works. Only when you launch an activity with startActivityForResult do these functions apply -- not when displaying search results.
The solution is to call startActivity on your MainActivity in the normal fashion, that is, not using activity results. Something like this:
listResults.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Serializable selectedResult = (Serializable) parent.getItemAtPosition(position);
Intent intent = new Intent();
intent.putExtra("result", selectedResult);
intent.setClass(SearchResultsActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
});
Now you will also need to capture this search result in your MainActivity, although you need to make sure you handle the normal case as well as the search results case:
#Override
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
if (intent.hasExtra("result")) {
// Launched from search results
Serializable selectedResult = (Serializable) intent.getSerializableExtra("result");
...
}
...
}
So I have 2 activities and in the first one I have a menu item that once clicked should open the second activity. The changing part works but it's not changing what it is supposed to, in the second activity which I activate with this :
Intent intent = new Intent(this, EditView.class);
startActivity(intent);
break;
in the first activity onOptionsItemSelected, and I click a button from the menu, in this second activity I have a diferent layout and I do this setContentView(R.layout.second); to change the layout I have a functional xml file because I tried it in another project, in the manifest file I have this :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ro.merca.ionel"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-sdk android:minSdkVersion="15" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".FileList"
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=".EditView"
android:label="#string/app_name" />
</application>
</manifest>
the problem is that when I click the option from the menu it loads a simple layout without all the things I put in second.xml... I don't know that the problem is...
public class EditView extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
Intent intent = getIntent();
TextView tv = new TextView(this);
final TextView name = (TextView) findViewById(R.id.name);
final TextView text = (TextView) findViewById(R.id.text);
setContentView(tv);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(1,1,1,"Salveaza Nota").setIcon(android.R.drawable.btn_default);
menu.add(1,2,2,"Anuleaza Modificari").setIcon(android.R.drawable.btn_default);
menu.add(1,3,3,"Sterge Nota").setIcon(android.R.drawable.btn_default);
menu.add(1,4,4,"Share").setIcon(android.R.drawable.btn_default);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case 1 :
Intent intent = new Intent(this, EditView.class);
this.startActivity(intent);
break;
case 2 :
break;
case 3 :
break;
case 4 :
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Nume" />
<EditText
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Text" />
<EditText
android:id = "#+id/text"
android:inputType="text|textMultiLine"
android:minLines="5"
android:gravity="top"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
You are calling setContentView twice in onCreate(). Remove the second one and try again.
I am bit confused over here. If you are just moving from 1st activity to 2nd without passing any values then what's the use of using getIntent() etc?
Write simply this much, and you will land on your desired activity:
public class EditView extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
TextView tv = new TextView(this);
final TextView name = (TextView) findViewById(R.id.name);
final TextView text = (TextView) findViewById(R.id.text);
}
}