onNavigationItemSelected set active item position title on actionbar - android

ActionBar
Let me try and explain this, I have a dropdown Actionbar with the selectable items, Home, Contact Us and About.
When the main activity loads, the default item shown on the ActionBar dropdown is Home. OK.
When I select the second item (contact us), the CURRENT ACTIVITY (main activity) sets itself as “Contact Us” then..
..then the NEXT ACTIVITY (contact us) starts up but sets the ActionBar back to default “Home” instead of ‘contact us’
Please see my code below:
public class MainActivity extends Activity {
private boolean mNaviFirstHit = true;
….
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SpinnerAdapter sadapter = ArrayAdapter.createFromResource(this, R.array.actions, R.layout.dropdown_textcolor);
// Callback
OnNavigationListener callback = new OnNavigationListener() {
String[] items = getResources().getStringArray(R.array.actions)
#Override
public boolean onNavigationItemSelected(int position, long id) {
if (mNaviFirstHit) {
mNaviFirstHit = false;
return true;
}
if (items[position].equals("Home"))
{
System.out.println("Selected Home");
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
if (items[position].equals("Contact Us"))
{
System.out.println("Selected Contact US");
startActivity(new Intent(getApplicationContext(),ActionContact.class));
}
if (items[position].equals("About"))
{
System.out.println("Selected About");
startActivity(new Intent(getApplicationContext(),ActionAbout.class));
}

Related

How to move to a new fragment after clicking a button in a list item

How can I ensure that a button inside a list item is clickable, because I am trying to make the button clickable so that it can transition to a different fragment?
Like the listview and the list items inside it are part of a fragment and I want to ensure that clicking a specific button inside a list item will transition to the new fragment.
MainActivity Code:
It contains tabs(not all of which are implemented yet, but thats not an issue right now)
public class MainActivity extends FragmentActivity implements HomeFragment.OnFragmentInteractionListener {
private FragmentTabHost mTabHost;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//set up the tabs which hold different fragments, it will currently crash because of the null
mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
mTabHost.setup(this,getSupportFragmentManager(), R.id.realtabcontent);
mTabHost.addTab(mTabHost.newTabSpec("home").setIndicator("Home"), HomeFragment.class , null);
// mTabHost.addTab(mTabHost.newTabSpec("search").setIndicator("Search"),null/*fragment here*/,null);
// mTabHost.addTab(mTabHost.newTabSpec("post").setIndicator("Post"),null/*fragment here*/,null);
// mTabHost.addTab(mTabHost.newTabSpec("books").setIndicator("Books"),null/*fragment here*/,null);
// mTabHost.addTab(mTabHost.newTabSpec("me").setIndicator("Me"),null/*fragment here*/,null);
}
#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);
}
//For home fragment...parameter might change
#Override
public void onFragmentInteraction(String id) {
Button viewPostings = (Button) findViewById(R.id.view_postings);
viewPostings.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PostDetailFragment fragment = PostDetailFragment.newInstance();
getSupportFragmentManager().beginTransaction().replace(R.id.realtabcontent, fragment).addToBackStack(null).commit();
}
});
}
}
Im trying to launch the new activity from the implementation of onFragmentInteractionListener. The app loads the list view and its contents, but the individual buttons in it aren't clickable.
First off you need to add this line to make the items in the custom list item clickable:
android:descendantFocusability="blocksDescendants"
Add this property to the enclosing layout.
Secondly, you need to set the onClickListener in the getView method of the custom adapter that you have made for your custom ListView. For example, that would be something like this:
ImageButton deleteBtn = (ImageButton) view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// code here
}
});
Use some sort of ListAdapter such as an ArrayAdapter to populate your ListView. That way, you can use the adapter to handle the button clicks.
In your list fragment, use the onItemClick:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (null != mListener) {
// Notify the active callbacks interface (the activity, if the
// fragment is attached to one) that an item has been selected.
mListener.onFragmentInteraction(foodList.get(position));
}
}
Then in your parent activity, you will have something like this.
#Override
public void onFragmentInteraction(Food food) {
//going from ListFragment to DetailFragment
//call detail fragment here
FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment fragment = DetailFragment.newInstance(food);
ft.replace(R.id.container, fragment);
ft.addToBackStack( "tag" );
ft.commit();
}

Save selected option drawer activity for use in back button

