I am facing a very weird issue. I am trying to launch one activity but instead of that, another activity is opening. I am trying to open RegActivity, I do have specified it in manifest and also made it Launcher activity but instead of that when I run the app "MainActivity" is calling.
MainActivity is not even a Launcher or Default activity. I cleaned up the project, Rebuilt it. But still, nothing works.
My Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.solodroid.ecommerce" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.GET_TASKS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<application
android:allowBackup="true"
android:hardwareAccelerated="true"
android:icon="#drawable/ic_launcher"
android:label="Frizzy"
android:theme="#style/AppTheme2" >
<activity
android:name="com.solodroid.ecommerce.RegActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.solodroid.ecommerce.MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
</activity>
<activity
android:name="com.solodroid.ecommerce.ActivityCategoryList"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityMenuList"
android:configChanges="keyboardHidden|orientation"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />
<activity
android:name="com.solodroid.ecommerce.ActivityMenuDetail"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityCart"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityCheckout"
android:configChanges="keyboardHidden|orientation"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateHidden" />
<activity
android:name="com.solodroid.ecommerce.ActivityConfirmMessage"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityContactUs"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityProfile"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityInformation"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.ActivityAbout"
android:screenOrientation="portrait" />
<activity
android:name="com.solodroid.ecommerce.LoginActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme.NoActionBar"/>
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"
/>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
</application>
</manifest>
RegActivity.java
package com.solodroid.ecommerce;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap;
public class RegActivity extends AppCompatActivity {
private EditText etid, etname, etstorename, etemail, etphone, etdoj;
Button btnregister;
TextView tvlogin;
private ParseContent parseContent;
PreferenceHelper preferenceHelper;
private final int RegTask = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg);
preferenceHelper = new PreferenceHelper(this);
parseContent = new ParseContent(this);
if(preferenceHelper.getIsLogin()){
Intent intent = new Intent(RegActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();
}
//etid = (EditText) findViewById(R.id.etmi_id);
etname = (EditText) findViewById(R.id.etname);
//etstorename = (EditText) findViewById(R.id.etstore_name);
etemail = (EditText) findViewById(R.id.etemail);
etphone = (EditText) findViewById(R.id.etphone);
// etdoj = (EditText) findViewById(R.id.etdoj);
btnregister = (Button) findViewById(R.id.btn);
tvlogin = (TextView) findViewById(R.id.tvlogin);
tvlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(RegActivity.this,LoginActivity.class);
startActivity(intent);
}
});
btnregister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
register();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
private void register() throws IOException, JSONException {
if (!AndyUtils.isNetworkAvailable(RegActivity.this)) {
Toast.makeText(RegActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show();
return;
}
AndyUtils.showSimpleProgressDialog(RegActivity.this);
final HashMap<String, String> map = new HashMap<>();
// map.put(AndyConstants.Params.MI_ID, etid.getText().toString());
map.put(AndyConstants.Params.NAME, etname.getText().toString());
// map.put(AndyConstants.Params.STORE_NAME, etstorename.getText().toString());
map.put(AndyConstants.Params.EMAIL, etemail.getText().toString());
map.put(AndyConstants.Params.PHONE, etphone.getText().toString());
//map.put(AndyConstants.Params.DOJ, etdoj.getText().toString());
new AsyncTask<Void, Void, String>(){
protected String doInBackground(Void[] params) {
String response="";
try {
HttpRequest req = new HttpRequest(AndyConstants.ServiceType.REGISTER);
response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
} catch (Exception e) {
response=e.getMessage();
}
return response;
}
protected void onPostExecute(String result) {
//do something with response
Log.d("newwwss", result);
onTaskCompleted(result, RegTask);
}
}.execute();
}
private void onTaskCompleted(String response,int task) {
Log.d("responsejson", response.toString());
AndyUtils.removeSimpleProgressDialog(); //will remove progress dialog
switch (task) {
case RegTask:
if (parseContent.isSuccess(response)) {
parseContent.saveInfo(response);
Toast.makeText(RegActivity.this, "Registered Successfully!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(RegActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();
}else {
Toast.makeText(RegActivity.this, parseContent.getErrorMessage(response), Toast.LENGTH_SHORT).show();
}
}
}
}
LoginActivity.java
package com.solodroid.ecommerce;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONException;
import java.io.IOException;
import java.util.HashMap;
public class LoginActivity extends AppCompatActivity {
private EditText etemail, etpassword;
Button btnlogin;
TextView tvreg;
private ParseContent parseContent;
private final int LoginTask = 1;
PreferenceHelper preferenceHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
parseContent = new ParseContent(this);
preferenceHelper = new PreferenceHelper(this);
etemail = (EditText) findViewById(R.id.etusername);
etpassword = (EditText) findViewById(R.id.etpassword);
btnlogin = (Button) findViewById(R.id.btn);
tvreg = (TextView) findViewById(R.id.tvreg);
tvreg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoginActivity.this, RegActivity.class);
startActivity(intent);
}
});
btnlogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
login();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
private void login() throws IOException, JSONException {
if (!AndyUtils.isNetworkAvailable(LoginActivity.this)) {
Toast.makeText(LoginActivity.this, "Internet is required!", Toast.LENGTH_SHORT).show();
return;
}
AndyUtils.showSimpleProgressDialog(LoginActivity.this);
final HashMap<String, String> map = new HashMap<>();
map.put(AndyConstants.Params.EMAIL, etemail.getText().toString());
map.put(AndyConstants.Params.PASSWORD, etpassword.getText().toString());
new AsyncTask<Void, Void, String>(){
protected String doInBackground(Void[] params) {
String response="";
try {
HttpRequest req = new HttpRequest(AndyConstants.ServiceType.LOGIN);
response = req.prepare(HttpRequest.Method.POST).withData(map).sendAndReadString();
} catch (Exception e) {
response=e.getMessage();
}
return response;
}
protected void onPostExecute(String result) {
//do something with response
Log.d("newwwss", result);
onTaskCompleted(result,LoginTask);
}
}.execute();
}
private void onTaskCompleted(String response, int task) {
Log.d("responsejson", response.toString());
AndyUtils.removeSimpleProgressDialog(); //will remove progress dialog
switch (task) {
case LoginTask:
if (parseContent.isSuccess(response)) {
parseContent.saveInfo(response);
Toast.makeText(LoginActivity.this, "Login Successfully!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(LoginActivity.this,RegActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();
}else {
Toast.makeText(LoginActivity.this, parseContent.getErrorMessage(response), Toast.LENGTH_SHORT).show();
}
}
}
}
MainActivity.java
package com.solodroid.ecommerce;
import java.io.IOException;
import java.util.ArrayList;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseInstallation;
import com.parse.PushService;
import android.annotation.SuppressLint;
import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.database.SQLException;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
#SuppressLint("NewApi")
public class MainActivity extends FragmentActivity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
// slide menu items
private String[] navMenuTitles;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> navDrawerItems;
private AdapterNavDrawerList adapter;
// declare dbhelper and adapter object
static DBHelper dbhelper;
AdapterMainMenu mma;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.nav_drawer_main);
// Parse push notification
Parse.initialize(this, getString(R.string.parse_application_id), getString(R.string.parse_client_key));
ParseAnalytics.trackAppOpened(getIntent());
PushService.setDefaultPushCallback(this, MainActivity.class);
ParseInstallation.getCurrentInstallation().saveInBackground();
mTitle = mDrawerTitle = getTitle();
// load slide menu items
navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);
// nav drawer icons from resources
navMenuIcons = getResources().obtainTypedArray(R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
mDrawerLayout.setDrawerShadow(R.drawable.navigation_drawer_shadow, GravityCompat.START);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items to array
navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons.getResourceId(8, -1)));
navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuIcons.getResourceId(9, -1)));
// Recycle the typed array
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new AdapterNavDrawerList(getApplicationContext(), navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.header)));
// get screen device width and height
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
// checking internet connection
if (!Constant.isNetworkAvailable(MainActivity.this)) {
Toast.makeText(MainActivity.this, getString(R.string.no_internet), Toast.LENGTH_SHORT).show();
}
mma = new AdapterMainMenu(this);
dbhelper = new DBHelper(this);
// create database
try {
dbhelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
// then, the database will be open to use
try {
dbhelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
// if user has already ordered food previously then show confirm dialog
if (dbhelper.isPreviousDataExist()) {
showAlertDialog();
}
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.drawable.ic_drawer, // nav
// menu
// toggle
// icon
R.string.app_name, // nav drawer open - description for
// accessibility
R.string.app_name // nav drawer close - description for
// accessibility
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
// on first time display view for first nav item
displayView(0);
}
}
// show confirm dialog to ask user to delete previous order or not
void showAlertDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.confirm);
builder.setMessage(getString(R.string.db_exist_alert));
builder.setCancelable(false);
builder.setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
// delete order data when yes button clicked
dbhelper.deleteAllData();
dbhelper.close();
}
});
builder.setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
// close dialog when no button clicked
dbhelper.close();
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
dbhelper.deleteAllData();
dbhelper.close();
finish();
overridePendingTransition(R.anim.open_main, R.anim.close_next);
}
/**
* Slide menu item click listener
*/
private class SlideMenuClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// toggle nav drawer on selecting action bar app icon/title
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.rate_app:
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + getPackageName())));
} catch (android.content.ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id=" + getPackageName())));
}
return true;
case R.id.more_app:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.more_apps))));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
/*
* * Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.ic_menu).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Diplaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
// update the main content by replacing fragments
Fragment fragment = null;
switch (position) {
case 0:
fragment = new ActivityHome();
break;
case 1:
startActivity(new Intent(getApplicationContext(), ActivityCategoryList.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 2:
startActivity(new Intent(getApplicationContext(), ActivityCart.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 3:
startActivity(new Intent(getApplicationContext(), ActivityCheckout.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 4:
startActivity(new Intent(getApplicationContext(), ActivityProfile.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 5:
startActivity(new Intent(getApplicationContext(), ActivityInformation.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 6:
startActivity(new Intent(getApplicationContext(), ActivityAbout.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 7:
Intent sendInt = new Intent(Intent.ACTION_SEND);
sendInt.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.app_name));
sendInt.putExtra(Intent.EXTRA_TEXT, "E-Commerce Android App\n\"" + getString(R.string.app_name)
+ "\" \nhttps://play.google.com/store/apps/details?id=" + getPackageName());
sendInt.setType("text/plain");
startActivity(Intent.createChooser(sendInt, "Share"));
break;
case 8:
startActivity(new Intent(getApplicationContext(), ActivityContactUs.class));
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
case 9:
dbhelper.deleteAllData();
dbhelper.close();
MainActivity.this.finish();
overridePendingTransition(R.anim.open_next, R.anim.close_next);
break;
default:
break;
}
if (fragment != null) {
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(navMenuTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#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);
}
}
What is wrong here? I don't find anything.
What about this code in your onCreate()
if(preferenceHelper.getIsLogin()){
Intent intent = new Intent(RegActivity.this,MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
this.finish();
}
if preferenceHelper.getIsLogin() is true you wont be able to see your RegActivity beacause it will instantly start MainActivity.
Related
I have a navigation drawer with some options (Home, Bluetooth, Alarm, Tips). I linked an activity to Bluetooth and Alarm but I got some problems with Home.
When I run the application I have a splash screen which is connected to the Home.java, in this activity I can click on my drawer and select the others alarm.java anche bluetooth.java but, when I link an activity to home, using the same method, my app stops working.
Thank you so much!
This is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.progetto.app">
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashScreen"
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=".Home"
android:label="#string/Home"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Alarm"
android:label="#string/title_activity_alarm"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Bluetooth"
android:label="#string/title_activity_bt"
android:theme="#style/AppTheme.NoActionBar" />
<activity
android:name=".Tips"
android:label="#string/title_activity_tips"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".AlarmActivity" />
<receiver android:name=".Alarm_Receiver" />
<activity android:name=".DeviceListActivity" />
<activity android:name=".ArduinoMain"/>
<service
android:name=".RingtonePlayingService"
android:enabled="true" />
</application>
</manifest>
This is my Home.java with drawer navigation
package com.progetto.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class Home extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
DrawerLayout drawer;
NavigationView navigationView;
Toolbar toolbar = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, 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);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
switch (id){
case R.id.nav_home:
Intent h = new Intent(Home.this,ArduinoMain.class);
startActivity(h);
break;
case R.id.nav_bt:
Intent i = new Intent(Home.this,DeviceListActivity.class);
startActivity(i);
break;
case R.id.nav_alarm:
Intent g = new Intent(Home.this,AlarmActivity.class);
startActivity(g);
break;
case R.id.nav_tips:
Intent s = new Intent(Home.this,Tips.class);
startActivity(s);
break;
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This is the activity I'm trying to connect to Home, I want to see this activity when the spash screen is over
package com.progetto.app;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class ArduinoMain extends Activity {
//Declare buttons & editText
Button functionOne, functionTwo;
private EditText editText;
//Memeber Fields
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// UUID service - This is the type of Bluetooth device that the BT module is
// It is very likely yours will be the same, if not google UUID for your manufacturer
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module
public String newAddress = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_arduino_main);
addKeyListener();
//Initialising buttons in the view
//mDetect = (Button) findViewById(R.id.mDetect);
functionOne = (Button) findViewById(R.id.functionOne);
functionTwo = (Button) findViewById(R.id.functionTwo);
//getting the bluetooth adapter value and calling checkBTstate function
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
/**************************************************************************************************************************8
* Buttons are set up with onclick listeners so when pressed a method is called
* In this case send data is called with a value and a toast is made
* to give visual feedback of the selection made
*/
functionOne.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("1");
Toast.makeText(getBaseContext(), "Function 1", Toast.LENGTH_SHORT).show();
}
});
functionTwo.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
sendData("2");
Toast.makeText(getBaseContext(), "Function 2", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onResume() {
super.onResume();
// connection methods are best here in case program goes into the background etc
//Get MAC address from DeviceListActivity
Intent intent = getIntent();
newAddress = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Set up a pointer to the remote device using its address.
BluetoothDevice device = btAdapter.getRemoteDevice(newAddress);
//Attempt to create a bluetooth socket for comms
try {
btSocket = device.createRfcommSocketToServiceRecord(MY_UUID);
} catch (IOException e1) {
Toast.makeText(getBaseContext(), "ERROR - Could not create Bluetooth socket", Toast.LENGTH_SHORT).show();
}
// Establish the connection.
try {
btSocket.connect();
} catch (IOException e) {
try {
btSocket.close(); //If IO exception occurs attempt to close socket
} catch (IOException e2) {
Toast.makeText(getBaseContext(), "ERROR - Could not close Bluetooth socket", Toast.LENGTH_SHORT).show();
}
}
// Create a data stream so we can talk to the device
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
Toast.makeText(getBaseContext(), "ERROR - Could not create bluetooth outstream", Toast.LENGTH_SHORT).show();
}
//When activity is resumed, attempt to send a piece of junk data ('x') so that it will fail if not connected
// i.e don't wait for a user to press button to recognise connection failure
sendData("x");
}
#Override
public void onPause() {
super.onPause();
//Pausing can be the end of an app if the device kills it or the user doesn't open it again
//close all connections so resources are not wasted
//Close BT socket to device
try {
btSocket.close();
} catch (IOException e2) {
Toast.makeText(getBaseContext(), "ERROR - Failed to close Bluetooth socket", Toast.LENGTH_SHORT).show();
}
}
//takes the UUID and creates a comms socket
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
//same as in device list activity
private void checkBTState() {
// Check device has Bluetooth and that it is turned on
if(btAdapter==null) {
Toast.makeText(getBaseContext(), "ERROR - Device does not support bluetooth", Toast.LENGTH_SHORT).show();
finish();
} else {
if (btAdapter.isEnabled()) {
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
// Method to send data
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
try {
//attempt to place data on the outstream to the BT device
outStream.write(msgBuffer);
} catch (IOException e) {
//if the sending fails this is most likely because device is no longer there
Toast.makeText(getBaseContext(), "ERROR - Device not found", Toast.LENGTH_SHORT).show();
finish();
}
}
public void addKeyListener() {
// get edittext component
editText = (EditText) findViewById(R.id.editText1);
// add a keylistener to keep track user input
editText.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// if keydown and send is pressed implement the sendData method
if ((keyCode == KeyEvent.KEYCODE_ENTER) && (event.getAction() == KeyEvent.ACTION_DOWN)) {
//I have put the * in automatically so it is no longer needed when entering text
sendData('*' + editText.getText().toString());
Toast.makeText(getBaseContext(), "Sending text", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
}
}
This is the splash screen
package com.progetto.app;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
public class SplashScreen extends AppCompatActivity {
private ImageView iv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash_screen);
iv=(ImageView) findViewById(R.id.iv);
Animation myanim= AnimationUtils.loadAnimation(this,R.anim.mytransition);
iv.startAnimation(myanim);
final Intent i=new Intent(this, Home.class);
Thread timer =new Thread(){
public void run(){
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
finally{
startActivity(i);
finish();
}
}
};
timer.start();
}
}
This is the project
DropBox
This is the apk
Apk
I am trying to display the title for the Navigation Drawer,It displayed properly but the problem is that when I am trying to click on the first item in the navigation drawer that is home ,it will display the Queues.class instead of expected class.And when click on the last item in the navigation Drawer application get crash.I just want to Display the Title in the navigation Drawer and last item click will show proper activity.Also problem is that the title display two times.
package com.abc;
//import android.app.Activity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.R.*;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.BaseBundle;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class navigation_drawer_class extends Activity
//public class navigation_drawer_class extends ListActivity
{
private static final int Copy = 0;
int a =0;
public static FrameLayout frameLayout;
TextView mytextview;
public static ListView mDrawerList;
public DrawerLayout mDrawerLayout;
String Fullname;
protected String[] listArray = {"Home","Queue","Inbox","Create Ticket","Search","Clients","App settings"};
protected static int position;
private static boolean isLaunch = true;
//*****************************************
JSONObject post_details_obj,post_obj;
public static String FIRST_NAME="first_name",LAST_NAME="last_name";
JSONArray staff_data_array;
//*****************************************
private ActionBarDrawerToggle actionBarDrawerToggle;
Operation op=new Operation();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//------------------ THIS ONE -------------------------
getActionBar().setHomeAsUpIndicator(R.drawable.crop3);//THIS ONE FOR THE DRAWER LOGO
//--------------------- THIS ONE ----------------------
frameLayout = (FrameLayout)findViewById(R.id.content_frame);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
/// mDrawerList.setAdapter(null);
//***************** To Set the Welcome client ******************************************
//========= THIS ONE ===============
new getname().execute();
//========= THIS ONE ===============
/* mDrawerList.setAdapter(null);
View header = (View)getLayoutInflater().inflate(R.layout.headerview,null);
TextView headerValue = (TextView) header.findViewById(R.id.headerview_id);
headerValue.setText("Mydata");
mDrawerList.addHeaderView(header, null, false);//addHeaderView(header, null, false)
*/
/* TextView tv=new TextView(getApplicationContext());
Log.d("Fullname in oncreate : ",Fullname.toString());
tv.setText(Fullname); */
//******************To Set the Welcome client ******************************************
mDrawerList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listArray));
mDrawerList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
openActivity(position);
}
});
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
actionBarDrawerToggle = new ActionBarDrawerToggle(
this, // host Activity
mDrawerLayout, // DrawerLayout object
R.drawable.ic_launcher, // nav drawer image to replace 'Up' caret
R.string.open_drawer, // "open drawer" description for accessibility
R.string.close_drawer) // "close drawer" description for accessibility
{
#Override
public void onDrawerClosed(View drawerView)
{
getActionBar().setTitle(listArray[position]);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerClosed(drawerView);
}
#Override
public void onDrawerOpened(View drawerView)
{
getActionBar().setTitle(getString(R.string.app_name));
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset)
{
super.onDrawerSlide(drawerView, slideOffset);
}
#Override
public void onDrawerStateChanged(int newState)
{
super.onDrawerStateChanged(newState);
}
};
mDrawerLayout.setDrawerListener(actionBarDrawerToggle);
if(isLaunch){
isLaunch = false;
openActivity(0);
}
}
protected void openActivity(int position) {
// mDrawerList.setItemChecked(position, true);
// setTitle(listArray[position]);
mDrawerLayout.closeDrawer(mDrawerList);
navigation_drawer_class.position = position; //Setting currently selected position in this field so that it will be available in our child activities.
switch (position) {
case 0:
startActivity(new Intent(this, Folders.class));
break;
//case 2:
case 1:
Intent i=new Intent(navigation_drawer_class.this,Queues.class);
i.putExtra("set_queue","set");
startActivity(i);
break;
case 2:
//case 3:
Intent inbox=new Intent(navigation_drawer_class.this,Tickets.class);
inbox.putExtra("filter_id","&vis_filter_id=1");
inbox.putExtra("title","Inbox");
inbox.putExtra("set_queue","no");
startActivity(inbox);
break;
case 3:
//case 4:
startActivity(new Intent(this, New_Ticket_step1.class));
break;
case 4:
//case 5:
startActivity(new Intent(this, Search.class));
break;
case 5:
//case 6:
startActivity(new Intent(this, Client.class));
break;
case 6:
//case 7:
startActivity(new Intent(this, Settings.class));
break;
default:
break;
}
/*
switch (position) {
case 0:
break;
case 1:
startActivity(new Intent(this, Folders.class));
break;
case 2:
Intent i=new Intent(navigation_drawer_class.this,Queues.class);
i.putExtra("set_queue","set");
startActivity(i);
break;
case 3:
Intent inbox=new Intent(navigation_drawer_class.this,Tickets.class);
inbox.putExtra("filter_id","&vis_filter_id=1");
inbox.putExtra("title","Inbox");
inbox.putExtra("set_queue","no");
startActivity(inbox);
break;
case 4:
startActivity(new Intent(this, New_Ticket_step1.class));
break;
case 5:
startActivity(new Intent(this, Search.class));
break;
case 6:
startActivity(new Intent(this, Client.class));
break;
case 7:
startActivity(new Intent(this, Settings.class));
break;
default:
break;
}
*/
//Toast.makeText(this, "Selected Item Position::"+position, Toast.LENGTH_LONG).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// getMenuInflater().inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(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 (actionBarDrawerToggle.onOptionsItemSelected(item))
{
return true;
}
switch (item.getItemId())
{
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
//boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
//menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/* We can override onBackPressed method to toggle navigation drawer*/
#Override
public void onBackPressed()
{
if(mDrawerLayout.isDrawerOpen(mDrawerList))
{
mDrawerLayout.closeDrawer(mDrawerList);
}
else
{
mDrawerLayout.openDrawer(mDrawerList);
}
}
//-----------------------------------------------------------
private class getname extends AsyncTask<Void, Void, JSONArray>
{
Dialog dialog;
#Override
public void onPreExecute()
{
dialog = new Dialog(navigation_drawer_class.this,android.R.style.Theme_Translucent_NoTitleBar);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setContentView(R.layout.progressbar);
dialog.show();
}
#Override
protected JSONArray doInBackground(Void... params)
{
String STAFF_URL=op.getUrl(getApplicationContext(),"staff","get_staff_details","");
staff_data_array = JSONfunctions.getJSONfromURL(STAFF_URL+"&vis_encode=json",navigation_drawer_class.this);
return staff_data_array;
}
#Override
public void onPostExecute(JSONArray staff_data_array)
{
super.onPostExecute(staff_data_array);
String staff_data_result =staff_data_array.toString();
try {
post_obj = staff_data_array.getJSONObject(0);
String fname=post_obj.getString(FIRST_NAME);
String lname=post_obj.getString(LAST_NAME);
//Fullname =fname+" "+lname;
Fullname =fname;
if(Fullname=="")
{
Fullname="Admin";
}
Fullname="Welcome "+Fullname;
View header = (View)getLayoutInflater().inflate(R.layout.headerview,null);
TextView headerValue = (TextView) header.findViewById(R.id.headerview_id);
headerValue.setText(Fullname);
mDrawerList.addHeaderView(header, null, false);//addHeaderView(header, null, false) */
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
dialog.dismiss();
}
}
//-----------------------------------------------------------
}
I want after a click on the OK button the MenuActivity to be shown. I have already searched on the Internet to find an answer and tried everything. I haave the activity declared in the AndroidManifest and I also tried to use Intent(this, MenuActivity.class) and also the one with the action inside but it doesn't work.
MainActivity:
package com.jamesjohnson.chronos;
import android.app.AlertDialog;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.*;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.jamesjohnson.chronos.R;
public class MainActivity extends ActionBarActivity implements OnClickListener {
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.setTitle("Willkommen");
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(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.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
switch(id) {
case R.id.action_mainmenu:
startActivity(new Intent("com.jamesjohnson.chronos.MenuActivity"));
return true;
case R.id.action_settings:
showMessageBox("Es gibt leider noch keine Einstellungen. Wir arbeiten daran!", true, true);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
try {
Intent intent = new Intent(MainActivity.this, MenuActivity.class);
Context ctx = this;
intent.setClassName(ctx, "com.jamesjohnson.chronos.MenuActivity");
intent.setAction("com.jamesjohnson.chronos.MenuActivity");
if ((intent.getAction() == "com.jamesjohnson.chronos.MenuActivity") || (intent.getClass() != null)) {
MainActivity.this.startActivity(intent);
showMessageBox("Button has been pressed " + intent.toString(), true, true);
}
else {
showMessageBox("Error : Hauptmenü ist nicht erreichbar", true, true);
}
}
catch (ActivityNotFoundException an) {
showMessageBox("Error :" + an.getMessage(), true, true);
}
catch (Exception e) {
showMessageBox("Error :" + e.getMessage(), true, true);
}
}
protected void showMessageBox(String message, boolean showOKbutton, boolean canceable) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MainActivity.this);
dlgAlert.setMessage(message);
dlgAlert.setTitle("Chronos");
if (showOKbutton) {
dlgAlert.setPositiveButton("OK", null);
}
if (canceable) {
dlgAlert.setCancelable(true);
}
dlgAlert.create().show();
}
}
Here's my AndroidManifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jamesjohnson.chronos"
android:versionCode="1"
android:versionName="1.0.1
" >
<application
android:allowBackup="true"
android:debuggable="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>
<activity
android:name=".MenuActivity"
android:label="#string/title_activity_menu"
android:parentActivityName=".MainActivity" >
<intent-filter>
<action android:name="com.jamesjohnson.chronos.MenuActivity" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<!-- Parent activity meta-data to support 4.0 and lower -->
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.jamesjohnson.chronos.MainActivity" />
</activity>
</application>
</manifest>
And finally here's the MenuActivity:
package com.jamesjohnson.chronos;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class MenuActivity extends ListActivity {
private static final String TAG = "MenuActivity";
static final String[] ENTRIES = new String[] {"Kunden", "Projekte", "Leistungen", "Zeiten"};
ListView listView = getListView();
#Override
protected void onCreate(Bundle savedInstanceState) {
showMessageBox("Activity is beeing created", true, true);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
this.setTitle("Hauptmenü");
this.setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ENTRIES));
listView.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switch (position) {
case 0:
showMessageBox("Kunden", true, true);
break;
case 1:
showMessageBox("Projekte", true, true);
break;
case 2:
showMessageBox("Leistungen", true, true);
break;
case 3:
showMessageBox("Zeiten", true, true);
break;
default:
showMessageBox("Error: Undefined index", true, true);
}
}
});
}
#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_menu, 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);
}
protected void showMessageBox(String message, boolean showOKbutton, boolean canceable) {
AlertDialog.Builder dlgAlert = new AlertDialog.Builder(MenuActivity.this);
dlgAlert.setMessage(message);
dlgAlert.setTitle("Chronos");
if (showOKbutton) {
dlgAlert.setPositiveButton("OK", null);
}
if (canceable) {
dlgAlert.setCancelable(true);
}
dlgAlert.create().show();
}
}
Unfortunately I can't show you my Logcat because it doesn't work on my computer. (I always have to export the APK to test the App).
P.S. I am working with Android Studio 1.0.1
...Please HELP ME !
To open a new activity you simply have to call it like this inside the onClick method.
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
So your onClick method will look like this.
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
}
Hope this helps.
Is because you say MainActivity.this, but you aren't in the MainActivity context.
You could make a reference of your current context in onCreate() and save it in a field:
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
context = this;
//rest of your code here
}
and use it as:
Intent intent = new Intent(context, MenuActivity.class);
//Something else
context.startActivity(intent);
Go to your manifest file, you will for your MainActivity manifest:
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
Just copy them and paste them for your MenuActivity.
I had the same same problem than you and it worked for me, but I don't know why.
Good luck!
first make sure your AndroidManifest.xml file contain declaration of all Activities in your app, like
<activity android:name=".MenuActivity"/>
then you create new intent and start it where you need to start the second Activity
Intent intent = new Intent(v.getContext(), MenuActivity.class);
startActivity(intent);
I am developing an app which has a home screen consisting of list view(Home Activity).User clicks on list item and new activity is started named as Topic.This activity also consist of list view. Home is set as parent activity for Topic.
Now in Topic class i am again calling Topic class using intent.
So a user clicks on a list item in Home activity,which opens a new Topic activity.User again clicks on list item ,and another new activity Topic is created,so we are at rd level. My app is working fine till here, but as Parent for Topic is Home,so as soon as i press back or up button,irrespective of where i am in my app,it is always the Home class which opens.
How to handle this so that all user can traverse back to each activity.
The code is given below:
Home.java
package com.example.guninder.home;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import java.util.List;
import static android.widget.AdapterView.*;
public class Home extends AppCompatActivity implements FetchDataListener {
private ProgressDialog dialog;
private ListView HomeListview;
private DrawerLayout home_drawer_layout;
private ListView Menu_option_list;
private String[] Menu_list;
private ActionBarDrawerToggle drawerToggle;
private ApplicationAdaptor adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
HomeListview = (ListView) findViewById(R.id.listView1);
itemClickListener(HomeListview);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
Menu_list = getResources().getStringArray(R.array.Menu_options);
home_drawer_layout = (DrawerLayout) findViewById(R.id.home_drawable);
Menu_option_list = (ListView) findViewById(R.id.home_menu_option);
Menu_option_list.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_expandable_list_item_1, Menu_list));
// home_Toolbar.setNavigationIcon(R.drawable.ic_drawer);
drawerToggle = new ActionBarDrawerToggle(this, home_drawer_layout, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
};
drawerToggle.setDrawerIndicatorEnabled(true);
home_drawer_layout.setDrawerListener(drawerToggle);
initView();
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_activity_actions, menu);
return true;
}
private void initView() {
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
// String url = "http://dexterous.comuv.com/connect.php";
String url = "http://192.168.0.25/connect.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url,null);
}
#Override
public void onFetchComplete(List<Application> data) {
// dismiss the progress dialog
if (dialog != null) dialog.dismiss();
// create new adapter
adapter = new ApplicationAdaptor(this, data);
HomeListview.setAdapter(adapter);
// set the adapter to list
//setListAdapter(adapter);
}
public void onPostCreate(Bundle savedInstanceState){
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if (dialog != null) dialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
#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;
}
if(drawerToggle.onOptionsItemSelected(item)){
return true;
}
return super.onOptionsItemSelected(item);
}
public void itemClickListener(final ListView HomeListview) {
HomeListview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Application app = adapter.getItem(position);
Intent intent = new Intent(Home.this, Topic.class);
intent.putExtra("topic_name",app.getTitle());
intent.putExtra("topic_id", app.getTopic_id());
intent.putExtra("Content", app.getParentContent());
Toast toast=Toast.makeText(Home.this,app.getParentContent(),Toast.LENGTH_LONG);
startActivity(intent);
}
});
}
}
Topic.java
package com.example.guninder.home;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class Topic extends AppCompatActivity implements FetchDataListener {
String topicName, ParentContent;
int topic_id;
//TextView txv;
ProgressDialog Topicdialog;
ListView topiclistView;
ApplicationAdaptor tAdaptor;
TextView txv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_topic);
Bundle extras = getIntent().getExtras();
if (extras == null) {
topicName = null;
}
topicName = extras.getString("topic_name");
topic_id = extras.getInt("topic_id");
ParentContent = extras.getString("Content");
txv = (TextView) findViewById(R.id.content);
txv.setMovementMethod(ScrollingMovementMethod.getInstance());
if (ParentContent.isEmpty()) {
txv.setVisibility(txv.GONE);
} else {
txv.setText(ParentContent);
}
setTitle(topicName);
topiclistView = (ListView) findViewById(R.id.topiclistView1);
itemClickListener(topiclistView);
topicinitView();
}
#Override
public void onPause(){
super.onPause();
}
public void onResume(){
super.onResume();
}
private void topicinitView() {
// show progress dialog
Topicdialog = ProgressDialog.show(this, "", "Loading...");
// String url = "http://dexterous.comuv.com/Topic.php";
String url = "http://192.168.0.25/Topic.php";
FetchDataTask task = new FetchDataTask(this);
task.execute(url, String.valueOf(topic_id));
}
#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_topic, 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);
}
#Override
public void onFetchComplete(List<Application> data) {
if (Topicdialog != null) Topicdialog.dismiss();
// create new adapter
tAdaptor = new ApplicationAdaptor(this, data);
topiclistView.setAdapter(tAdaptor);
// set the adapter to list
//setListAdapter(adapter);
}
#Override
public void onFetchFailure(String msg) {
// dismiss the progress dialog
if (Topicdialog != null) Topicdialog.dismiss();
// show failure message
Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}
public void itemClickListener(final ListView TopicListview) {
TopicListview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Application app = tAdaptor.getItem(position);
if (app.getChildExist()) {
Intent intent = new Intent(Topic.this, Topic.class);
intent.putExtra("topic_name", app.getTitle());
intent.putExtra("topic_id", app.getTopic_id());
intent.putExtra("Content", app.getParentContent());
// Toast toast = Toast.makeText(Topic.this, app.getTopic_id(), Toast.LENGTH_LONG);
//toast.show();
startActivity(intent);
finish();
}
}
});
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.guninder.home" >
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Home"
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=".Topic"
android:label="#string/title_activity_topic"
android:parentActivityName=".Home" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.guninder.home.Home" />
</activity>
<activity
android:name=".SetNotification"
android:label="#string/title_activity_set_notification"
android:theme="#android:style/Theme.Dialog" >
</activity>
</application>
</manifest>
Please help.Thanks in advance
Comment finish() inside the listitem click in topic class. it will solve your problem.
What you could do is, do not set Home as the parent of Topic.
This way when user presses back, the previous activity that was open will be shown to the user.
im trying to add a (+) icon on right of navigation bar in android, and then launch a new intent when clicked, but i can't seem to make it work, it's showing me the left icon to open/close the drawer, but the right icon is nowhere to be found.
Can anyone give me a hand on why its not working? im loosing my mind here...
The navigation bar looks like this, there's enough room for the right side
ActivityHome.java
package com.roneskinder.x111.activity.fragment;
import java.util.ArrayList;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
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.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.roneskinder.x111.PagerSlidingTabStrip;
import com.roneskinder.x111.R;
import com.roneskinder.x111.adapter.MenuAdapter;
import com.roneskinder.x111.config.AppConfig;
import com.roneskinder.x111.manager.ResourcesContentManager;
import com.roneskinder.x111.model.NavDrawerItem;
import com.roneskinder.x111.util.AppUtils;
public class ActivityHome extends ActionBarActivity {
private Context mContext;
DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] navMenuTitles;
private FragmentManager mFragmentManager;
private Fragment mFragment;
private ActionBarDrawerToggle mDrawerToggle;
private TypedArray navMenuIcons;
private ArrayList<NavDrawerItem> mNavDrawerItems;
private MenuAdapter menuAdapter;
private Dialog mCustomDialog;
private RelativeLayout mAdsView;
protected static String TAG = ActivityHome.class.toString();
protected static EditText nameList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = ActivityHome.this;
showNavigationSlider();
if (savedInstanceState == null) {
selectItem(0);
}
// Init Ads
// initAds();
}
#Override
protected void onResume() {
super.onResume();
setTheme();
}
/**
* Method to show navigation drawer
*/
private void showNavigationSlider() {
if (mDrawerLayout == null) {
// enable ActionBar app icon to behave as action to toggle nav drawer
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mTitle = mDrawerTitle = getTitle();
navMenuTitles = getResources().getStringArray(
R.array.nav_drawer_items);
navMenuIcons = getResources().obtainTypedArray(
R.array.nav_drawer_icons);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
mNavDrawerItems = new ArrayList<NavDrawerItem>();
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[0],
navMenuIcons.getResourceId(0, -1)));
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[1],
navMenuIcons.getResourceId(1, -1)));
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[2],
navMenuIcons.getResourceId(2, -1)));
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[3],
navMenuIcons.getResourceId(3, -1)));
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[4],
navMenuIcons.getResourceId(4, -1)));
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[5],
navMenuIcons.getResourceId(5, -1)));
mNavDrawerItems.add(new NavDrawerItem(navMenuTitles[6],
navMenuIcons.getResourceId(6, -1)));
navMenuIcons.recycle();
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
menuAdapter = new MenuAdapter(ActivityHome.this);
menuAdapter.setList(mNavDrawerItems);
mDrawerList.setAdapter(menuAdapter);
mDrawerToggle = new ActionBarDrawerToggle
(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.app_name, /* "open drawer" description for accessibility */
R.string.app_name /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
}
#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);
mDrawerToggle.syncState();
setTheme();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Here im inflating my menu options
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.new_list, 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);
// here im setting its visibility to true/false depending on the drawer position
menu.findItem(R.id.action_new_list).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
break;
}
// here im adding a click event in the button
case R.id.action_new_list:
aboutClicked();
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* Slide menu item click listener
* */
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
onItemClickListerner(position);
}
}
/**
* Display selected navigation drawer list item
* */
private void onItemClickListerner(int position) {
Intent intent = null;
switch (position) {
case 0:
//intent = new Intent(mContext, ActivitySettings.class);
//startActivity(intent);
mDrawerLayout.closeDrawers();
break;
case 1:
//intent = new Intent(mContext, ActivityTheme.class);
//startActivity(intent);
mDrawerLayout.closeDrawers();
break;
case 2:
//updateClicked();
mDrawerLayout.closeDrawers();
break;
case 3:
//moreAppClicked();
mDrawerLayout.closeDrawers();
break;
case 4:
//shareClicked(getString(R.string.share_subject),TabsApplication.getAppUrl());
mDrawerLayout.closeDrawers();
break;
case 5:
//rateAppClicked();
mDrawerLayout.closeDrawers();
break;
case 6:
newListClicked();
mDrawerLayout.closeDrawers();
break;
}
}
/**
* Method to check for updated app.
*/
private void updateClicked() {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id="
+ mContext.getPackageName())));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id="
+ mContext.getPackageName())));
}
}
/**
* Method to rate the app.
*/
private void rateAppClicked() {
try {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id="
+ mContext.getPackageName())));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://play.google.com/store/apps/details?id="
+ mContext.getPackageName())));
}
}
/**
* Method to share app via different available share apps
*/
private void shareClicked(String subject, String text) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_SUBJECT, subject);
intent.putExtra(Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(intent,
getString(R.string.share_via)));
}
/**
* Method to Show more apps from Developer
*/
private void moreAppClicked() {
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(String
.format("market://search?q=pub:%s",
AppConfig.PLAYSTORE_ACCOUNT_NAME))));
} catch (ActivityNotFoundException anfe) {
startActivity(new Intent(
Intent.ACTION_VIEW,
Uri.parse(String
.format("https://play.google.com/store/apps/developer?id=%s&hl=en",
AppConfig.PLAYSTORE_ACCOUNT_NAME))));
}
}
/**
* Method to show about
*/
private void aboutClicked() {
try {
String appname = null;
appname = getString(R.string.app_name_message) + " "
+ getString(R.string.app_name) + "" + "\n\n";
String appversion = getString(R.string.app_version)
+ " "
+ mContext.getPackageManager().getPackageInfo(
mContext.getPackageName(),
PackageInfo.CONTENTS_FILE_DESCRIPTOR).versionCode
+ "\n\n";
String name = getString(R.string.response_message);
showAboutCustomDialog(getString(R.string.about), appname
+ appversion + name, getString(R.string.ok),
getString(R.string.cancel), true);
} catch (NameNotFoundException ex) {
ex.printStackTrace();
}
}
/**
* Method to show custom dialog.
*
* #param title
* #param message
* #param okText
* #param cancelText
* #param singleButtonEnabled
*/
private void showAboutCustomDialog(String title, String message,
String okText, String cancelText, boolean singleButtonEnabled) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.about_dialog_view, null);
RelativeLayout titlebarView = (RelativeLayout) dialogView
.findViewById(R.id.title_bar_view);
titlebarView.setBackgroundColor(ResourcesContentManager.getInstance()
.getTitleBarColor(mContext, -1));
Button okButton = (Button) dialogView.findViewById(R.id.ok_button);
Button cancelButton = (Button) dialogView
.findViewById(R.id.cancel_button);
okButton.setBackgroundResource(ResourcesContentManager.getInstance()
.getButtonBackgroundResource(mContext, -1));
okButton.setTextAppearance(mContext, ResourcesContentManager
.getInstance().getButtonTextStyle(mContext, -1));
cancelButton.setBackgroundResource(ResourcesContentManager
.getInstance().getButtonBackgroundResource(mContext, -1));
cancelButton.setTextAppearance(mContext, ResourcesContentManager
.getInstance().getButtonTextStyle(mContext, -1));
TextView titleTextview = (TextView) dialogView
.findViewById(R.id.title_textview);
TextView messageTextview = (TextView) dialogView
.findViewById(R.id.message_textview);
TextView name = (TextView) dialogView.findViewById(R.id.email_textview);
name.setText("test#test.com");
if (mCustomDialog != null) {
mCustomDialog.dismiss();
mCustomDialog = null;
}
mCustomDialog = new Dialog(mContext,
android.R.style.Theme_Translucent_NoTitleBar);
mCustomDialog.setContentView(dialogView);
mCustomDialog.setOnKeyListener(new OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == keyCode) {
dialog.dismiss();
}
return false;
}
});
mCustomDialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
}
});
mCustomDialog.setCanceledOnTouchOutside(false);
titleTextview.setText(title);
messageTextview.setText(message);
if (singleButtonEnabled) {
okButton.setText(okText);
cancelButton.setVisibility(View.GONE);
} else {
okButton.setText(okText);
cancelButton.setText(cancelText);
}
/**
* Listener for OK button click.
*/
okButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCustomDialog.dismiss();
}
});
/**
* Listener for Cancel button click.
*/
cancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCustomDialog.dismiss();
}
});
mCustomDialog.show();
}
/**
* Method to create new list
*/
private void newListClicked() {
showCreateListDialog("Nueva lista de compras", "Crear", getString(R.string.cancel), false);
}
/**
* Method to create new list dialog
*
* #param title
* #param message
* #param okText
* #param cancelText
* #param singleButtonEnabled
*/
private void showCreateListDialog(String title,
String okText, String cancelText, boolean singleButtonEnabled) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater.inflate(R.layout.new_list_dialog_view, null);
RelativeLayout titlebarView = (RelativeLayout) dialogView
.findViewById(R.id.title_bar_view);
titlebarView.setBackgroundColor(ResourcesContentManager.getInstance()
.getTitleBarColor(mContext, -1));
Button okButton = (Button) dialogView.findViewById(R.id.ok_button);
Button cancelButton = (Button) dialogView.findViewById(R.id.cancel_button);
okButton.setBackgroundResource(ResourcesContentManager.getInstance().getButtonBackgroundResource(mContext, -1));
okButton.setTextAppearance(mContext, ResourcesContentManager.getInstance().getButtonTextStyle(mContext, -1));
cancelButton.setBackgroundResource(ResourcesContentManager.getInstance().getButtonBackgroundResource(mContext, -1));
cancelButton.setTextAppearance(mContext, ResourcesContentManager.getInstance().getButtonTextStyle(mContext, -1));
TextView titleTextview = (TextView) dialogView.findViewById(R.id.title_textview);
nameList = (EditText) dialogView.findViewById(R.id.list_name);
if (mCustomDialog != null) {
mCustomDialog.dismiss();
mCustomDialog = null;
}
mCustomDialog = new Dialog(mContext,android.R.style.Theme_Translucent_NoTitleBar);
mCustomDialog.setContentView(dialogView);
mCustomDialog.setOnKeyListener(new OnKeyListener() {
public boolean onKey(DialogInterface dialog, int keyCode,
KeyEvent event) {
if (KeyEvent.KEYCODE_BACK == keyCode) {
dialog.dismiss();
}
return false;
}
});
mCustomDialog.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
}
});
mCustomDialog.setCanceledOnTouchOutside(false);
titleTextview.setText(title);
if (singleButtonEnabled) {
okButton.setText(okText);
cancelButton.setVisibility(View.GONE);
} else {
okButton.setText(okText);
cancelButton.setText(cancelText);
}
/**
* Listener for OK button click.
*/
okButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// if list has valid name, save
String name = nameList.getText().toString();
if(!name.matches("")){
Intent intent = new Intent(mContext, ActivityAddProductsToList.class);
startActivity(intent);
mCustomDialog.dismiss();
}else{
AppUtils.showToast(mContext, "Por favor ingrese el nombre de la nueva lista");
}
}
});
/**
* Listener for Cancel button click.
*/
cancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mCustomDialog.dismiss();
}
});
mCustomDialog.show();
}
private void selectItem(int position) {
switch (position) {
case 0:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.content,
FragmentPageSlidingTabStrip.newInstance(),
FragmentPageSlidingTabStrip.TAG).commit();
break;
default:
// mFragment = new PlanetFragment();
// Bundle args = new Bundle();
// args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
// mFragment.setArguments(args);
//
// getSupportFragmentManager().beginTransaction()
// .add(R.id.content, mFragment).commit();
break;
}
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
protected void onDestroy() {
if (mContext != null) {
if (mCustomDialog != null) {
mCustomDialog.dismiss();
mCustomDialog = null;
}
mDrawerList = null;
mDrawerTitle = null;
mTitle = null;
navMenuTitles = null;
mFragmentManager = null;
mFragment = null;
mDrawerLayout = null;
mDrawerToggle = null;
mContext = null;
super.onDestroy();
}
}
/**
* Method to set themes backgrounds
*/
private void setTheme() {
int actionBarTitleId = Resources.getSystem().getIdentifier(
"action_bar_title", "id", "android");
if (actionBarTitleId > 0) {
TextView title = (TextView) findViewById(actionBarTitleId);
title.setTextAppearance(mContext, R.style.ActionBarTitleTextStyle);
}
getSupportActionBar().setBackgroundDrawable(
new ColorDrawable(ResourcesContentManager.getInstance()
.getTitleBarColor(mContext, -1)));
mDrawerList.setBackgroundColor(ResourcesContentManager.getInstance()
.getScreenBgColor(mContext, -1));
PagerSlidingTabStrip tabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabStrip.setIndicatorColor(ResourcesContentManager.getInstance()
.getTitleBarColor(mContext, -1));
}
/**
* Method to inits the ads banner view
*/
/*
private void initAds() {
if (mAdsView == null) {
mAdsView = (RelativeLayout) findViewById(R.id.bottom_ads_view);
}
if (AppConfig.BANNER_ADS_ENABLED) {
mAdsView.setVisibility(View.VISIBLE);
AppUtils.addAdsBannerView(ActivityHome.this, mAdsView);
} else {
mAdsView.setVisibility(View.GONE);
}
}
*/
}
activity_main.xml
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/drawer_layout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="#+id/content_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<RelativeLayout
android:id="#+id/bottom_ads_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" >
</RelativeLayout>
<RelativeLayout
android:id="#+id/content"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#id/bottom_ads_view" >
</RelativeLayout>
</RelativeLayout>
<!-- The navigation drawer -->
<ListView
android:id="#+id/left_drawer"
android:layout_width="#dimen/slider_width"
android:layout_height="fill_parent"
android:layout_gravity="start"
android:background="#color/slider_bg_color"
android:choiceMode="singleChoice"
android:divider="#color/slider_divider_color"
android:dividerHeight="1dp" />
</android.support.v4.widget.DrawerLayout>
new_list.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/action_new_list"
android:icon="#drawable/action_search"
android:title="#string/action_new_list"
android:showAsAction="ifRoom|withText" />
</menu>
Change following line in onCreateOptionsMenu
return super.onCreateOptionsMenu(menu);
to
return true;
The id of your menu item is the same name as the string (action_new_list). I'd try changing that to see if there's a collision.
2. Add a titleCondensed attribute, as that's all that will show in your Options Menu.
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="#+id/action_new_list"
android:icon="#drawable/action_search"
android:title="#string/action_new_list"
android:titleCondensed="#string/new_string"
android:showAsAction="ifRoom|withText" />
</menu>