【问题标题】:Android - Cannot resolve symbol "R"Android - 无法解析符号“R”
【发布时间】:2015-04-23 04:18:19
【问题描述】:

许多关于 stackoverflow 的回复建议导入 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 清单文件(已删除我的密钥)。请注意我的活动名称。我这样做是因为如果我删除活动名称前的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) 文件顺序不对

关于这个问题的任何指导?

【问题讨论】:

    标签: java android xml android-activity


    【解决方案1】:

    问题在于您的 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"
    

    不是 google 示例包名称。

    【讨论】:

    • 老实说,在同一个文件上工作了 8 多个小时后,我很惭愧我没有注意到那个错误。谢谢:D
    • 让我看看是否解决了它(希望应该)
    • 你是我的救星!我为自己的错误感到非常羞耻哈哈!我会尽快接受您的回答! :)
    【解决方案2】:
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
       package="com.example.google.playservices.placecomplete"
    

    将此包名称更改为您的包名称,即 com.eatwithme 包。

    【讨论】:

      【解决方案3】:

      我没有通读您的所有代码 - 抱歉 :)

      我建议删除您对 R 的导入。如果您确定所有文件都在正确的位置,请按照 @Abhishekvasisht 的建议和“清理项目”执行(在 Android Studio 中,您单击构建 > 清理项目;我忘记了在哪里它在 Eclipse 中)。

      如果这不起作用,您还可以尝试所谓的“使缓存无效并重新启动”。这有点极端,因为它摆脱了项目的本地历史,但听起来你已经到了绝望的地步。在 Android Studio 中,您单击 File > Invalidate Caches / Restart... 并且您想要选择在同一操作中使所有内容无效并重新启动的选项。

      作为最后的手段,您可以尝试将现有代码作为新的 Android 项目导入。这是一个废话拍摄,但过去它对我有用过几次。

      祝你好运!对不起,伙计,我知道这会是多么令人沮丧。

      【讨论】:

        【解决方案4】:

        如果您是 udacity android 应用程序开发和学习课程 2A/5th 主题的初学者,并且在运行 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);
                }
            }
        

        【讨论】:

          【解决方案5】:

          我没有足够的引用来添加 cmets,否则这将是一个评论。

          根据我的个人经验,尝试“清理并重建”,这有时会清除此错误。

          希望其他人可以支持我

          【讨论】:

          • 恐怕我这样做了超过 10 次。在过去的两个小时里,这就是我所做的一切,因为我几乎迷路了。不过谢谢你的建议! :D
          【解决方案6】:

          确保您的所有 XML 文件都具有有效的资源、图像和内容以及清理项目。

          我从 GitBucket 更新了我的项目,但不知何故丢失了一个 .png,所以我得到了那个错误并且 R 丢失了。我专注于解决 R 问题并为此浪费了几个小时,当我将随机的 .png 替换为丢失的一个并清理项目时,R 又回来了。

          【讨论】:

            【解决方案7】:

            迟到的答案,另一种解决方案。认为有人需要它。

            我使用的是 gradle 3.3.0。这是罪魁祸首。浪费了我生命中的 6.50 小时。 Gradle 3.2.1 消除了这个错误。

            classpath 'com.android.tools.build:gradle:3.2.1'
            

            【讨论】:

              【解决方案8】:

              我遇到了同样的问题。我的解决方案是我保存项目的目录路径太长。

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 2016-10-26
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2018-05-14
                • 2016-08-23
                • 1970-01-01
                • 2023-03-03
                相关资源
                最近更新 更多