Android, Navigation Drawer - how to show IC_lancher - java

I have created in Eclipse a Android default project with navigation drawer.
But my App Icon is not showing on the Action bar. I want to use the min API 9.
I also using appcombat V7 for support library.
Main Activity :
public class MainActivity extends ActionBarActivity implements
NavigationDrawerFragment.NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the
* navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in
* {#link #restoreActionBar()}.
*/
private CharSequence mTitle;
ActionBar actionBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initiate
actionBar = getSupportActionBar();
mNavigationDrawerFragment = (NavigationDrawerFragment) getSupportFragmentManager()
.findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
}
#Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager
.beginTransaction()
.replace(R.id.container,
Fragment1.newInstance(position + 1)).commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
// enable ActionBar app icon to behave as action to toggle nav drawer
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Manifest:
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".SplashScreen"
android:label="#string/title_activity_splash_screen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
</activity>
my Style :
<resources>
<!--
Base application theme, dependent on API level. This theme is replaced
by AppBaseTheme from res/values-vXX/styles.xml on newer devices.
-->
<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
<!--
Theme customizations available in newer API levels can go in
res/values-vXX/styles.xml, while customizations related to
backward-compatibility can go here.
-->
</style>
<!-- Application theme. -->
<style name="AppTheme" parent="AppBaseTheme">
<!-- All customizations that are NOT specific to a particular API-level can go here. -->
</style>
</resources>
Thanks

Related

How to sync with time in custom calendar that I have made.? Like when I open my calendar it should show the current date and month

