onMenuItemSelected never executes - android

When I click on a menu item I am presented with the following message in DDMS:
Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub$Proxy#43882778
Here is most of the code from the Main class where the onMenuClick is being ignored.
public class Main extends TabActivity {
public static final int ACTIVITY_CREATE = 0;
private static final int ADD_ID = Menu.FIRST;
private Long listId;
private DbHelper mDbHelper;
private Cursor mCursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Set the list id
Bundle extras = getIntent().getExtras();
if (extras != null) {
listId = extras.getLong("listId");
}
// Open the database
mDbHelper = new DbHelper(this);
mDbHelper.open();
// Setup the tabs
createTabs();
}
public void createTabs() {
mCursor = mDbHelper.fetchAllCategories(listId);
startManagingCursor(mCursor);
for (int i = 0; i [less than symbol] mCursor.getCount(); i++)
{
createTab(
mCursor.getLong(mCursor.getColumnIndexOrThrow("_id")),
mCursor.getString(mCursor.getColumnIndexOrThrow("category")));
}
}
public void createTab(Long categoryId, String category) {
TabHost tabHost = getTabHost();
TabHost.TabSpec spec;
Intent intent;
intent = new Intent();
intent.putExtra("Test", category);
intent.setClass(this, Categories.class);
spec = tabHost.newTabSpec(category);
spec.setContent(intent);
spec.setIndicator(category);
tabHost.addTab(spec);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, ADD_ID, 0, R.string.menu_addCategory).setIcon(R.drawable.add_grey);
return true;
}
#Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case ADD_ID:
addCategory();
return true;
}
return super.onMenuItemSelected(featureId, item);
}
public void addCategory() {
Intent intent = new Intent();
intent.setClass(this, CategoryEdit.class);
startActivityForResult(intent, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
switch (requestCode) {
case ACTIVITY_CREATE:
if (resultCode == RESULT_OK) {
Bundle createExtras = intent.getExtras();
mDbHelper.addCategory(createExtras.getString("category"));
}
}
}
}
Originally my CategoryEdit.class wasn't listed in the AndroidManifest.xml file. I have added that to the manifest and still receive the same error.

use ::
public boolean onOptionsItemSelected(MenuItem item) {
instead of::
public boolean onMenuItemSelected(int featureId, MenuItem item) {

Try changing it to intent.setClass(TabActivity.this, CategoryEdit.class);
If that doesn't work I'm gonna need some more output from Logcat, you can one line and it is really helping much.

Related

How to open link in a fragment with webview when a specific item is clicked from listview fragment

I have an Android app with a navigation drawer with menu items.This menu contains entry to multiple fragments. One of the fragments has a listview in it with names of websites. My aim is that whenever a name of website is clicked from that list the link associated with the listview item saved in stringarray in strings.xml file is opened in new fragment with webview which opens the site.
So far I have implemented this code for the fragment with listview
class AtlasListFragment extends android.support.v4.app.ListFragment implements AdapterView.OnItemClickListener {
#Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.atlas_list_fragment, container, false);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
ArrayAdapter adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.tut_titles, android.R.layout.simple_list_item_1);
setListAdapter(adapter);
getListView().setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Toast.makeText(getActivity(), "Item: " + position, Toast.LENGTH_SHORT).show();
}}
And the code which launches the fragment from navigation drawer is below
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
android.support.v4.app.Fragment fragment = null;
if (id == R.id.home) {
fragment = frag;
else if (id == R.id.settings) {
fragment=new Settings();
} else if (id == R.id.about_us) {
fragment=new AboutUc();
}
else if(id == R.id.atlas){
fragment = new AtlasListFragment();
}
else{
}
if (fragment!=null)
{
FragmentManager fragmentManager=getSupportFragmentManager();
FragmentTransaction ft=fragmentManager.beginTransaction();
ft.replace(R.id.fragmentview,fragment);
ft.commit();
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
By this mehod you can open a webview in where you want use WebView layout and use this method in your activity
public void openWebView(String url){
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
}
Hope it works for you
First of all you will need broadcast so you can send your clicked
URL from adapter to your fragment, and in your main fragment when you
receive the url you can use intent or webview
1- CREATE BroadcastHelper CLASS :
public class BroadcastHelper {
public static final String BROADCAST_EXTRA_METHOD_NAME = "INPUT_METHOD_CHANGED";
public static final String ACTION_NAME = "hassan.hossam";
private static final String UPDATE_LOCATION_METHOD = "updateLocation";
public static void sendInform(Context context, String method) {
Intent intent = new Intent();
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void sendInform(Context context, String method, Intent intent) {
intent.setAction(ACTION_NAME);
intent.putExtra(BROADCAST_EXTRA_METHOD_NAME, method);
try {
context.sendBroadcast(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
}
2- Send intent from your adapter
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent url = new Intent("url");
url ("url_adapter",item.get(position).getURL());
BroadcastHelper.sendInform(context,"url",url);
}
});
3- in your fragment this use :
Receiver receiver;
boolean isReciverRegistered = false;
#Override
public void onResume() {
super.onResume();
if (receiver == null) {
receiver = new Receiver();
IntentFilter filter = new IntentFilter(BroadcastHelper.ACTION_NAME);
getActivity().registerReceiver(receiver, filter);
isReciverRegistered = true;
}
}
#Override
public void onDestroy() {
if (isReciverRegistered) {
if (receiver != null)
getActivity().unregisterReceiver(receiver);
}
super.onDestroy();
}
private class Receiver extends BroadcastReceiver {
#Override
public void onReceive(Context arg0, Intent arg1) {
Log.v("r", "receive " + arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME));
String methodName = arg1.getStringExtra(BroadcastHelper.BROADCAST_EXTRA_METHOD_NAME);
if (methodName != null && methodName.length() > 0) {
Log.v("receive", methodName);
switch (methodName) {
case "url":
String url_adapter = arg1.getStringExtra("url_adapter");
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url_adapter));
startActivity(i);
break;
default:
break;
}
}
}
}
i hope this helped

