Ошибка открытия файла трассировки. Нет такого файла или каталога [2]

1

Я действительно очень новый с java и Android, и я в основном самоучка. Мне нужна помощь в решении этой проблемы. Это может быть что-то действительно глупое, очевидное или немое, но эй, я должен начать где-то вправо? Мое приложение падает при запуске. Я получаю это сообщение в logcat после того, как попытаюсь запустить мое приложение.

Это мой код, его упражнение, в котором я должен был сделать небольшое приложение, где вы показываете некоторые страны, и вы вводите их в капители. Im использует 3 кнопки, 2 текстовых изображения и 1 редактор.

MainActivity.java

    public class MainActivity extends Activity {
public int cuenta = 0;
public TextView questionlabel = (TextView) findViewById(R.id.textView1);
public TextView resultadolabel = (TextView) findViewById(R.id.textView2);
public Button startbutton = (Button) findViewById(R.id.button1);
public Button checkbutton = (Button) findViewById(R.id.button2);
public Button nextbutton = (Button) findViewById(R.id.button3);
public EditText inputbox = (EditText) findViewById(R.id.editText1);

public String[] mPaises = {
        "Canada",
        "Estados Unidos",
        "Mexico",
        "Guatemala",
        "Belice"};

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    startbutton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            //start button
    questionlabel.setText(mPaises[cuenta]);
        }});

    checkbutton.setOnClickListener(new View.OnClickListener() {


        @Override
        public void onClick(View v) {
            // check button
            if (cuenta == 0) {
                if (inputbox.toString() == "Ottawa") {
                    resultadolabel.setText("Correcto");}
                else {resultadolabel.setText("Respuesta correcta: Ottawa");}}
            else if (cuenta == 1) {
                if (inputbox.toString() == "Washington") {
                    resultadolabel.setText("Correcto");}
                else {resultadolabel.setText("Respuesta correcta: Washington");}}
            else if (cuenta == 2) {
                if (inputbox.toString() == "Mexico") {
                    resultadolabel.setText("Correcto");}
                else {resultadolabel.setText("Respuesta correcta: Mexico");}}
            else if (cuenta == 3) {
                if (inputbox.toString() == "Guatemala") {
                    resultadolabel.setText("Correcto");}
                else {resultadolabel.setText("Respuesta correcta: Guatemala");}}
            else if (cuenta == 4) {
                if (inputbox.toString() == "Belmopan") {
                    resultadolabel.setText("Correcto");}
                else {resultadolabel.setText("Respuesta correcta: Belmoopan");}}
        }
    });

    nextbutton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // LO QUE HACE EL NEXT BUTTON
            cuenta = cuenta + 1;
            questionlabel.setText(mPaises[cuenta]);


        }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

Это мой Activity_Main

    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<EditText
    android:id="@+id/editText1"
    android:inputType="text"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="129dp"
    android:ems="10" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/editText1"
    android:layout_alignLeft="@+id/editText1"
    android:layout_marginBottom="42dp"
    android:layout_marginLeft="16dp"
    android:text="@string/Start" />

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/button1"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="63dp"
    android:text="@string/pais" />

<Button
    android:id="@+id/button2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/button1"
    android:layout_alignBottom="@+id/button1"
    android:layout_toRightOf="@+id/button1"
    android:text="@string/check" />

<Button
    android:id="@+id/button3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/button2"
    android:layout_toRightOf="@+id/button2"
    android:text="@string/next" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/button1"
    android:layout_alignLeft="@+id/textView1"
    android:layout_marginBottom="21dp"
    android:text="@string/mensaje" />

И мой манифест

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.capitales.del.mundo"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

  • 0
    В чем ошибка?
Теги:

2 ответа

1

Вам нужно сначала раздуть ваш макет, а затем извлечь элементы интерфейса, иначе findViewById возвращает null и, следовательно, ваш сбой приложения, вызванный NullPointerException в этой строке:

startbutton.setOnClickListener


Поэтому setContentView(R.layout.activity_main); макет с помощью setContentView(R.layout.activity_main); а затем получить элементы пользовательского интерфейса.
public TextView questionlabel;
public TextView resultadolabel;
public Button startbutton;
public Button checkbutton;
public Button nextbutton;
public EditText inputbox;    

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    questionlabel = (TextView) findViewById(R.id.textView1);
    resultadolabel = (TextView) findViewById(R.id.textView2);
    startbutton = (Button) findViewById(R.id.button1);
    checkbutton = (Button) findViewById(R.id.button2);
    nextbutton = (Button) findViewById(R.id.button3);
    inputbox = (EditText) findViewById(R.id.editText1);
    /****/
}

Заметки:

  • if (inputbox.toString() == "Ottawa") Не сравнивайте содержимое Strings с использованием ==. Вместо этого используйте equals().
  • См. Как сравнить строки в Java?
  • В следующий раз включите свой логарифм в вопросе
0

Напишите все коды после этих двух строк,

super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

Потому что как вы можете получить идентификатор или элемент до его создания.

Но вы можете объявить его перед этим. Но получение идентификатора должно быть после создания активности.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню