Custom window title and ActionBar - java

Why getActionBar() returns null?
I have custom window title in my app.
below my AndroidManifest.xml file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.map"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.example.map.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/customTheme" >
<activity
android:name="com.example.map.MainActivity"
android:configChanges="orientation|screenSize"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustResize"
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="com.example.map.MapActivity"
android:screenOrientation="portrait"
android:label="#string/app_name" >
</activity>
<activity
android:name="com.example.map.PersonalInformationActivity"
android:screenOrientation="portrait"
android:label="#string/app_name" >
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="MY_KEY" />
</application>
</manifest>
Problem with MainActivity.It works with ActionBar Tabs + Fragments (code below). In other Activities all work fine.
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.window_header);
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
String label1 = getResources().getString(R.string.label1);
Tab tab = actionBar.newTab();
tab.setText(label1);
TabListener<Login> tl = new TabListener<Login>(this, label1, Login.class);
tab.setTabListener(tl);
actionBar.addTab(tab);
String label2 = getResources().getString(R.string.label2);
tab = actionBar.newTab();
tab.setText(label2);
TabListener<Registration> tl2 = new TabListener<Registration>(this, label2, Registration.class);
tab.setTabListener(tl2);
actionBar.addTab(tab);
}
private class TabListener<T extends Fragment> implements ActionBar.TabListener {
private Fragment mFragment;
private final Activity mActivity;
private final String mTag;
private final Class<T> mClass;
public TabListener(Activity activity, String tag, Class<T> clz) {
mActivity = activity;
mTag = tag;
mClass = clz;
}
public void onTabSelected(Tab tab, FragmentTransaction ft) {
// Check if the fragment is already initialized
if (mFragment == null) {
// If not, instantiate and add it to the activity
mFragment = Fragment.instantiate(mActivity, mClass.getName());
ft.add(android.R.id.content, mFragment, mTag);
} else {
// If it exists, simply attach it in order to show it
ft.attach(mFragment);
}
}
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (mFragment != null) {
// Detach the fragment, because another one is being attached
ft.detach(mFragment);
}
}
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// User selected the already selected tab. Usually do nothing.
}
}
}
}

If you want to use ActionBar you need to request for the ActionBar
See the code below.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// The Action Bar is a window feature. The feature must be requested
// before setting a content view.
getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.main);
// experiment with the ActionBar
ActionBar actionBar = getActionBar();
actionBar.hide();
}

getActionBar() was introduced in API level 11. In your manifest, you claim your app will run on API level 8 as well. It won't.
Here are numerous reasons why the call may return null on a device with API >= 11.

I had similiar problem, i used to get error on the lines below, since
I was requesting the custom title feature before setting the content view.
setContentView(R.layout.userlayout);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE)
first request the feature and problem went away
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE)
setContentView(R.layout.userlayout);
Hope that is the solution you wanted..

Related

Admob ads loading but not showing

So in my LIBGDX game I'm trying to impement Admob ads.
They load fine but just wont show, even after a 60 second refresh or pressing home button and entering the game again.
I followed some answers on this site, but none of them helped.
Here's the code of Android Launcher class:
public class AndroidLauncher extends AndroidApplication implements AdHander{
private static final String TAG = "AndroidLauncher";
protected AdView adView;
private final int SHOW_ADS = 1;
private final int HIDE_ADS = 0;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
switch (msg.what){
case SHOW_ADS:
adView.setVisibility(View.VISIBLE);
break;
case HIDE_ADS:
adView.setVisibility(View.GONE);
break;
}
}
};
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout layout = new RelativeLayout(this);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new Main(this), config);
adView = new AdView(this);
adView.setAdSize(AdSize.SMART_BANNER);
// HERE I IMPLEMENTED ADMOB TEST ID FOR BANNERS
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
adView.setBackgroundColor(Color.BLACK);
adView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
int visibility = adView.getVisibility();
adView.setVisibility(AdView.GONE);
adView.setVisibility(visibility);
Log.i(TAG, "Ad loaded");
}
});
AdRequest.Builder builder = new AdRequest.Builder();
adView.loadAd(builder.build());
layout.addView(gameView);
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
adParams.addRule(RelativeLayout.ALIGN_PARENT_TOP);
adParams.addRule(RelativeLayout.ALIGN_PARENT_RIGHT);
layout.addView(adView, adParams);
setContentView(layout);
config.useImmersiveMode = true;
initialize(new Main(this), config);
}
#Override
public void showAds(boolean show) {
handler.sendEmptyMessage(show ? SHOW_ADS : HIDE_ADS);
}
}
What have I did wrong?
Check your manifest it should look similar to this one :-
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.serveroverload.recorder"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<!-- Include required permissions for Google Mobile Ads to run -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<!-- This meta-data tag is required to use Google Play Services. -->
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name="com.serveroverload.recorder.ui.HomeActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!--Include the AdActivity configChanges and theme. -->
<activity android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
</application>
</manifest>
#Override
public void showAds(boolean show) {
Message msg = new Message();
msg.what = show ? SHOW_ADS : HIDE_ADS;
handler.sendMessage(msg);
}