Main Activity ScreenI have made a custom calendar with textview, So I want the calendar to show current date and month when I open the calendar...
`My calendar should open directly in the current month and show the current date, just like google calendar.
<TextView
android:textColor="#color/Blue"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:fontFamily="#font/caviardreams"
android:gravity="top|center"
android:text="1"
android:textSize="11sp"
android:textStyle="bold"
android:maxWidth="1dp"
android:maxHeight="1dp"/>
<TextView
android:textColor="#color/Blue"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:fontFamily="#font/caviardreams"
android:gravity="top|center"
android:text="2"
android:textSize="11sp"
android:textStyle="bold"
android:maxWidth="1dp"
android:maxHeight="1dp"/>
<TextView
android:textColor="#color/Blue"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_weight="1"
android:fontFamily="#font/caviardreams"
android:gravity="top|center"
android:text="3"
android:textSize="11sp"
android:textStyle="bold"
android:maxWidth="1dp"
android:maxHeight="1dp"/>
`
I expect the current date to be highlighted in the current month.
This is the java code of MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
ViewPager viewPager;
EditText txt;
Button btn;
String str;
AdView adView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout 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 = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
viewPager = findViewById(R.id.view_pager);
viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
//admob app id
MobileAds.initialize(this,"ca-app-pub-6376378742627184~5911477780");
adView = (AdView)findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().addTestDevice(AdRequest.DEVICE_ID_EMULATOR).build();
adView.loadAd(adRequest);
}
public void date(View view) {
}
private class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int pos) {
switch(pos) {
case 0: return Frag1.newInstance("Frag1, Instance 1");
case 1: return Frag2.newInstance("Frag2, Instance 2");
case 2: return Frag3.newInstance("Frag3, Instance 3");
case 3: return Frag4.newInstance("Frag4, Instance 4");
case 4: return Frag5.newInstance("Frag5, Instance 5");
case 5: return Frag6.newInstance("Frag6, Instance 6");
case 6: return Frag7.newInstance("Frag7, Instance 7");
case 7: return Frag8.newInstance("Frag8, Instance 8");
case 8: return Frag9.newInstance("Frag9, Instance 9");
case 9: return Frag10.newInstance("Frag10, Instance 10");
case 10: return Frag11.newInstance("Frag11, Instance 11");
case 11: return Frag12.newInstance("Frag12, Instance 12");
default: return Frag1.newInstance("Frag1, Default");
}
}
#Override
public int getCount() {
return 12;
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
finish();
System.exit(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
finish();
System.exit(0);
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
ApplicationInfo app = getApplicationContext().getApplicationInfo();
String filePath = app.sourceDir;
int id = item.getItemId();
if (id == R.id.home)
{
// Handle the camera action
Intent a = new Intent(MainActivity.this,MainActivity.class);
startActivity(a);
}
else if (id == R.id.about)
{
Intent b = new Intent(MainActivity.this,About.class);
startActivity(b);
}
else if (id == R.id.nav_share)
{
Intent c = new Intent(Intent.ACTION_SEND);
c.setType("*/*");
String shareBody = "https://play.google.com/store/apps/details?id=com.jangphong.hem.karbicalender2";
String shareSub = "Download Karbi calendar 2019";
c.putExtra(Intent.EXTRA_SUBJECT,shareSub);
c.putExtra(Intent.EXTRA_TEXT,shareBody);
c.putExtra(Intent.EXTRA_STREAM,Uri.fromFile(new File(filePath)));
startActivity(Intent.createChooser(c,"Share using"));
}
else if (id == R.id.feedback)
{
Intent in = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.karbidigitalresources.tk"));
startActivity(in);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
}
This is the Manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jangphong.hem.karbicalender2">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_karbi_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_karbi_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar" />
<activity android:name=".About" />
<activity
android:name=".SplashScreen"
android:noHistory="true"
android:theme="#style/AppTheme.Splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".edit_text" />
<activity android:name=".feb" />
<activity android:name=".march" />
<activity android:name=".april" />
<activity android:name=".may" />
<activity android:name=".june" />
<activity android:name=".july" />
<activity android:name=".august" />
<activity android:name=".sep" />
<activity android:name=".oct" />
<activity android:name=".nov" />
<activity android:name=".dec"></activity>
</application>

Missing Navigation Drawer hamburger icon in Activity

I built a Navigation Drawer with fragments and an Activity. All the fragments have the icon and drawer access is smooth as butter, but there is nothing in the Activity. The Activity is the default "Home Page", so access to the Navigation Drawer is critical. Typically not calling toggle.syncState(); is the solution, but it fails in this case.
MainActivity:
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
DrawerLayout drawer = 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.setDrawerIndicatorEnabled(true);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
//Sets default fragment
Intent i = new Intent(MainActivity.this,GarageActivity.class);
startActivity(i);
navigationView.setCheckedItem(R.id.nav_garage);
}
//Name in Action bar
public void setActionBarTitle(String title) {
getSupportActionBar().setTitle(title);
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
Activity in question:
public class GarageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_garage);
getSupportActionBar().setTitle("My Garage");
}
}
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<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=".MainActivity"
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=".GarageActivity">
<meta-data
android:name="android.support.parent_activity"
android:value=".MainActivity"/>
</activity>
</application>
First you need to enable actionbar's Home button. Then Assign Hamburger icon to Home button and write code to open the drawer in his listener. following are the steps:
Get hamburger/menu icon:
In the Project window, right-click the res folder and select New > Vector Asset.
Select Material icon as the asset type and then click the Icon button to open the Select Icon window.
Search for "menu" and select the menu icon (the icon is 3 horizontal lines).
Click OK, and then rename the file to "ic_menu" and click Next to import it.
Enable "Home" button in actionbar:
add this code in your onCreate method:-
ActionBar actionbar = getSupportActionBar();
actionbar.setDisplayHomeAsUpEnabled(true);
actionbar.setHomeAsUpIndicator(R.drawable.ic_menu);
Add code in onOptionsItemSelected method:
first create global variable of DrawerLayout so you can access it in other methods. add reference to that variable in onCreate and use it in onOptionsItemSelected to open the drawer. following is the code:
public class MainActivity extends AppCompatActivity {
private DrawerLayout mDrawerLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDrawerLayout = findViewById(R.id.drawer_layout);
...
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
mDrawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
}
source Create Navigation Drawer

"Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set WindowActionBar to false in your theme to use a toolbar instead"

I get the error "Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set WindowActionBar to false in your theme to use a toolbar instead" whenever I try to run my app in the emulator on Android Studio and it crashes upon startup. I understand that this question has been asked before, but when I remove the extends AppCompatActivity as I am told to do in other posts it then gives me an error for the setSupportActionBar(toolbar) line a bit further down in the code.
As far as I understand this is an error with Android Studio getting confused about the native toolbar and the toolbar that I'm trying to implement. Perhaps I'm misunderstanding the crux of the problem? Why is it giving me an error for setSupportActionBar(toolbar) once I get rid of the extends statement?
The main activity is using the "AppTheme"
Thanks.
MainActivity Code for reference:
package com.treehouse.android.movies;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.GridView;
import android.widget.Toast;
import java.util.ArrayList;
//extends AppCompatActivity
public class MainActivity extends AppCompatActivity
{
static public ArrayList<Movie> moviesList;
static public ArrayList<String> images;
public String mostPopular="http://api.themoviedb.org/3/movie/popular?api_key=";
public String highRated="http://api.themoviedb.org/3/movie/top_rated?api_key=";
//Make both GridAdapter and GridView non-Static?
static public GridAdapter gridAdapter;
static public GridView gridView;
public static boolean connectionEnabled;
public Context currentContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
String result="";
moviesList=new ArrayList<>();
images=new ArrayList<>();
currentContext=getApplicationContext();
if (isNetworkAvailable()!= false) {
connectionEnabled=true;
getJsonData(0);
new GetMovies(currentContext);
gridView =(GridView) findViewById(R.id.moviesGridView);
gridAdapter =new GridAdapter(MainActivity.this,moviesList,images);
gridView.setAdapter(gridAdapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent movieIntent=new Intent(getApplicationContext(),DetailsActivity.class);
Log.i("Default position ", String.valueOf(position));
movieIntent.putExtra("position",position);
startActivity(movieIntent);
}
});
}
else{
Toast.makeText(this, "Network Is Not Available", Toast.LENGTH_LONG).show();
connectionEnabled=false;
}
}
public boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
//get json file
//0 for most popular
//1 for highest-rated
public void getJsonData(int searchBy){
GetMovies downloadTask=new GetMovies(currentContext);
try {
if (searchBy == 0 ){
downloadTask.execute(mostPopular);
}
else if(searchBy == 1){
downloadTask.execute(highRated);
}
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.mostpopular_button) {
if (isNetworkAvailable()!= false) {
new GetMovies(currentContext).execute(mostPopular);
gridAdapter.notifyDataSetChanged();
}
else{
Toast.makeText(this, "Network Is Not Available", Toast.LENGTH_LONG).show();
}
}
else if (id== R.id.highrated_button){
if (isNetworkAvailable()!= false) {
new GetMovies(currentContext).execute(highRated);
gridAdapter.notifyDataSetChanged();
}
else{
Toast.makeText(this, "Network Is Not Available", Toast.LENGTH_LONG).show();
}
}
return super.onOptionsItemSelected(item);
}
}
Styles Code for reference:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
<style name="AppTheme.NoActionBar">
<item name="windowActionBar">false</item>
<item name="windowNoTitle">true</item>
</style>
<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />
<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>
Manifest Code for reference:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.treehouse.android.movies" >
<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" part of application -->
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN"
android:theme="#style/AppTheme"
/>
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
change your style.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
</style>
replace to this :
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="windowActionBar">true</item>
<item name="windowNoTitle">true</item>
</style>
Since your Activity's theme is set to AppTheme, it comes with an "action bar" by default. When you then call setSupportActionBar(toolbar), your app crashes because you've already got an actionbar (from your theme).
Simply change your Activity's theme to AppTheme.NoActionBar in your manifest.

