Android Action bar buttons wont show up with navigation drawer with fragmentactivity - java

i am trying to show some buttons in actionbar but they just dont show up
i have successfully implemented the navigation drawer and viewpager using fragments
the implementes for showing menu inflator and action bar buttons has also been done but they just wont show up
in menu/main.xml i have added app:showAsAction="always" but still it wont show up
here is the
detailactivity.java
package com.test.app;
import java.lang.reflect.Field;
import android.app.ActionBar;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.ActionBarDrawerToggle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
//import android.support.v7.app.ActionBar;
import com.Blog.gkgyan.parser.RSSFeed;
//public class DetailActivity extends FragmentActivity implements OnItemClickListener{
public class DetailActivity extends FragmentActivity implements OnItemClickListener{
RSSFeed feed;
int pos;
private DescAdapter adapter;
private ViewPager pager;
private DrawerLayout drawerLayout;
private ListView listView;
private String[] planets;
private ActionBarDrawerToggle drawerListener;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.detail);
//Drawer Layout
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerListener = new ActionBarDrawerToggle(this, drawerLayout,R.drawable.ic_drawer,R.string.drawer_open, R.string.drawer_close){
#Override
public void onDrawerClosed(View drawerView) {
// TODO Auto-generated method stub
//super.onDrawerClosed(drawerView);
Toast.makeText(DetailActivity.this, "Drawer closed", Toast.LENGTH_LONG).show();
}
#Override
public void onDrawerOpened(View drawerView) {
// TODO Auto-generated method stub
//super.onDrawerOpened(drawerView);
Toast.makeText(DetailActivity.this, "Drawer opened", Toast.LENGTH_LONG).show();
}
};
drawerLayout.setDrawerListener(drawerListener);
//getSupportActionBar().setHomeButtonEnabled(true);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);;
getActionBar().setDisplayHomeAsUpEnabled(true);
// try {
// ViewConfiguration config = ViewConfiguration.get(this);
// Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
// if (menuKeyField != null) {
// menuKeyField.setAccessible(true);
// menuKeyField.setBoolean(config, false);
// }
// } catch (Exception e) {
// e.printStackTrace();
// }
if ( Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
try {
ViewConfiguration config = ViewConfiguration.get(this);
Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
if(menuKeyField != null) {
menuKeyField.setAccessible(true);
menuKeyField.setBoolean(config, false);
}
} catch (Exception e) { e.printStackTrace(); }
}
listView = (ListView) findViewById(R.id.drawerlist);
planets = getResources().getStringArray(R.array.planets);
listView.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, planets ));
listView.setOnItemClickListener(this);
// Get the feed object and the position from the Intent
feed = (RSSFeed) getIntent().getExtras().get("feed");
pos = getIntent().getExtras().getInt("pos");
// Initialize the views
adapter = new DescAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.pager);
// Set Adapter to pager:
pager.setAdapter(adapter);
pager.setCurrentItem(pos);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
// TODO Auto-generated method stub
super.onConfigurationChanged(newConfig);
drawerListener.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.main, menu);
return true;
//return super.onCreateOptionsMenu(menu);
}
//#Override
//public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
if (drawerListener.onOptionsItemSelected(item)) {
return true;
}
Intent i = null;
switch (item.getItemId()) {
case R.id.action_rate:
String webpage = "http://developer.android.com/index.html";
i = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(i);
//return true;
break;
case R.id.action_share:
i = new Intent();
i.setAction(Intent.ACTION_SEND);
i.putExtra(Intent.EXTRA_TEXT, "Hello from Hansel and Petal!");
i.setType("text/plain");
startActivity(i);
//return true;
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onPostCreate(savedInstanceState);
drawerListener.syncState();
}
public class DescAdapter extends FragmentStatePagerAdapter {
public DescAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return feed.getItemCount();
}
#Override
public Fragment getItem(int position) {
DetailFragment frag = new DetailFragment();
Bundle bundle = new Bundle();
bundle.putSerializable("feed", feed);
bundle.putInt("pos", position);
frag.setArguments(bundle);
return frag;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
if (position == 0) {
Intent intent = new Intent(this, GkcategoryListActivity.class);
startActivity(intent);
}
else if (position == 1) {
Intent intent = new Intent(this, GkcategoryListActivity.class);
startActivity(intent);
}
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
}
`
and 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="com.Blog.gkgyan.MainActivity" >
<item
android:id="#+id/action_settings"
android:orderInCategory="100"
android:title="#string/action_settings"
app:showAsAction="never"/>
<item
android:id="#+id/action_share"
android:icon="#drawable/ic_action_share"
android:orderInCategory="101"
android:title="#string/action_share"
app:showAsAction="always" />
<item
android:id="#+id/action_rate"
android:icon="#drawable/ic_action_important"
android:orderInCategory="101"
android:title="#string/action_rate"
app:showAsAction="always"/>
</menu>
i wan to show the action_share and Action_rate butons in action bar on detailactivity.java tried every thing nothing works on this page
however it does work perfectly fine in main activity.java
here is the code
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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) {
// TODO Auto-generated method stub
Intent intent = null;
switch (item.getItemId()) {
case R.id.action_rate:
String webpage = "http://developer.android.com/index.html";
intent = new Intent(Intent.ACTION_VIEW, Uri.parse(webpage));
startActivity(intent);
break;
case R.id.action_share:
intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.putExtra(Intent.EXTRA_TEXT, "Hello from Hansel and Petal!");
intent.setType("text/plain");
startActivity(intent);
break;
default:
break;
}
return super.onOptionsItemSelected(item);
}
public void latestActivity(View v){
//Intent intent = new Intent(this, SplashActivity.class);
Intent intent = new Intent(this, GkcategoryListActivity.class);
startActivity(intent);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
}
}
is it a issue with fragment activity or navigation drawer any help would be great please mention where is should make changes in my code

Related

Android Intent doesnt work

so I have these code
main.java
package com.example.kamusinggris_indonesiaidiom;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class Main extends Activity {
private TextView teks;
private ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
teks = (TextView) findViewById(R.id.text);
list = (ListView) findViewById(R.id.list);
}
protected void onNewIntent(Intent intent) {
handleIntent(getIntent());
}
private void handleIntent(Intent intent) {
// TODO Auto-generated method stub
handleIntent(intent);
if (Intent.ACTION_VIEW.equals(intent.getAction())) {
Intent wordIntent = new Intent(this, Definisi.class);
wordIntent.setData(intent.getData());
startActivity(wordIntent);
} else if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
showResults(query);
}
}
private void showResults(String query) {
// TODO Auto-generated method stub
Cursor cursor = managedQuery(Provider.CONTENT_URI, null, null,
new String[] {query}, null);
if (cursor == null) {
// There are no results
teks.setText(getString(R.string.no_results, new Object[] {query}));
} else {
// Display the number of results
int count = cursor.getCount();
String countString = getResources().getQuantityString(R.plurals.search_results,
count, new Object[] {count, query});
teks.setText(countString);
// Specify the columns we want to display in the result
String[] from = new String[] { Database.KATA,
Database.DEFINISI };
// Specify the corresponding layout elements where we want the columns to go
int[] to = new int[] { R.id.kata,
R.id.definisi };
// Create a simple cursor adapter for the definitions and apply them to the ListView
SimpleCursorAdapter words = new SimpleCursorAdapter(this,
R.layout.hasil_pencarian, cursor, from, to);
list.setAdapter(words);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View tmp,
int posisi, long id) {
// TODO Auto-generated method stub
Intent definisi = new Intent(getApplicationContext(), Definisi.class);
Uri data = Uri.withAppendedPath(Provider.CONTENT_URI,
String.valueOf(id));
definisi.setData(data);
startActivity(definisi);
}
});
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()) );
searchView.setIconifiedByDefault(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
onSearchRequested();
return true;
default:
return false;
}
}
}
definisi.java
package com.example.kamusinggris_indonesiaidiom;
import android.app.ActionBar;
import android.app.Activity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.SearchView;
import android.widget.TextView;
public class Definisi extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definisi);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
}
Uri uri = getIntent().getData();
Cursor kursor = managedQuery(uri, null, null, null, null);
if (kursor == null) {
finish();
} else {
kursor.moveToFirst();
TextView kata = (TextView) findViewById(R.id.kata);
TextView definisi= (TextView) findViewById(R.id.definisi);
int wIndex = kursor.getColumnIndexOrThrow(Database.KATA);
int dIndex = kursor.getColumnIndexOrThrow(Database.DEFINISI);
kata.setText(kursor.getString(wIndex));
definisi.setText(kursor.getString(dIndex));
} }
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.search:
onSearchRequested();
return true;
case android.R.id.home:
Intent a = new Intent(this, Main.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);
return true;
default:
return false;
}
}
}
its a dictionary, so when a search suggestion on a listview is clicked, it supposed to open the definisi.java and display the definition. But what I got here is when I clicked the search suggestion it displayed the main.java (its just go back to the previous activity). what's wrong on the intent part? please help me
Use passed intent variable in onNewIntent
protected void onNewIntent(Intent intent) {
handleIntent(intent);
}
You should also remove call to handleIntent from within handleIntent method

which oncreate (bundle) will call in activity

I have created a activity(MainActivity.java) extends to Activity.java
and again I create the another activity(prodicts.java) now here I extends this activity(products.java) to MainActivity.java
So my question is that which onCreate(bundle) will call in my products.java class its super class onCreate(bundle) or its own onCreate(bundle) and my code is below:
MainActivity.java
import java.util.Locale;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.SearchManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
protected DrawerLayout mDrawerLayout;
private ListView mDrawerList;
public ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mPlanetTitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawer);
mTitle = mDrawerTitle = getTitle();
mPlanetTitles = getResources().getStringArray(R.array.List_Content);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mPlanetTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
//displayView(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
case R.id.action_websearch:
// create intent to perform web search for this planet
Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// catch event that there's no activity to handle intent
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
} else {
Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
displayView(position);
}
}
#SuppressWarnings("unused")
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0: Intent product = new Intent(MainActivity.this,Products.class);
startActivity(product);
break;
case 1: Intent notes = new Intent (MainActivity.this,Notes.class);
startActivity(notes);
break;
case 2: Intent Contacts = new Intent (MainActivity.this,Contacts.class);
startActivity(Contacts);
break;
case 3:
Intent viewPdf = new Intent (MainActivity.this,pdfView.class);
startActivity(viewPdf);
break;
case 4:
Intent search = new Intent (MainActivity.this,search.class);
startActivity(search);
break;
/*case 5:
fragment = new WhatsHotFragment();
break;*/
default:
break;
}
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
//setTitle(mDrawerList[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#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);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
/**
* Fragment that appears in the "content_frame", shows a planet
*/
public static class PlanetFragment extends Fragment {
public static final String ARG_PLANET_NUMBER = "planet_number";
public PlanetFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
int i = getArguments().getInt(ARG_PLANET_NUMBER);
String planet = getResources().getStringArray(R.array.List_Content)[i];
int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
"drawable", getActivity().getPackageName());
((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
getActivity().setTitle(planet);
return rootView;
}
}
}
and products.java
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.Toast;
public class Products extends MainActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
LayoutInflater inflater = (LayoutInflater) this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View contentView = inflater.inflate(R.layout.products, null, false);
mDrawerLayout.addView(contentView, 0);
GridView gridview = (GridView)findViewById(R.id.productgridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Toast.makeText(Products.this, " "+position, Toast.LENGTH_SHORT).show();
}
});
}
}
So please tell what will happen in this Activity , I am confused about it.
when i will call the products.java class which onCreate(bundle) it will call MainActivity.java's onCreate(bundle) or products.java's onCreate(bundle).
onCreate() of Product Class will be called, then onCreate() of MainActivity class and finally onCreate() of Activity class will be called.

OnLongClickListener - not getting fired + android

I have this OnLongClickListener which is not getting fired. I think I have setup everything correctly and it has worked with a contextmenu before but right now it's not firing and the log is not even giving me any error.
I really hope you can give me any ideas. It is probably a silly mistake somewhere.
package fragments;
import interfaces.AsyncTaskCompleteListener;
import java.util.List;
import com.example.slidingmenu.R;
import dialog.EditDialog;
import services.GetRequest;
import model.Post;
import adapter.PostAdapter;
import android.os.Bundle;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.util.Log;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;
public class HomeFragment extends Fragment implements AsyncTaskCompleteListener, View.OnLongClickListener {
private ListView mainListView;
private GetRequest service;
private ProgressDialog dialog;
private ActionMode mActionMode;
public HomeFragment() {}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedIntanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
mainListView = (ListView) rootView.findViewById(R.id.mainListView);
mainListView.setOnLongClickListener(this);
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Please wait...");
service = new GetRequest(this);
service.execute();
dialog.show();
registerForContextMenu(mainListView);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
setHasOptionsMenu(true);
super.onCreate(savedInstanceState);
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch(item.getItemId()) {
case R.id.edit:
Log.d("edit", "pressed");
FragmentManager fragmentManager = getFragmentManager();
EditDialog editDialog = new EditDialog();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.add(android.R.id.content, editDialog).addToBackStack(null).commit();
mode.finish();
return true;
default:
return false;
}
}
};
#Override
public boolean onLongClick(View v) {
Toast.makeText(getActivity(), "PRESSED", Toast.LENGTH_SHORT).show();
Log.d("hey", "pressed");
if(mActionMode != null) {
return false;
}
mActionMode = getActivity().startActionMode(mActionModeCallback);
mainListView.setSelected(true);
return true;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
Toast.makeText(getActivity(), "Refresh!", Toast.LENGTH_SHORT).show();
dialog = new ProgressDialog(getActivity());
dialog.setMessage("Please wait while refreshing...");
dialog.show();
service = new GetRequest(this);
service.execute();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onTaskComplete(List<Post> posts) {
PostAdapter adapter = new PostAdapter(getActivity(), R.layout.listview_item_row, posts);
LayoutInflater inflater = (LayoutInflater)getActivity().
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View header = (View)inflater.inflate(R.layout.listview_header_row, null);
if(mainListView.getHeaderViewsCount() == 0) {
mainListView.addHeaderView(header);
}
mainListView.setAdapter(adapter);
if(dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
public void onTaskComplete(String result) {
// TODO Auto-generated method stub
}
}
Here is the xml file where I have my ListView:
<?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" >
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/mainListView"
android:longClickable="true"
android:clickable="true"
></ListView>
</LinearLayout>
You are attaching a listener to the entire view instead of each row. I'm not sure why nothing is being fired, but those touch events are probably being intercepted by other views.
Instead of ListView.setOnLongClickListener(), you should use ListView.setOnItemLongClickListener().
Here is the link for the Android Docs for this method.
Since you are registerForContextMenu for your listview already. setOnLongClickListener is not longer needed. What you needs is onCreateContextMenu method and onContextItemSelected.
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo){
// create menu item here
}
#Override
public boolean onContextItemSelected(MenuItem item){
// do your long click listener here
}

Android app crashes, due to count down timer?

I have made an app recently and I added a count down timer one day and made a few changes here and there and now when I run the app on my (actual) Galaxy Note 3 it crashes as soon as I hit the Play button below are my LevelOne.java file and my MainActivity.Java file. By the way the logcat shows nothing as if it doesn't realize it crashed.
LevelOne.java
package com.parker.orangedot;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
public class LevelOne extends ActionBarActivity {
Button myButton;
LevelOne context;
CountDownTimer timer = new CountDownTimer(1500, 1500)
{
#Override
public void onFinish() {
Intent intent = new Intent(context, Scores.class);
startActivity(intent);
}
#Override
public void onTick(long arg0) {
// TODO Auto-generated method stub
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_level_one);
//ass soon as this activity is created, I start my timer.
timer.start();
myButton = (Button) findViewById(R.id.button2);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
timer.cancel();
}});
}
#Override
public void onBackPressed() {
}
public void next(View view) {
// Do something in response to button
Intent intent = new Intent(this, LevelTwo.class);
startActivity(intent);
}
public void openScores(View view) {
// Do something in response to button
Intent intent = new Intent(this, Scores.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.level_one, 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_level_one,
container, false);
return rootView;
}
}
}
MainActivity.java
package com.parker.orangedot;
import android.content.Intent;
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;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
public void openScores(View view) {
// Do something in response to button
Intent intent = new Intent(this, Scores.class);
startActivity(intent);
}
public void play(View view) {
// Do something in response to button
Intent intent = new Intent(this, LevelOne.class);
startActivity(intent);
}
#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;
}
}
}
UPDATE:
When using the emulater for the Galaxy Nexus, pressing "play" does absolutely nothing.

Button and menus stop working after orientation change

I have an Android app which uses tabs and fragments for navigation. The app works fine when launched, but after I change the orientation the menu items and the widgets in the fragments stop working. The app works if I put
android:configChanges="orientation|screenSize"
in the manifest, but in the Android documentation it says that this should be a last resort, so I'm wondering if there is a better solution. Here's the code for the host activity and one of the fragments.
package com.mynews;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.view.Menu;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
//stopService(new Intent(this, FindArticlesService.class));
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab tab = actionBar.newTab()
.setText("Articles")
.setTabListener(new TabListener<Articles>(this, "articles", Articles.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText("Websites")
.setTabListener(new TabListener<UserSites>(this, "websites", UserSites.class));
actionBar.addTab(tab);
tab = actionBar.newTab()
.setText("Add a website")
.setTabListener(new TabListener<AddSites>(this, "add a site", AddSites.class));
actionBar.addTab(tab);
}
#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
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
////Intent intent = new Intent(this, FindArticlesService.class);
//this.startService(intent);
}
public static class TabListener<T extends Fragment> implements ActionBar.TabListener {
Fragment fragment;
final Activity activity;
final String tag;
final Class<T> mClass;
public TabListener(Activity a, String s, Class<T> c){
activity = a;
tag = s;
mClass = c;
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if(fragment == null){
fragment = Fragment.instantiate(activity, mClass.getName());
ft.add(android.R.id.content, fragment, tag);
}else{
ft.attach(fragment);
}
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
if(fragment != null){
ft.detach(fragment);
}
activity.closeContextMenu();
}
}
}
My Fragment Class
package com.mynews;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AddSites extends Fragment {
public AddSites(){}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_add_sites);
// Show the Up button in the action bar.
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
Button button = (Button) getActivity().findViewById(R.id.add);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
UserSitesFunc usf = new UserSitesFunc(); //create a new UserSitesFunc to hold
try{ //the list of sites
FileInputStream fis = getActivity().openFileInput("MySites.ser");//check if there's a file
ObjectInputStream ois = new ObjectInputStream(fis);//with a USF object
usf = (UserSitesFunc) ois.readObject(); //if there is, deserialize it and use it
ois.close();//instead of a brand new object
}catch(IOException e){ //catch various exceptions
e.printStackTrace();
}catch(Exception ep){
ep.printStackTrace();
}finally{
try{ //do this with either the new object or the deserialised one
EditText website = (EditText) getActivity().findViewById(R.id.editText1);//get the input
EditText keywords = (EditText) getActivity().findViewById(R.id.editText2);//from the user
String web = website.getText().toString(); //store it in strings
String key = keywords.getText().toString();
String[] kwords = key.split(", ");
ArrayList<String> newKeywords = new ArrayList<String>();
for(String s:kwords){
newKeywords.add(s);
}
Sites s = new Sites(web, newKeywords);//create a new site from the input
if(usf.siteList.contains(s)){
showContainedDialog();
return;
}
usf.addSite(s);//add it to the user's list of sites
FileOutputStream fs = getActivity().openFileOutput("MySites.ser", Context.MODE_PRIVATE);//save it
ObjectOutputStream oos = new ObjectOutputStream(fs);
oos.writeObject(usf);
oos.close();
Toast.makeText(getActivity(), web + " added to Tracked Websites", Toast.LENGTH_LONG).show();
website.setText("");
keywords.setText("");
}catch(MalformedURLException mue){
showDialog();
}catch(Exception ex){
ex.printStackTrace();
}
}
}
});
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.activity_add_sites, container, false);
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
menu.clear();
inflater.inflate(R.menu.add_sites, menu);
super.onCreateOptionsMenu(menu, inflater);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
return true;
}
return super.onOptionsItemSelected(item);
}
public static class NotAWebsiteDialog extends DialogFragment {
public static NotAWebsiteDialog newInstance(){
NotAWebsiteDialog notAWebsite = new NotAWebsiteDialog();
Bundle args = new Bundle();
notAWebsite.setArguments(args);
return notAWebsite;
}
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
// TODO Auto-generated method stub
return new AlertDialog.Builder(getActivity())
.setMessage("Please enter a vaild web address")
.create();
}
}
public void showDialog(){
DialogFragment dialog = NotAWebsiteDialog.newInstance();
dialog.show(getFragmentManager(), "Not A Website");
}
public static class AlreadyContainsWebsiteDialog extends DialogFragment {
public static AlreadyContainsWebsiteDialog newInstance(){
AlreadyContainsWebsiteDialog containsAWebsite = new AlreadyContainsWebsiteDialog();
Bundle args = new Bundle();
containsAWebsite.setArguments(args);
return containsAWebsite;
}
#Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
// TODO Auto-generated method stub
return new AlertDialog.Builder(getActivity())
.setMessage("This website is already being tracked")
.create();
}
}
public void showContainedDialog(){
DialogFragment dialog = AlreadyContainsWebsiteDialog.newInstance();
dialog.show(getFragmentManager(), "Contains this Website");
}
}
Kudos for not taking the easy way... keep up your programming efforts!
Refer to my answer here regarding the use of Menus and their host Fragments.

Categories