Activity reopens when a NFC Tag is found

I'm developing an app that should detect NFC tags.
My problem is that my activity reopens every time the app scans a tag. It should just open when the app is closed. But when it is active, I just want the data from the tag.
Manifest:
?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.corinna.nfc_testapp" >
<uses-permission android:name="android.permission.NFC" />
<uses-sdk android:minSdkVersion="14"/>
<uses-feature android:name="android.hardware.nfc" android:required="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
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>
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
</application>
</manifest>
Activity onCreate & handleIntent
rotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Fragment ReadOrWrite
fRead = (Fragment_Read) Fragment.instantiate(getApplicationContext(), Fragment_Read.class.getName(), null);
Fragment_ReadOrWrite fReadOrWrite = (Fragment_ReadOrWrite) Fragment.instantiate(getApplicationContext(), Fragment_ReadOrWrite.class.getName(), null);
fReadOrWrite.setFragment_Read(fRead);
FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.id_activity_main, fReadOrWrite);
fragmentTransaction.commit();
//NFC
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
handleIntent(getIntent());
}
private void handleIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
String type = intent.getType();
if (MIME_TEXT_PLAIN.equals(type)) {
Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
NdefReaderTask ndefReader = new NdefReaderTask(fRead);
ndefReader.execute(tag);
} else {
System.out.println("Wrong mime type: " + type);
}
}
}
Just use launchMode="singleTop" in your main activity manifest.
This will ensure that if your activity is at the top of your task stack, it will not be recreated.
Be aware that onCreate is no longer called in this case, so if you want to read the content from intent, you need to override the onNewIntent Activity method.

SearchView doesn't start Search Activity but searchbar opens

