[英]Android - Cannot resolve symbol “R”
堆棧溢出的許多響應建議導入R.我做到了 在提出這個問題之前,我確保重建/清理我的路徑超過10次。
以下是我的文件排列方式:
我們都可以清楚地看到錯誤位於MainActivity
文件或XML文件之間。
以下是MainActivity
文件的代碼,它幾乎是Google的git hub帳戶的副本,唯一的錯誤是它無法識別“R”是什么:
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.");
}
}
另外,這是我的Android Manifest文件(刪除了我的密鑰)。 請注意我活動的名稱。 我這樣做是因為如果我在活動名稱之前刪除com.eatwithme
,它會給我一個錯誤。
<?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>
我親自嘗試過我的水平,但遺憾的是,我無法解決這個沖突。 我認為唯一的三個錯誤來源可能是
1)沒有R文件
2)AndoridManifest文件不對
3)主文件不對4)文件順序不對
關於這個問題的任何指導?
問題在於你的xml清單:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
Wrong --> package="com.example.google.playservices.placecomplete"
android:versionCode="1"
android:versionName="1.0">
它必須是項目的確切包名,即:
package="com.eatwithme"
不是谷歌樣本包名稱。
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.google.playservices.placecomplete"
將此包名稱更改為包名稱iecom.eatwithme包。
我沒有讀完你的所有代碼 - 抱歉:)
我建議刪除你的R導入。如果你確定你的所有文件都在正確的位置,請按@AbhishekVasisht建議和“清理項目”(在Android Studio中單擊Build> Clean Project;我忘記它在哪里日食)。
如果這不起作用,您還可以嘗試所謂的“使緩存無效並重新啟動”。 這有點極端,因為它擺脫了你當地的項目歷史,但聽起來你已經到了絕望的地步。 在Android Studio中,單擊“文件”>“使緩存/重新啟動無效...”,並且要在同一操作中選擇使“無效”和“重新啟動”的選項。
作為最后的手段,您可以嘗試將現有代碼導入為新的Android項目。 這是一個廢話,但它在過去幾次對我有用。
祝好運! 對不起,我知道這個人有多么沮喪。
如果你是udacity初學者Android應用程序開發和學習課2A / 5主題和問題發生在運行MainActivity.java代碼編譯然后將下面的代碼放在MainActivity.java代碼中給出如下
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);
}
}
我沒有足夠的參考來添加評論,否則這將是一個評論。
根據我的個人經驗,嘗試進行“清理和重建”,這有時會清除此錯誤。
希望其他人可以支持我
確保所有XML文件都包含有效的資源,圖像和內容以及Clean項目。
我從GitBucket更新了我的項目,一個.png因某種原因丟失了,所以我得到了這個錯誤並且R丟失了。 我集中精力解決R問題並浪費了幾個小時,當我把隨機的.png代替丟失的那個並清理項目時,R回來了。
遲到的答案,另一個解決方案。 以為任何人都需要它。
我使用的是gradle 3.3.0。 這是罪魁禍首。 從我的生命中浪費了6.50小時。 Gradle 3.2.1刪除了錯誤。
classpath 'com.android.tools.build:gradle:3.2.1'
我遇到了同樣的問題。 我的解決方案是我保存項目的目錄路徑太長了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.