Many responses over stackoverflow advised to import R. I did that and I made sure to rebuild/clean my path over 10 times before asking this question.
Here are how my files are arranged:
We can all clearly see the error lies somewhere between MainActivity file or XML file.
Here is the code for the MainActivity file , it is pretty much a copy from Google's git hub account and the ONLY error is it cannot identity what "R" is.:
package com.eatwithme;
/*
* Copyright (C) 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.eatwithme.activities.SampleActivityBase;
import com.eatwithme.logger.Log;
import com.eatwithme.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.PendingResult;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.location.places.Place;
import com.google.android.gms.location.places.PlaceBuffer;
import com.google.android.gms.location.places.Places;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.LatLngBounds;
public class MainActivity extends SampleActivityBase
implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks {
/**
* GoogleApiClient wraps our service connection to Google Play Services and provides access
* to the user's sign in state as well as the Google's APIs.
*/
protected GoogleApiClient mGoogleApiClient;
private PlaceAutocompleteAdapter mAdapter;
private AutoCompleteTextView mAutocompleteView;
private TextView mPlaceDetailsText;
private static final LatLngBounds BOUNDS_GREATER_SYDNEY = new LatLngBounds(
new LatLng(-34.041458, 150.790100), new LatLng(-33.682247, 151.383362));
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set up the Google API Client if it has not been initialised yet.
if (mGoogleApiClient == null) {
rebuildGoogleApiClient();
}
setContentView(R.layout.activity_main);
// Retrieve the AutoCompleteTextView that will display Place suggestions.
mAutocompleteView = (AutoCompleteTextView)
findViewById(R.id.autocomplete_places);
// Register a listener that receives callbacks when a suggestion has been selected
mAutocompleteView.setOnItemClickListener(mAutocompleteClickListener);
// Retrieve the TextView that will display details of the selected place.
mPlaceDetailsText = (TextView) findViewById(R.id.place_details);
// Set up the adapter that will retrieve suggestions from the Places Geo Data API that cover
// the entire world.
mAdapter = new PlaceAutocompleteAdapter(this, android.R.layout.simple_list_item_1,
BOUNDS_GREATER_SYDNEY, null);
mAutocompleteView.setAdapter(mAdapter);
// Set up the 'clear text' button that clears the text in the autocomplete view
Button clearButton = (Button) findViewById(R.id.button_clear);
clearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mAutocompleteView.setText("");
}
});
}
/**
* Listener that handles selections from suggestions from the AutoCompleteTextView that
* displays Place suggestions.
* Gets the place id of the selected item and issues a request to the Places Geo Data API
* to retrieve more details about the place.
*
* #see com.google.android.gms.location.places.GeoDataApi#getPlaceById(com.google.android.gms.common.api.GoogleApiClient,
* String...)
*/
private AdapterView.OnItemClickListener mAutocompleteClickListener
= new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
/*
Retrieve the place ID of the selected item from the Adapter.
The adapter stores each Place suggestion in a PlaceAutocomplete object from which we
read the place ID.
*/
final PlaceAutocompleteAdapter.PlaceAutocomplete item = mAdapter.getItem(position);
final String placeId = String.valueOf(item.placeId);
Log.i(TAG, "Autocomplete item selected: " + item.description);
/*
Issue a request to the Places Geo Data API to retrieve a Place object with additional
details about the place.
*/
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
Toast.makeText(getApplicationContext(), "Clicked: " + item.description,
Toast.LENGTH_SHORT).show();
Log.i(TAG, "Called getPlaceById to get Place details for " + item.placeId);
}
};
/**
* Callback for results from a Places Geo Data API query that shows the first place result in
* the details view on screen.
*/
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
= new ResultCallback<PlaceBuffer>() {
#Override
public void onResult(PlaceBuffer places) {
if (!places.getStatus().isSuccess()) {
// Request did not complete successfully
Log.e(TAG, "Place query did not complete. Error: " + places.getStatus().toString());
return;
}
// Get the Place object from the buffer.
final Place place = places.get(0);
// Format details of the place for display and show it in a TextView.
mPlaceDetailsText.setText(formatPlaceDetails(getResources(), place.getName(),
place.getId(), place.getAddress(), place.getPhoneNumber(),
place.getWebsiteUri()));
Log.i(TAG, "Place details received: " + place.getName());
}
};
private static Spanned formatPlaceDetails(Resources res, CharSequence name, String id,
CharSequence address, CharSequence phoneNumber, Uri websiteUri) {
Log.e(TAG, res.getString(R.string.place_details, name, id, address, phoneNumber,
websiteUri));
return Html.fromHtml(res.getString(R.string.place_details, name, id, address, phoneNumber,
websiteUri));
}
/**
* Construct a GoogleApiClient for the {#link Places#GEO_DATA_API} using AutoManage
* functionality.
* This automatically sets up the API client to handle Activity lifecycle events.
*/
protected synchronized void rebuildGoogleApiClient() {
// When we build the GoogleApiClient we specify where connected and connection failed
// callbacks should be returned, which Google APIs our app uses and which OAuth 2.0
// scopes our app requests.
mGoogleApiClient = new GoogleApiClient.Builder(this)
.enableAutoManage(this, 0 /* clientId */, this)
.addConnectionCallbacks(this)
.addApi(Places.GEO_DATA_API)
.build();
}
/**
* Called when the Activity could not connect to Google Play services and the auto manager
* could resolve the error automatically.
* In this case the API is not available and notify the user.
*
* #param connectionResult can be inspected to determine the cause of the failure
*/
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(TAG, "onConnectionFailed: ConnectionResult.getErrorCode() = "
+ connectionResult.getErrorCode());
// TODO(Developer): Check error code and notify the user of error state and resolution.
Toast.makeText(this,
"Could not connect to Google API Client: Error " + connectionResult.getErrorCode(),
Toast.LENGTH_SHORT).show();
// Disable API access in the adapter because the client was not initialised correctly.
mAdapter.setGoogleApiClient(null);
}
#Override
public void onConnected(Bundle bundle) {
// Successfully connected to the API client. Pass it to the adapter to enable API access.
mAdapter.setGoogleApiClient(mGoogleApiClient);
Log.i(TAG, "GoogleApiClient connected.");
}
#Override
public void onConnectionSuspended(int i) {
// Connection to the API client has been suspended. Disable API access in the client.
mAdapter.setGoogleApiClient(null);
Log.e(TAG, "GoogleApiClient connection suspended.");
}
}
Also, Here is my my Android Manifest file (with my key removed). Please notice my activity's name. I did so cause if I remove the com.eatwithme before the activity's name, it gives me an error.
<?xml version="1.0" encoding="UTF-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.google.playservices.placecomplete"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="19"/>
<!-- PlacePicker also requires OpenGL ES version 2 -->
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
<application
android:allowBackup="true"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version"/>
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AnLE"/>
<activity
android:name="com.eatwithme.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>
I have personally tried my level best but sadly, I am unable to resolve this conflict. The only three sources of error in my opinion could be
1) Have no R file
2) AndoridManifest file is not right
3) Main file isnt right
4) The order of file isnt right
Any guidance on this issue?
The problem lies in your xml manifest here:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
Wrong --> package="com.example.google.playservices.placecomplete"
android:versionCode="1"
android:versionName="1.0">
It needs to be the exact package name of your project which is:
package="com.eatwithme"
not the google sample package name.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.google.playservices.placecomplete"
Change this package name to your package name i.e.com.eatwithme package.
I didn't read through all your code - sorry :)
I recommend removing your import of R. If you're sure you have all your files in the right places, do as #AbhishekVasisht suggested and "clean project" (in Android Studio you click Build > Clean Project; I forget where it is in Eclipse).
If that doesn't work, you can also try what's called "invalidate caches and restart." This is a little extreme because it gets rid of your local history for the project, but it sounds like you've reached a point of desperation. In Android Studio, you click File > Invalidate Caches / Restart... and you want to select the option that invalidates AND restarts all in the same action.
As a last resort, you could try to import your existing code as a new Android project. This is a crap shoot but it's worked for me a couple times in the past.
Good luck! Sorry man, I know how frustrating this one can be.
if you are beginner in udacity android app development and learning lesson 2A /5th topic and problem occur in running MainActivity.java code compiletion then put below code in MainActivity.java
code is given below
package com.example.android.justjava;
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 {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void submitOrder(View view) {
display(1);
}
private void display(int number) {
TextView quantityTextView = (TextView) findViewById(
R.id.quanity_text_view);
quantityTextView.setText("" + number);
}
#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);
}
}
I don't have enough references to add comments, otherwise this would be a comment.
From my personal experience, try doing a "clean and rebuild", this sometime clears this error.
Hope some other people can back me up with this
Make sure all your XML files have valid resources, images and stuff and Clean project.
I updated my project from GitBucket and one .png was missing somehow so i got that error and that R was missing. I concentrated on resolving R issue and wasted couple of hours on that and when i put random .png instead the missing one and cleaned the project, the R got back.
Late answer, and another solution. Thought anyone need it.
I was using gradle 3.3.0. It was the main culprit. Wasted 6.50 hours from my life. Gradle 3.2.1 removed the error.
classpath 'com.android.tools.build:gradle:3.2.1'
I faced the same problem. My solution was that the directory path under which I saved my project was too long.
My Android app is simple. It has only 1 activity. I created two layouts for the same activity: one for the portrait position (inside the res/layout folder) and one for the landscape position (inside the res/layout-land folder). I give the code for both at the end of this question.
I have nothing special inside the myActivity.java file, I just inflate the layout:
package com.example.myApp;
import android.app.Activity;
import android.os.Bundle;
public class MCentralActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_myActivity);
}
}
Everything works fine at this point. If I hold my device in the portrait position, the app will call the appropriate XML. It works like a charm too, in case I decide to hold it in the landscape position.
The problem arises when I decide to add a little bit of code to the aforementioned myActivity.java file; it is still really simple!
package com.example.myApp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
public class MCentralActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
ImageButton ibPacientes;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_myActivity);
ibPacientes = (ImageButton)findViewById(R.id.imageButton_Pacientes);
ibPacientes.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//NOTHING INSIDE HERE!!
}
});
}
}
After implementing that little code, if I decide to go landscape, the App will stop abruptly saying "Unfortunately myApp has stopped". Interesting enough this won't occur if I don't implement onClickListener!
The exact error given by LogCat is as shown:
03-28 13:39:27.870: E/SurfaceFlinger(157): DRAW orientation 1 viewport:(0, 0, 1920, 1080) frame(0, 0, 1920, 1080)
03-28 13:39:15.360: E/SurfaceFlinger(157): STATE orientation 1 viewport:(0, 0, 1920, 1080) frame(0, 0, 1920, 1080)
03-28 13:39:15.360: I/SurfaceFlinger(157): ######## orientation:1, transformOri:4
Don't think the layout XML files has to do much in my problem, but I will copy and paste them in this link (for portrait) and this other link (for landscape), in order to not to make this question excessively long.
Thanks in advance!
In your landscape XML file you have the ImageButton called imageButton_Users instead of imageButton_Pacientes. Rename it and everything should work fine.
You're trying to find a view that's not there and so your app will crash.
I am trying to hide status bar but it is not working for me.
I tried to add
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
In AndroidManifest.xml But it is not working.
I also tried to add
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
In onCreate function
But nothing is working.
I am using phonegap build.
First time when i open my application status bar goes away but after 1 sec it comes back.
Can anyone help me?
I fix it.
In onCreate function i add this lines
this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
Now status bar is hidden...
Oficial way: https://developer.android.com/training/system-ui/status.html
And you can try this:
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
Try that. You can check here: How to hide status bar in Android
You can do it by two ways
1) Programatically :
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
public class ActivityName extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// remove title
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
}
}
2) Modifying AndroidManifest.xml file:
<activity android:name=".ActivityName"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen">
</activity>
Just turn off the battery saver mode.
I want to show the application window in full screen where it looks like a game screen...
Please help me..
package play.lear.com;
import org.apache.cordova.DroidGap;
import android.os.Bundle;
import android.view.WindowManager;
public class PlayActivity extends DroidGap {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
super.setIntegerProperty("splashscreen", R.drawable.splash);
super.loadUrl("file:///android_asset/www/index.html", 10000);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
}
}
There's a flag you can set in config.xml for full screen
<preference name="fullscreen" value="true" />
Phonegap's Notification has nothing to do with push notification.
Check this for integrating Pushwoosh for Android with Phonegap
I have 2 classes for an Android project.
The first class is the Activity and the second class is just a OnClickListener which implements the interface.
If I run the project on my phone I always get an runtime error.
Also I got the message:
The specified activity does not exist! Getting the launcher activity.
Here are my two classes
SendActivity
package kops.sms;
//import android.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.widget.Button;
public class SendActivity extends Activity {
Button buttonSend= (Button) findViewById(R.id.buttonSend);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
buttonSend.setOnClickListener(new ButtonListener());
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.send, menu);
return true;
}
}
and the ButtonListener
package kops.sms;
import android.view.View;
import android.view.View.OnClickListener;
public class ButtonListener implements OnClickListener {
#Override
public void onClick(View v)
{
}
}
I donĀ“t know what is wrong...
I look forward to your replies! :)
You cannot call findViewById() until after you call setContentView(). Please move:
Button buttonSend= (Button) findViewById(R.id.buttonSend);
to after:
setContentView(R.layout.activity_send);
and before:
buttonSend.setOnClickListener(new ButtonListener());
Also, in the future, please use LogCat (e.g., in the DDMS perspective in Eclipse) to examine the Java stack trace associated with your crashes. You would have been told about your NullPointerException, and that may have helped you to fix your problem.
Be sure that your Activity is declared in your manifest. Also, change your onCreate()
public class SendActivity extends Activity {
Button buttonSend;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send);
buttonSend = (Button) findViewById(R.id.buttonSend);
buttonSend.setOnClickListener(new ButtonListener());
}
You can't call a View such as a Button before you call setContentView() as it exists in your Layout and you haven't inflated your Layout until you call setContentViewe().
If these don't fix your problem then please post Logcat
Edit
Unless I missed it, you need to have all of your Activitys in your manifest. Something like:
<activity
android:name="your.package.name.SendActivity"
// activity attributes such as config changes, lable, etc...
</activity>
Logcat
Logcat output can be one of the most important pieces to determining a crash. It lists what the error was and a line number with activity where the problem occurred. If using Eclipse,
Window-->Show View-->Other-->Android-->Logcat
If you copy/paste the Logcat using coding brackets, it makes getting help much easier. You can also set filters for the logs so you don't get every single message and it is much more manageable. For example, I have a filter with: Filter Name: Runtime, by Log Tag: AndroidRuntime, by Log Level: error. This gives me only error messages for runtime errors/crashes. These filters are on the left side of the logcat view. Hope this helps