Android Action Bar and Menu Options are missing

I am having difficulty with showing my Action bar that is suppose to be at the top. Everytime I use a ListView, the ActionBar with all my menu options on top disappears on me. Can someone shed some light on why this happening with the ListView.
MainActivity Class:
public class MainActivity extends Activity {
ListView listView;
ArrayAdapter<String> adapter;
String[] android_versions = {"Cupcake",
"Donut",
"Eclair",
"Froyo",
"Gingerbread",
"Honeycomb",
"Ice Cream Sandwich",
"Jelly Bean",
"KitKat",
"Lollipop"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android_versions);
listView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.farrellequipment.www.listview" >
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Layout activity_main.xml file:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" tools:context=".MainActivity">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_gravity="left|top" />
</RelativeLayout>
Menu menu_main.xml file
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
<item android:id="#+id/action_settings" android:title="#string/action_settings"
android:orderInCategory="100" app:showAsAction="never" />
</menu>
Styles.xml file
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
</style>
</resources>
It is a simple straight forward app but I am missing the ActionBar and Menu Options I need for this app. Again can someone please shed some light on the problem. I have been searching this problem for about 4 hours now and I need help. Thank you in advance.
You just need to replace Activity to AppCompatActivity
public class MainActivity extends AppCompatActivity {
ListView listView;
ArrayAdapter<String> adapter;
String[] android_versions = {"Cupcake",
"Donut",
"Eclair",
"Froyo",
"Gingerbread",
"Honeycomb",
"Ice Cream Sandwich",
"Jelly Bean",
"KitKat",
"Lollipop"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android_versions);
listView.setAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Your #style/AppTheme probably extends a .NoActionBar theme, make sure that's not the case.
You should inherit your Activity from AppCompatActivity (https://developer.android.com/reference/android/support/v7/app/AppCompatActivity.html) from the Support Library instead from the plain Acitivty class.
You should also inherit your app theme from Theme.AppCompat.
See also Difference between extending LifecycleActivity,Activity,ActionbarActivity & AppCompactActivity?

Android Studio; Launching to USB Device (phone), installs but won't open

My application builds and says successful, but exits without launching when I open it on my phone. Is there something wrong with my manifest file?
Error: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.terik.thirdattempt/com.example.terik.thirdattempt.MainActivity}: android.view.InflateException: Binary XML file line #23: Error inflating class android.widget.Button
Here's the xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.terik.thirdattempt" >
<uses-sdk android:minSdkVersion="8" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Here's my layout for kicks and giggles.
<TextView android:layout_width="500dp"
android:layout_height="200dp"
android:text="0"
android:textSize="72pt"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_alignLeft="#+id/Button1"
android:layout_alignStart="#+id/Button1"
android:layout_marginLeft="41dp"
android:layout_marginStart="71dp"
android:layout_alignRight="#+id/Button1"
android:layout_alignEnd="#+id/Button1"></TextView>
<Button
android:layout_width="200dp"
android:layout_height="200dp"
android:id="#+id/Button1"
android:background="#drawable/custom_button"
android:adjustViewBounds="false"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="51dp" />
</RelativeLayout>
And I guess my MainActivity.java file
package com.example.terik.thirdattempt;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity {
int number = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.textView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void addOne(View view){
number = number +1;
textView.setText(number);
}
}
You got null pointer exception because you declare your textview before setcontent view. This should fix that (but i dont understand what method addOne is, so i leave that alone):
int number = 0;
TextView textView;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void addOne(View view){
number = number +1;
textView.setText(number);
}
You can initialize UI after setContentView(R.layout.activity_main) in the function of onCreate.
So your app crashed when you launched your device.You Should initialize the TextView after the function of onCreate like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView)findViewById(R.id.textView);
}

Categories