Google glass closing second level activity closes app

I have two activities, Main Activity and List Activity. I always want a menu displayed on Main Activity as there's no where else to go.
Main Activity has this code:
#Override
public void onOptionsMenuClosed(Menu menu) {
// Nothing else to do, closing the activity.
finish();
}
#Override
public void onResume() {
super.onResume();
openOptionsMenu();
}
When I close List Activity, my entire app closes - and its due to the onOptionsMenuClosed method in my MainActivity, really confused as to why this is the case, when ListActivity is closed I just want to go back to the menu.
I had the same problem and solved it like this:
public class StartActivity extends Activity{
private boolean cancel = true;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
openOptionsMenu();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.startmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.Item1){
cancel = false;
Intent intent = new Intent(this, ActivityA.class);
startActivityForResult(intent, 0);
return true;
}
else if(id == R.id.Item2){
cancel = false;
Intent intent = new Intent(this, ActivityB.class);
startActivityForResult(intent, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == RESULT_CANCELED) {
openOptionsMenu();
cancel = true;
}
}
}
#Override
public void onOptionsMenuClosed(Menu menu)
{
super.onOptionsMenuClosed(menu);
if(cancel){
finish();
}
}
}

Removing item from list on other activity

How can I remove a item from a ListActivity from a button on another Activity, the thing is,
I have this ListActivity:
public class ListaEventos extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onRestart();
republicar();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.lista_eventos, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.criar_evento:
Intent criar = new Intent(this, CriarEvento.class);
startActivity(criar);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void republicar() {
List<DadosEvento> eventos = MySingleton.getInstance().getEventos();
setListAdapter(new ArrayAdapter<DadosEvento>(this, android.R.layout.simple_list_item_1, eventos));
}
#Override
public void onListItemClick(ListView listView, View view, int position, long id) {
DadosEvento clickNumber = MySingleton.getInstance().getEventos().get(position);
Intent intent = new Intent(this, ExibirEvento.class);
Bundle exibirEvento = new Bundle();
exibirEvento.putString("exibirNome", clickNumber.getNome());
exibirEvento.putString("exibirData", clickNumber.getData());
exibirEvento.putString("exibirEnd", clickNumber.getEndereco());
exibirEvento.putString("exibirTel", clickNumber.getTel());
intent.putExtras(exibirEvento);
startActivity(intent);
}
}
Other Activity:
public class ExibirEvento extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_exibir_evento);
Intent intent = getIntent();
Bundle exibirEvento = intent.getExtras();
String exibirNome = exibirEvento.getString("exibirNome");
String exibirData = exibirEvento.getString("exibirData");
String exibirEnd = exibirEvento.getString("exibirEnd");
String exibirTel = exibirEvento.getString("exibirTel");
TextView exibir_nome = (TextView) findViewById(R.id.exibirevento_edittext_nome);
exibir_nome.setText(exibirNome);
TextView exibir_data = (TextView) findViewById(R.id.exibirevento_edittext_data);
exibir_data.setText(exibirData);
TextView exibir_end = (TextView) findViewById(R.id.exibirevento_edittext_end);
exibir_end.setText(exibirEnd);
TextView exibir_tel = (TextView) findViewById(R.id.exibirevento_edittext_tel);
exibir_tel.setText(exibirTel);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.exibir_evento, menu);
return true;
}
public void sairExibicao(View v) {
finish();
}
}
Now, on the ExibirEvento is where it shows me the infos about the Party, and there I need a button that removes that item from the List.
Well there are several scenarios that you can follow.
Use startActivityForResult instead of startActivity and then override the onActivityResult method and catch a proper requestCode and result (e. g. RESULT_OK) and delete current item and notifyDataChanged the adapter
Use singelton class, create newInstance, set values, and then refere to it from ExibirEvento
Use the database, and take advantage of ContentProvider and Loader, and pass only the ID of the entry to ExibirEvento
I think that the 3 option is the best way to go for.