I have a drawer activity and a method that calls several fragments, when I select an option shows me a listview with buttons. Clicking a button sends me to a new activity that has a back button. I want to return to the previous screen, return to the option you select in the drawer activity.
public class DrawerOpcionesActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer_menu);
....
drawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
mostrarFragment(position);
adapterOpciones.setPositionCheked(position);
}
});
if(savedInstanceState == null){
mostrarFragment(0);
}
...
}
private void mostrarFragment(int position){
Fragment fragment = null;
System.out.println("opcion: " + position);
switch (position) {
case 1:
fragment = new LineasTransporteFragment();
break;
....
}
In the other activity...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.xxxxx);
actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
... //new Intent.. I dont Know who call the save option from activity drawerOptions
return true;
default:
return super.onOptionsItemSelected(item);
}
}
I need to save the selected option, when I call a new Intent show me the selected option. I show the fragment of default position 0
You may use SharedPrefrence of android to save the state and access back the state. Please have a look for sharedPrefrence

error whilst passing values between activities

I have an activity which has an edit text which becomes visible when a button is clicked. I fill the edit text up and click another button. On clicking this button the edit text content must be sent to another activity.The first activity takes the edit text and queries a list of data from my Parse database and shows it in a ListView in the Second Activity.But whenever i click the first button(after entering the string) the app crashes.This is the first activity
public class MainActivity extends ActionBarActivity {
String name;
EditText search;
Button g;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpSpinners();
Parse.initialize(this, "AAh5US7zhbYyFBexsv07cjo34ZZiB7KNe9SuTv7e",
"eKUG1pYaV50hVyDC9d4qZc4qf1dCtOTqnX92eGJV");
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation();
search = (EditText) findViewById(R.id.search);
g = (Button) findViewById(R.id.Go);
}
#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);
}
public void byName(View v) {
search.setVisibility(View.VISIBLE);
search.requestFocus();
g.setVisibility(View.VISIBLE);
}
public void Go(View v) {
name = search.getText().toString();
final Intent i;
i = new Intent(MainActivity.this, ResterauntList1.class);
i.putExtra("restrauntName", name);
startActivity(i);
}
}
In the above byName is the onClick for making the EditText visible, and Go is the onClick for getting my EditText string and passing it to the next activity. The second activity is below
public class ResterauntList1 extends Activity {
String rValue;
ArrayAdapter<String> adapter;
ProgressDialog mProgressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_resteraunt_list1);
Bundle bdl = getIntent().getExtras();
rValue = bdl.getString("restrauntName");
setContentView(R.layout.activity_resteraunt_list);
populateList(rValue, "name");
}
private void populateList(final String Value, final String Key) {
ParseQueryAdapter.QueryFactory<ParseObject> factory = new ParseQueryAdapter.QueryFactory<ParseObject>() {
#Override
#SuppressWarnings({ "unchecked", "rawtypes" })
public ParseQuery create() {
ParseQuery query = new ParseQuery("resdb");
query.whereEqualTo(Key, Value);
return query;
}
};
ParseQueryAdapter<ParseObject> adapter = new ParseQueryAdapter<ParseObject>(
this, factory);
adapter.setTextKey("name");
adapter.addOnQueryLoadListener(new OnQueryLoadListener<ParseObject>() {
#Override
public void onLoading() {
mProgressDialog = new ProgressDialog(ResterauntList1.this);
mProgressDialog.setTitle("Searching for " + Value);
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
mProgressDialog.show();
}
#Override
public void onLoaded(List<ParseObject> objects, Exception e) {
mProgressDialog.dismiss();
}
});
final ListView listView = (ListView) findViewById(R.id.restListView1);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ParseObject object = (ParseObject) listView
.getItemAtPosition(position);
String Id = object.getObjectId();
Intent i = new Intent(getApplicationContext(),
SingleRestraunt.class);
i.putExtra("restId", Id);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.resteraunt_list1, 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);
}
}
The error as stated above occurs when I click the Go button.The error is
09-02 14:58:46.443: E/AndroidRuntime(3061): Process: com.example.gastronomaapp, PID: 3061
09-02 14:58:46.443: E/AndroidRuntime(3061): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.gastronomaapp/com.example.gastronomaapp.ResterauntList1}: java.lang.NullPointerException
Any idea where I am making a mistake? The funniest thing almost the same code has worked in another part of my app. absolutely clueless whats wrong.
Bundle bdl = getIntent().getExtras();
rValue = bdl.getString("restrauntName");
change to
rValue = getIntent().getStringExtra("restrauntName");
You put the string directly on the intent, not packaged in a bundle.