I'm having trouble creating the search feature for my application. I have followed various tutorials, followed the Android Docs, and other Stack Overflow answers with no success. I have the icon for the each in one activity (ContinentActivity.java) and when clicked the toolbar opens up a search window. However typing data does not register in the SearchResultsActivity. It is never created. Could this be because I am using a toolbar and a menu?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_swell_alert_logo"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<meta-data
android:name="android.app.default_searchable"
android:value=".SearchResultsActivity"/>
<activity
android:name=".SearchResultsActivity"
android:label="#string/app_name"
android:launchMode="singleTop">
<!-- to identify this activity as "searchable" -->
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data
android:name="android.appcompat.searchable"
android:resource="#xml/searchable" />
</activity>
<activity
android:name=".ui.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=".ui.locations.LocationSelectionActivity"
android:label="#string/title_activity_location_selection"
android:noHistory="true"
android:parentActivityName=".ui.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ui.MainActivity" />
</activity>
<activity
android:name=".ui.locations.ContinentActivity"
android:theme="#style/NoAnimationTheme"
android:label="#string/title_activity_continent"
android:parentActivityName=".ui.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ui.MainActivity" />
</activity>
<!-- Children of Continent Activity. Each have search capabilities-->
<activity
android:name=".ui.locations.CountryActivity"
android:theme="#style/NoAnimationTheme"
android:label="#string/title_activity_country"
android:parentActivityName=".ui.locations.ContinentActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ui.locations.ContinentActivity" />
</activity>
<activity
android:name=".ui.locations.StateActivity"
android:theme="#style/NoAnimationTheme"
android:label="#string/title_activity_state"
android:parentActivityName=".ui.locations.CountryActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ui.locations.CountryActivity" />
</activity>
<activity
android:name=".ui.locations.SurfSpotActivity"
android:theme="#style/NoAnimationTheme"
android:label="#string/title_activity_surf_spot"
android:parentActivityName=".ui.locations.StateActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".ui.locations.StateActivity" />
</activity>
</application>
SearchResultsActivity.java
public class SearchResultsActivity extends AppCompatActivity {
public static final String TAG = "SEARCH_RESULTS_ACTIVITY";
SearchResultsAdapter mSearchResultsAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.v(TAG, "onCreate");
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.v(TAG, "onNewIntent");
handleIntent(intent);
}
private void handleIntent(Intent intent) {
Log.v(TAG, "HANDLE INTENT");
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
showResults(query);
}
}
private void showResults(String query) {
// Query your data set and show results
// ...
Log.v(TAG, "Searching for " + query + "...");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.v(TAG, "onCreateOptionsMenu");
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_location, menu);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();
searchView.setSearchableInfo( searchManager.getSearchableInfo(getComponentName()) );
return true;
}
This activities menu has the search icon
ContinentActivity.java
public class ContinentActivity extends AppCompatActivity {
private ArrayList<Continent> mContinents;
#Bind(R.id.recyclerView) RecyclerView mRecyclerView;
#Bind(R.id.toolBar) Toolbar mToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location_selection);
ButterKnife.bind(this);
setSupportActionBar(mToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
LocationDataSource dataSource = new LocationDataSource(this);
dataSource.test();
mContinents = dataSource.readContinents();
ContinentAdapter adapter = new ContinentAdapter(this, mContinents);
mRecyclerView.setAdapter(adapter);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(layoutManager);
mRecyclerView.setHasFixedSize(true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_location, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
return super.onOptionsItemSelected(item);
}
}
menu_location.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:appcompat="http://schemas.android.com/apk/res-auto">
<item
android:id="#+id/action_search"
android:orderInCategory="200"
android:title="#string/action_settings"
android:icon="#drawable/ic_search_white_24dp"
appcompat:showAsAction="always"
appcompat:actionViewClass="android.widget.SearchView"/>
</menu>
tool_bar.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/ColorPrimary"
android:elevation="4dp"
android:theme="#style/Base.ThemeOverlay.AppCompat.Dark"
android:titleTextColor="#color/ColorText">
</android.support.v7.widget.Toolbar>
Seems you have missing call to associate SearchView with searchable info within the onCreateOptionsMenu() method? Quote from the training link http://developer.android.com/guide/topics/search/search-dialog.html
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
But since you are not using the same activity for search result, you cannot simply use getComponentName(), but to use new ComponentName(this, SearchResultsActivity.class)

Unable to instantiate activity ComponentInfo… java.lang.NullPointerException

OK, so the problem I'm having occurs when the startGame button is pressed. The app crashes when the button is pressed. The activity is instantiated in the manifest so I'm not sure where the error is. The code for the intent is a copy of the other one (which works) so I have no clue where I went wrong.
Error Log:
02-25 14:46:51.064: E/AndroidRuntime(1261): FATAL EXCEPTION: main
02-25 14:46:51.064: E/AndroidRuntime(1261): Process: com.example.hegemony, PID: 1261
02-25 14:46:51.064: E/AndroidRuntime(1261): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.hegemony/com.example.hegemony.PlayerTurn}: java.lang.NullPointerException
Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hegemony"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="11"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.hegemony.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="com.example.hegemony.StartScreen" >
<intent-filter>
<action android:name="com.example.hegemony.STARTSCREEN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.hegemony.SetupHomeScreen" >
<intent-filter>
<action android:name="com.example.hegemony.SETUPHOMESCREEN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.hegemony.SetupPlayer"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.hegemony.SETUPPLAYER" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name="com.example.hegemony.PlayerTurn"
android:label="#string/app_name" >
<intent-filter>
<action android:name="com.example.hegemony.PLAYERTURN" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
Java Code of sending activity:
public class SetupHomeScreen extends Activity{
private ArrayList<Player> p = GameMaster.players;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setup_home_screen);
getActionBar().hide();
updatePlayers();
Button gotoInput = (Button) findViewById(R.id.btnSetupPlayer);
gotoInput.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent toInput = new Intent("com.example.hegemony.SETUPPLAYER");
startActivity(toInput);
}
});
Button startGame = (Button) findViewById(R.id.btnStartGame);
startGame.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent toStart = new Intent("com.example.hegemony.PLAYERTURN");
startActivity(toStart);
}
});
}
public void updatePlayers(){
TextView playerList = (TextView) findViewById(R.id.playerList);
String msg = "";
for(int i=0;i < p.size();i++)
msg = msg + "\n - "+p.get(i).getName();
playerList.setText(msg);
if(p.size() >=2){
Button enable = (Button) findViewById(R.id.btnStartGame);
enable.setEnabled(true);
}
}
}
Java code of receiving activity:
public class PlayerTurn extends Activity {
final ActionBar actionBar = getActionBar();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_turn);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.TabListener tabListener = new ActionBar.TabListener() {
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
}
};
}
}
Button startGame = (Button) findViewById(R.id.btnStartGame);
startGame.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent toStart = new Intent(SendingActivity.this, NewActivity.class);
startActivity(toStart);
}
});
I think this is how you should start an intent. Maybe its missing a context or the "activityname" is not the right way to do it. I tried to start an activity the way you are trying and it gave me an error as well, not the same one, but it didn't work.
I'm sorry if the solution I'm trying to provide doesn't work. This is really the first time I'm trying to help someone. I hope it works.
As per the logcat error message, your activity class is failing to instantiate. Instantiation involves the allocation and assignment of any class member variables. In the case of PlayerTurn, the only one is this:
final ActionBar actionBar = getActionBar();
The call to getActionBar() throws a NullPointerException because the activity's window has not been built yet - you should call getActionBar() after setContentView() has been called in onCreate(). You can resolve this by simply moving that line of code into onCreate().
If you still want to retain this as a class member variable, declare it but don't assign it:
ActionBar actionBar;
...and then do the assignment in onCreate():
actionBar = getActionBar();