getIntent is not working inside MainActivity. Getting weird behaviour

I have one MainActivity and I have defined below code in onCreate() method. The intention is, when MainActivity gets extra String "EXIT" then show Toast message:
Intent current = getIntent();
if (current !=null && current.getStringExtra("EXIT") != null) {
Toast.makeText(this, "exiting", Toast.LENGTH_LONG).show();
}
This MainActivity starts another activity "DayOne" on some button press like:
public void processGo(View v){
Intent i = new Intent(MainActivity.this,DayOne.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
MainActivity.this.startActivity(i);
}
Now I am returning back from "DayOne" to MainActivity after putting extra string "EXIT". This I am doing inside onOptionsItemSelected(MenuItem item) method:
public boolean onOptionsItemSelected(MenuItem item){
if(item.getTitle().equals("Exit")){
Intent i = new Intent(DayOne.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("EXIT", "EXIT");
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
The issue is, when MainActivity is getting called from DayOne with extra string "EXIT"; I am not seeing the Toast message defined in MainActivity. What is missing or wrong here?
Appreciate any help.
Thanks all for your comments and helps.
I have figured out the issue here. It was because the manifest file had entry an entry android:launchMode="singleInstance" for Both the activities (MainActivity and DayOne Activity)..
Removing it from there, it worked fine.
First check your null then get the Intent String, can you just make your code look like below within in onCreate of MainActivity#
Bundle extra= getIntent().getExtras();
if(extra!=null){
String _StrExit=extra.getString("EXIT");
if(_StrExit.equalsIgnoreCase("EXIT")){
Toast.makeText(this, "exiting", Toast.LENGTH_LONG).show();
}
}
Update
Make change while calling Intent from menuitem
public boolean onOptionsItemSelected(MenuItem item){
if(item.getTitle().equals("Exit")){
Intent i = new Intent(DayOne.this,MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
String _Str="EXIT";
i.putExtra("EXIT", _Str);
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
Its working for me.
MainActivity:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent current = getIntent();
if (current != null && current.getStringExtra("EXIT") != null) {
Toast.makeText(this, "exiting", Toast.LENGTH_LONG).show();
}
}
public void processGo(View view) {
Intent i = new Intent(MainActivity.this, OneDayActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
OneDayActivity:
public class OneDayActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_day_one);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.day_one, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getTitle().equals("Exit")) {
Intent i = new Intent(this, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.putExtra("EXIT", "EXIT");
startActivity(i);
finish();
}
return super.onOptionsItemSelected(item);
}
}
dont clear the stack instead of if you want to do some task when you come back to your main activity (using "EXIT" string) you can achieve that using onActivityResult also.:
public void processGo(View v){
Intent i = new Intent(MainActivity.this,DayOne.class);
MainActivity.this.startActivity(i,10); // 10 is the id to handle
}
#Override
public void onActivityResult( int requestCode, int resultCode, Intent data )
{
super.onActivityResult( requestCode, resultCode, data );
switch ( requestCode )
{
case ( 10 ): // id that we pass on start activity
{
if ( resultCode == Activity.RESULT_OK )
{
Toast.makeText(this, "exiting"+data.getStringExtra( "EXIT", "" ), Toast.LENGTH_LONG).show();
}
}
break;
}
}
On finish
public boolean onOptionsItemSelected(MenuItem item){
if(item.getTitle().equals("Exit")){
Intent resultIntent = new Intent();
resultIntent.putExtra( "EXIT", "EXIT" );
setResult( Activity.RESULT_OK, resultIntent );
finish();
}
return super.onOptionsItemSelected(item);
}
on finish it will go back to Main Activity and call onActivityResult automatically where you can do your task.
Sorry for the typo hope it will help.

Android Tabs with ListActivity BackButton

I have 3 Tabs
Tab1,Tab2,Tab3
public Class TabLayout extends TabActivity {
Tab1,Tab2,Tab3
}
Each Tab Contains one ListActivity
that means
Tab1>>>Tab1ListActivity(List with Image and Text)
Tab2>>>Tab2ListActivity(List with Image and Text)
Tab3>>>Tab3ListActivity(List with Image and Text)
and if i click on any listitem from(Tab1ListActivity,Tab2ListActivity etc.......)
I'm forwarding to one More Activity(Tab1ListItemActivity,Tab2ListItemActivity etc......)
But My Actual Requirement is if suppose I'm clicking backbutton from Tab2ListItemActivity ,then I
Should be able to forward to Tab2ListActivity
But,if i write my code like this
public class Tab2ListItemActivity extends Activity
{
//on Back Button Pressed
Intent intent=new Intent(Tab2ListItemActivity.this,TabLayout.class);
startActivity(intent);
Tab2ListItemActivity.this.finish();
}
when i execute above code I'm able to forward to my TabLayout(Tab1ListActivity) but not to Tab2ListActivity?,Beacuse
Tab2ListItemActivity related to Tab2ListActivity
Could any one help?
Why not leave the default behaviour (do not override onBackPressed)? It will restore to previous Activity.
Solution 1:
Do not finish the TabLayout Activity. And Leave the default implementation of back button in Tab2ListItemActivity activity.
Solution 2 (the hard, the force way):
Add the intent extra on what tab it should open.
Intent intent = new Intent(Tab2ListItemActivity.this, TabLayout.class);
intent.putExtra(TabLayout.EXTRA_TAB_TO_OPEN, 1);
startActivity(intent);
Tab2ListItemActivity.this.finish();
in TabLayout Activity
#Override
protected void onPostCreate(Bundle state) {
super.onPostCreate(state);
handleTab(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
handleTab(intent);
}
private void handleTab(Intent intent) {
// init tabs
final int tab = intent.getIntExtra(EXTRA_TAB_TO_OPEN, -1);
if (tab != -1) {
getTabHost().setCurrentTab(tab);
}
}
Why are you trying to override the Back button ? I mean, just let the default behaviour take place and then pressing the back button would take you to the previous activity.
If you really want to do it your way, then you would need to set the tab id before launching the TabLayout activity and inside the onCreate() of TabLayout you would need to check the tab id and launch the corresponding ListActivity. The tab id is 1 by default and that is why it is taking you to the Tab1ListActivity always.
I am getting same issue but i solve using this solution.
TabSample.class
public class TabSample extends TabActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TabHost tabHost = getTabHost();
tabHost.addTab(tabHost.newTabSpec("tab1")
.setIndicator("OPT")
.setContent(new Intent(this, TabGroup1Activity.class)));
tabHost.addTab(tabHost.newTabSpec("tab2")
.setIndicator("EDIT")
.setContent(new Intent(this, TabGroup2Activity.class)));
tabHost.setCurrentTab(1);
}
}
TabGroup1Activity.class
public class TabGroup1Activity extends TabGroupActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
startChildActivity("OptionsActivity", new Intent(this,OptionsActivity.class));
}
}
OptionsActivity.class
public class OptionsActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.optionspage);
Button back = (Button) findViewById(R.id.BackButton1);
Button next = (Button) findViewById(R.id.NextButton1);
OnTouchListener backListener = new OnTouchListener() {
public boolean onTouch (View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_UP){
finish();
}
return false;
}
};
OnTouchListener nextListener = new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction()==MotionEvent.ACTION_UP){
Intent edit = new Intent(getParent(), EditActivity.class);
TabGroupActivity parentActivity = (TabGroupActivity)getParent();
parentActivity.startChildActivity("EditActivity", edit);
return true;
}
return false;
}
};
back.setOnTouchListener(backListener);
next.setOnTouchListener(nextListener);
}
}
finally over TabGroupActivity.class which save all the stat instance.
public class TabGroupActivity extends ActivityGroup {
private ArrayList<String> mIdList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (mIdList == null) mIdList = new ArrayList<String>();
}
#Override
public void finishFromChild(Activity child) {
LocalActivityManager manager = getLocalActivityManager();
int index = mIdList.size()-1;
if (index < 1) {
finish();
return;
}
manager.destroyActivity(mIdList.get(index), true);
mIdList.remove(index); index--;
String lastId = mIdList.get(index);
Intent lastIntent = manager.getActivity(lastId).getIntent();
Window newWindow = manager.startActivity(lastId, lastIntent);
setContentView(newWindow.getDecorView());
}
public void startChildActivity(String Id, Intent intent) {
Window window = getLocalActivityManager().startActivity(Id,intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
if (window != null) {
mIdList.add(Id);
setContentView(window.getDecorView());
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
//preventing default implementation previous to android.os.Build.VERSION_CODES.ECLAIR
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
onBackPressed();
return true;
}
return super.onKeyUp(keyCode, event);
}
public void onBackPressed() {
int length = mIdList.size();
if ( length > 1) {
Activity current = getLocalActivityManager().getActivity(mIdList.get(length-1));
current.finish();
}
}
}
This is awesome solution you can try this.and make appropriate manifest entry.

Categories

Resources