How can the back button in action bar act as the back button on device?

In Android if I start new Activity B from within activity A, Android will automatically save all the state of Activity A. So when I click back button on the device in Activity B, A will be restored to the state when I had started Activity B (for example: Spinners, ListView and Toggle Buttons all are in their previous positions).
BUT when I click the back button in action bar activity A starts fresh with no stored state.
Is there any way to make this back button similar to the device's back or I have to use SharedPreferences and store every thing myself?
(api 8 and above for my app)
In one of the fragments in my app I have a ListView which is one of the fragments that needs to be in the same state when coming back from the next page. I have added the code below.
If any other part is needed please tell me and I will add the code.
The main activity code:
private ProgressDialog progress;
/**
* The {#link android.support.v4.view.PagerAdapter} that will provide
* fragments for each of the sections. We use a {#link FragmentPagerAdapter}
* derivative, which will keep every loaded fragment in memory. If this
* becomes too memory intensive, it may be best to switch to a
* {#link android.support.v4.app.FragmentStatePagerAdapter}.
*/
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(Farsi.Convert(getString(R.string.app_name_farsi)));
setContentView(R.layout.activity_main);
final ActionBar actionBar = getSupportActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
// Create the adapter that will return a fragment for each of the three primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
// When swiping between different sections, select the corresponding tab. We can also use ActionBar.Tab#select() to do this if we have a reference to the Tab.
mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
});
// For each of the sections in the app, add a tab to the action bar.
for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
// Create a tab with text corresponding to the page title defined by the adapter. Also specify this Activity object, which implements the TabListener interface, as the callback (listener) for when this tab is selected.
actionBar.addTab(actionBar.newTab().setText(mSectionsPagerAdapter.getPageTitle(i)).setTabListener(this));
}
}
#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) {
Intent intent=new Intent(MainActivity.this, AboutActivity.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
// When the given tab is selected, switch to the corresponding page in the ViewPager.
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
#Override
public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
}
Here is the code to my List Fragment:
public class SearchResultListFragment extends Fragment{
Pagination pagination;
boolean loadingMore = false;
ListView list;
TextView text1;
TextView text2;
TextView text3;
TextView text4;
TextView text5;
Button Btngetdata;
private static String url = "https://www.....com/api/property/search";
private static int currentFirstVisibleItem;
public SearchResultArrayListAdaptor adapter ;
LinearLayout linlaHeaderProgress;
JSONArray jsonArray = null;
JSONParse fetchclass = null;
public SearchResultListFragment() {
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
linlaHeaderProgress = (LinearLayout) getActivity().findViewById(R.id.linlaHeaderProgress);
ArrayAdapter<PropertyObject> aa =(ArrayAdapter<PropertyObject>) list.getAdapter();
if (aa!= null){
aa.clear();
aa.notifyDataSetChanged();
}
list.setOnItemClickListener((OnItemClickListener) getActivity());
adapter = new SearchResultArrayListAdaptor(getActivity(), R.layout.list_view_items, new ArrayList<PropertyObject>());
list.setAdapter(adapter);
pagination = new Pagination(0,15);
fetchclass = new JSONParse(getActivity());
fetchclass.execute(url);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_search_result_list, container, false);
list=(ListView)rootView.findViewById(R.id.listViewSearchResult);
list.setOnScrollListener(
new OnScrollListener(){
private int currentVisibleItemCount;
private int currentTotalItemCount;
private int currentScrollState;
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted() {
if (currentFirstVisibleItem + currentVisibleItemCount >= currentTotalItemCount) {
if (this.currentVisibleItemCount > 0 && this.currentScrollState == SCROLL_STATE_IDLE) {
if(fetchclass!=null) {
pagination = new Pagination(this.currentTotalItemCount,15);
if(!(fetchclass.getStatus()== AsyncTask.Status.RUNNING)) {
fetchclass= new JSONParse(getActivity());
fetchclass.execute(url);
}
}
else {
fetchclass = new JSONParse(getActivity());
fetchclass.execute(url);
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
currentFirstVisibleItem = firstVisibleItem;
this.currentVisibleItemCount = visibleItemCount;
this.currentTotalItemCount = totalItemCount;
}
});
return rootView;
}
//*********************************** inner class
public class JSONParse extends AsyncTask<String, String, JSONObject> {
Context mContext;
int checkBoxRooms;
public JSONParse(Context context){
mContext = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
linlaHeaderProgress.setVisibility(View.VISIBLE);
}
#Override
protected JSONObject doInBackground(String... args) {
JSONObject json = null;
PropertyFilter searchFilter = SearchFilterManager.initializePropertyFilter(new PropertyFilter(), getArguments());
getActivity().setProgressBarIndeterminateVisibility(true);
JSONParserForSearch jParser = new JSONParserForSearch();
json = jParser.getJSONFromUrl(url, searchFilter, pagination);
return json;
}
#Override
protected void onPostExecute(JSONObject json) {
// SHOW THE SPINNER WHILE LOADING FEEDS
getActivity().setProgressBarIndeterminateVisibility(false);
PropertyObject propertyObject;
try {
jsonArray = json.getJSONArray("PropertyListings");
if (jsonArray == null || jsonArray.length()<1){
// list.setEmptyView(getActivity().findViewById(R.id.txtNoResult));
}
else {
for(int i = 0; i < jsonArray.length(); i++){
JSONObject c = jsonArray.getJSONObject(i);
propertyObject = new Gson().fromJson(c.toString(), new PropertyObject().getClass());
adapter.add(propertyObject);
adapter.notifyDataSetChanged();
}
}
// CHANGE THE LOADINGMORE STATUS TO PERMIT FETCHING MORE DATA
loadingMore = false;
// HIDE THE SPINNER AFTER LOADING FEEDS
linlaHeaderProgress.setVisibility(View.GONE);
}
catch (JSONException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
My layout XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
<ListView
android:id="#+id/listViewSearchResult"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_weight="2"
>
</ListView>
<LinearLayout
android:id="#+id/linlaHeaderProgress"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical"
android:visibility="gone"
>
My Adapter is ArrayAdapter.
I have implemented isEmpty and getCount too.
My Activity For List:
public class SearchResultListActivity extends ActionBarActivity implements OnItemClickListener{
static PropertyObject selectedPropertyObject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
Bundle bundle=new Bundle();
bundle.putInt("intentionOfOwner", intent.getIntExtra("intentionOfOwner",0));
SearchResultListFragment fragobj=new SearchResultListFragment();
fragobj.setArguments(bundle);
///back button
setContentView(R.layout.activity_search_result_list);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction().add(R.id.container, fragobj).commit();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View textView, int rowNumber, long arg3) {
Intent intent = new Intent(this, PropertyDetailActivity.class);
PropertyObject po = (PropertyObject) arg0.getAdapter().getItem((int)arg3);
intent.putExtra("listingID",po.getID());
startActivity(intent);
}
EDIT:
All right. I changed my API level from 8 to 11 to.
Also I added getActionBar().setDisplayHomeAsUpEnabled(true); to onCreate() of activity.
And changes the onOptionsItemSelected as follows.
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent=new Intent(PropertyDetailActivity.this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.up:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.homeAsUp:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
BUT none of the switch cases gets the chance to run when I click the back button in the action bar!

Android menu item list navigation

I need help please could someone help me with switch and case...
I have 3 item in action bar item1, item2, item3 and i have 3 activity item1Activity.java, item2Activity, item2Activity.. I want to call those activity from menu when its item selected..
public class MainActivity extends Activity {
/** An array of strings to populate dropdown list */
String[] actions = new String[] {
"Item1",
"Item2",
"Item3"
};
protected int position;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Create an array adapter to populate dropdownlist */
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_dropdown_item, actions);
/** Enabling dropdown list navigation for the action bar */
getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);
/** Defining Navigation listener */
ActionBar.OnNavigationListener navigationListener = new OnNavigationListener() {
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
switch (itemPosition) {
case 1:
Intent i = new Intent();
i.setClass(getApplicationContext(), Item1Activity.class);
startActivity(i);
return true;
case 2:
Intent i = new Intent();
i.setClass(getApplicationContext(), Item2Activity.class);
startActivity(i);
return true;
}
}
};
/** Setting dropdown items and item navigation listener for the actionbar */
getActionBar().setListNavigationCallbacks(adapter, navigationListener);
}
}
Use MainActivity.this instead of getApplicationContext()
Activity is child of Context

Categories

Resources