Errors in Android Studio myfirstapp : Gradle errors

I'm trying to follow along with the official Android tutorial (http://developer.android.com/training/basics/firstapp/starting-activity.html) but I'm failing miserably. Everything worked OK until I needed to add a second Activity. First, the Activity I created in Android Studio does not show up in my list of java files. I clicked New -> Activity and nothing appeared. To get around this I opened up Windows Explorer and copied/renamed MainActivity.java to DisplayMessageActivity.java and added the code in the tutorial.
After following along the app does not run and I get multiple "Gradle" errors such as:
Gradle: error: cannot find symbol class Activity
Gradle: error: cannot find symbol class Bundle
What do I need to fix in order to get this to run? Here is the relevant code:
MainActivity.java
package com.example.myfirstapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.content.Intent;
import android.widget.EditText;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
}
}
Display MessageActivity.java
package com.example.myfirstapp;
public class DisplayMessageActivity extends Activity {
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
// Make sure we're running on Honeycomb or higher to use ActionBar APIs
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
// Show the Up button in the action bar.
getActionBar().setDisplayHomeAsUpEnabled(true);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.example.myfirstapp.MainActivity"
android:label="#string/app_name"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
when you create an activity, make sure you insert it into mainifest.xml as well, so your manifest should be like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myfirstapp"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="16" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.example.myfirstapp.MainActivity"
android:label="#string/app_name"
android:parentActivityName="com.example.myfirstapp.MainActivity" >
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.myfirstapp.MainActivity" />
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.myfirstapp.MessageActivity>
</activity>
</application>
</manifest>
On each error you got (on red as on image) go and press Alt+Enter to import missing classes or declare the variables.
Please note that all files (.java) have to be not red underlined if they are error free.
Maybe some tutorial´s names of classes´s changed. then you need put the name your Activity before the variable "extra_message" like that MyActivity.EXTRA_MESSAGE
on the main Activity put...
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
or simple use any value. like that
String message = intent.getStringExtra('xxx');
Go on through the tutorial, you'll be taught to create one later.

Categories

Resources