开发者

Android development: "R cannot be resolved", but in only one context within the class

开发者 https://www.devze.com 2023-01-29 02:38 出处:网络
I\'m following along fairly closely in my code with Lauren Darcy\'s Teach Yourself Android Application Development in 24 Hours. I\'ve hit a snag with \"R cannot be resolved.\" on one line:

I'm following along fairly closely in my code with Lauren Darcy's Teach Yourself Android Application Development in 24 Hours. I've hit a snag with "R cannot be resolved." on one line:

final View layout=inflater.inflate(R.layout.password_dialog, (ViewGroup) findViewById(R.id.root));

The "R cannot be resolved" shows up on this line twice, once for each reference to R.

  • if I copy and paste the author's code, I get the same result, so it's not a typo
  • from reading posts of others who have encountered this same issue, it sounds like R is not resolved anywhere in the class. However, I do use R in other contexts in this class without any objection and with expected results.
  • another common piece of advice is to verify that I'm not importing android.R. I'm not.

At wit's end here... where should I be looking?

The class in full:

package com.oneinfinity.btdt;

import java.util.Calendar;


import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.text.format.DateFormat;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android开发者_运维问答.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class QuizSettingsActivity extends QuizActivity {
    SharedPreferences mGameSettings;
    static final int DATE_DIALOG_ID=0;
    static final int PASSWORD_DIALOG_ID=1;


    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.settings);
        mGameSettings=getSharedPreferences(GAME_PREFERENCES, MODE_PRIVATE);
        initTextField(R.id.etNickname, GAME_PREFERENCES_NICKNAME);
        initTextField(R.id.etEmail, GAME_PREFERENCES_EMAIL);
        writeBirthday();
        Button setPass=(Button) findViewById(R.id.ButtonPassword);
        Button setBd=(Button) findViewById(R.id.ButtonBirthday);
        setPass.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //TODO - password dialog
                Toast.makeText(QuizSettingsActivity.this, "TODO: Password form", Toast.LENGTH_LONG).show();
            }
        });
        setBd.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                //TODO - birthday dialog
                //Toast.makeText(QuizSettingsActivity.this, "TODO: birthday form", Toast.LENGTH_LONG).show();
                showDialog(DATE_DIALOG_ID);
            }
        });
        setSpinner(R.id.spinnerGender, R.array.genderSet, GAME_PREFERENCES_GENDER);
    }

    private void setSpinner(int whichSpinner, int whichArray, String whichPref) {
        final String PutString=whichPref;
        final Spinner spinner=(Spinner) findViewById(whichSpinner);
        ArrayAdapter<?> adapter=ArrayAdapter.createFromResource(this, whichArray, android.R.layout.simple_spinner_item);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner.setAdapter(adapter);
        if(mGameSettings.contains(PutString)) {
            int toSelect=mGameSettings.getInt(PutString, 0);
            spinner.setSelection(toSelect);
        }
        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> parent, View itemSelected, int selectedItemPosition, long selectedId) {
                    Editor editor = mGameSettings.edit();
                    editor.putInt(PutString, selectedItemPosition);
                    editor.commit();
                    //test whether committed
                    if(mGameSettings.contains(PutString)) {
                        Log.i("trace", "gender is set to " + mGameSettings.getInt(PutString, 0)+"");                
                    }
                    else {
                        Log.i("trace", "gender has not been specied yet");
                    }
                }
                public void onNothingSelected(AdapterView<?> parent) {
                    Toast.makeText(QuizSettingsActivity.this, "TODO:handle nothing selected", Toast.LENGTH_LONG).show();
                }
            });
    }


    private void initTextField(int whichField, String whichSetting) {
        final String PutSetting=whichSetting;
        final EditText findField=(EditText) findViewById(whichField);
        if(mGameSettings.contains(PutSetting)) {
            String textString=mGameSettings.getString(PutSetting, "");
            findField.setText(textString);
        }
        findField.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if((event.getAction()==KeyEvent.ACTION_DOWN) && (keyCode==KeyEvent.KEYCODE_ENTER)) {
                    String strValueToSave=findField.getText().toString();
                    Editor editor = mGameSettings.edit();
                    editor.putString(PutSetting, strValueToSave);
                    editor.commit();
                    return true;
                }
                return false;
            }
        });

    }

    /* Just in case it really is necessary to repeat these instructions
    private void initnicknameEntry() {
        final EditText nicknameText=(EditText) findViewById(R.id.etNickname);
        nicknameText.setOnKeyListener(new View.OnKeyListener() {
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if((event.getAction()==KeyEvent.ACTION_DOWN) && (keyCode==KeyEvent.KEYCODE_ENTER)) {
                    String strValueToSave=nicknameText.getText().toString();
                    return true;
                }
                return false;
            }
        });
    }
    */

    @Override
    protected Dialog onCreateDialog(int id) {
        switch(id) {
            case DATE_DIALOG_ID:
                DatePickerDialog dateDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { 
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { 
                        TextView dob=(TextView) findViewById(R.id.TextView_Bday_Info);
                        Time dateOfBirth=new Time();
                        dateOfBirth.set(dayOfMonth, monthOfYear, year);
                        long dtDob = dateOfBirth.toMillis(true);
                        dob.setText(DateFormat.format("MMMM dd, yyyy", dtDob));
                        Editor editor=mGameSettings.edit();
                        editor.putLong(GAME_PREFERENCES_DOB, dtDob);
                        editor.commit();

                    }
                }, 0, 0, 0 );
            return dateDialog;
            case PASSWORD_DIALOG_ID:
                //create the dialog
                LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                final View layout=inflater.inflate(R.layout.password_dialog, (ViewGroup) findViewById(R.id.root));
                //return the dialog;
        }
        return null;
    }

    @Override 
    protected void onPrepareDialog(int id, Dialog dialog) {
        switch(id) {
        case DATE_DIALOG_ID:
            DatePickerDialog dateDialog = (DatePickerDialog) dialog;
            int iDay, iMonth, iYear;
            if(mGameSettings.contains(GAME_PREFERENCES_DOB)) {
                long bd=mGameSettings.getLong(GAME_PREFERENCES_DOB, 0);
                Time birthday=new Time();
                birthday.set(bd);
                iDay=birthday.monthDay;
                iMonth=birthday.month;
                iYear=birthday.year;
                Log.i("trace", "verifying that it is no longer the year 2");
            }
            else {
                Calendar cal=Calendar.getInstance();
                iDay=cal.get(Calendar.DAY_OF_MONTH);
                iMonth=cal.get(Calendar.MONTH);
                iYear=cal.get(Calendar.YEAR);
            }
            dateDialog.updateDate(iYear, iMonth, iDay);
            return;
        case PASSWORD_DIALOG_ID:
            //prepare the dialog
            return;         
        }
    }

    private void writeBirthday() {
        TextView dob=(TextView) findViewById(R.id.TextView_Bday_Info);
        CharSequence myBirthday=getResources().getString(R.string.no_birthday);
        if(mGameSettings.contains(GAME_PREFERENCES_DOB)) {
            long bd=mGameSettings.getLong(GAME_PREFERENCES_DOB, 0);
            myBirthday=DateFormat.format("MMMM dd, yyyy", bd);
        }
        dob.setText(myBirthday);
    }
}


Try going to Project -> Clean, run that. Then go to Project -> Build Project. You may need to uncheck "Build Automatically" first.


I would take Janus advice and remove imports Android.R; but replace with your.package.name.R; and will fix. =)


I can see two things a novice can fail in :

  1. the xxx.xml is no lower case.
  2. when you needed to write the sdk version what did you typed ?see this notice for the api level part


i have had some of these problems sometimes when i started with android. What i did was definitely check my imports. Should be, like they say, your_package_name.R and not Android.

Allso check if you manifest is good. And what works most of the time, its just simply restart Android Studio.

Good luck mate!

0

精彩评论

暂无评论...
验证码 换一张
取 消