функция щелчка не работает в моем приложении

#java #android

#java #Android

Вопрос:

Я пытаюсь показать другое действие, нажав кнопку с классом Intent, но он по-прежнему выдает ошибку, которая

» к сожалению, мое приложение остановилось»

и я думаю, что код правильный

это `основной класс активности

     course=(EditText) findViewById(R.id.editText);
    hour=(EditText) findViewById(R.id.editText1);
    add= (Button) findViewById(R.id.button);
    view_= (Button) findViewById(R.id.button1);

    view_.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(MainActivity.this,ViewActivity.class);
            startActivity(intent);
        }
    });

}
}
  

и это класс ViewActivity

 TextView tv;
Button ed, de, view_;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.view);

    tv = (TextView) findViewById(R.id.details);
    ed = (Button) findViewById(R.id.ed);
    de = (Button) findViewById(R.id.delete);
    view_= (Button) findViewById(R.id.button1);
    Intent intent = getIntent();

    view_.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    });
}
  

Кроме того, я добавил .ViewActivity на AndroidManifest.xml

 <application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name=".MainActivity" >

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

locat >>

 FATAL EXCEPTION: main
                                                                        Process: com.example.android.intent, PID: 11316
                                                                        java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.android.intent/com.example.android.intent.ViewActivity}: java.lang.NullPointerException
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2184)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233)
                                                                            at android.app.ActivityThread.access$800(ActivityThread.java:135)
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                            at android.os.Looper.loop(Looper.java:136)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5001)
                                                                            at java.lang.reflect.Method.invokeNative(Native Method)
                                                                            at java.lang.reflect.Method.invoke(Method.java:515)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
                                                                            at dalvik.system.NativeStart.main(Native Method)
                                                                         Caused by: java.lang.NullPointerException
                                                                            at com.example.android.intent.ViewActivity.onCreate(ViewActivity.java:34)
                                                                            at android.app.Activity.performCreate(Activity.java:5231)
                                                                            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
                                                                            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148)
                                                                            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2233) 
                                                                            at android.app.ActivityThread.access$800(ActivityThread.java:135) 
                                                                            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196) 
                                                                            at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                                            at android.os.Looper.loop(Looper.java:136) 
                                                                            at android.app.ActivityThread.main(ActivityThread.java:5001) 
                                                                            at java.lang.reflect.Method.invokeNative(Native Method) 
                                                                            at java.lang.reflect.Method.invoke(Method.java:515) 
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785) 
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601) 
                                                                            at dalvik.system.NativeStart.main(Native Method) 
  

просмотр файла макета

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

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentTop="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true">

    <TableRow
        android:layout_width="80dp"
        android:layout_height="50dp" >

        <TextView
            android:text="Course"
            android:layout_width="80dp"
            android:layout_height="50dp"
            android:id="@ id/course"
            android:layout_marginLeft="50dp"
            android:layout_marginTop="10dp"
            android:textSize="24sp" />

        <TextView
            android:text="Hour"
            android:layout_width="80dp"
            android:layout_height="50dp"
            android:id="@ id/hour"
            android:layout_marginLeft="170dp"
            android:layout_marginTop="10dp"
            android:textSize="24sp"
            android:layout_marginRight="30dp" />



    </TableRow>

</TableLayout>

<Button
    android:text="Edit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="45dp"
    android:id="@ id/ed"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_marginLeft="38dp"
    android:layout_marginStart="38dp"
    android:onClick="" />

<Button
    android:text="Delete"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="19dp"
    android:layout_marginEnd="19dp"
    android:id="@ id/delete"
    android:layout_alignBaseline="@ id/ed"
    android:layout_alignBottom="@ id/ed"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
    android:onClick="" />

<TextView
    android:layout_width="350dp"
    android:layout_height="350dp"
    android:id="@ id/details"
    android:layout_above="@ id/delete"
    android:layout_centerHorizontal="true" />

<Button
    android:text="Refresh"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@ id/delete"
    android:layout_toLeftOf="@ id/delete"
    android:layout_toStartOf="@ id/delete"
    android:layout_marginRight="28dp"
    android:layout_marginEnd="28dp"
    android:id="@ id/button4"
    android:onClick="" />
  

Кто-нибудь может помочь, спасибо 🙂

Комментарии:

1. пожалуйста, также опубликуйте свой logcat..

2. Также опубликуйте свой полный AndroidManifest..

Ответ №1:

Измените свой манифест следующим образом: вы добавили ViewActivity в другое действие.

 <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

Добавьте это в свой макет представления,

 <Button
    android:text="Close View Activity"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@ id/button1" />
  

Комментарии:

1. появилась та же ошибка .. locat показывает ошибку в ViewActivity.onCreate(ViewActivity.java:34)!!

2. Попробуйте прокомментировать эту строку Intent intent = GetIntent(); и построить

3. Можете ли вы опубликовать трассировку стека журнала после исправления AndroidManifest? или это дает ту же ActivityNotFound?

4. присутствует ли view_ button с идентификатором R.id.button1 в R.layout.view?

5. Вы пытаетесь получить доступ к кнопке, которую вы установили в своем макете MainActivity. Поэтому он не может найти идентификатор в представлении макета. Там возникает NullPointer.

Ответ №2:

Вы не закрыли тег activity. Изменить AndroidManifest.xml чтобы:

 <application
  android:allowBackup="true"
  android:icon="@mipmap/ic_launcher"
  android:label="@string/app_name"
  android:supportsRtl="true"
  android:theme="@style/AppTheme" >
  <activity android:name=".MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

Комментарии:

1. появилась та же ошибка .. locat показывает ошибку в ViewActivity.onCreate(ViewActivity.java:34)!! является ли функция OnClickListener неверной? в ViewActivity calss

2. да, я уверен …. locat показывает, что OnClickListener в классе ViewActivity является причиной ошибки!! это неправильно?

3. Нет, проблем быть не должно. за исключением намерения intent = GetIntent(); в ViewActivity бесполезно.

Ответ №3:

Измените это

 view_= (Button) findViewById(R.id.button1);
  

Для

 view_= (Button) findViewById(R.id.button4);
  

В XML вашего класса ViewActivity нет кнопки button1, поэтому при попытке получить доступ к button1 NullPointerException происходит.

Ответ №4:

Попробуйте это в своем манифесте. Вы помещаете одно действие в другое. Поместите отдельно.

 <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

Комментарии:

1. появилась та же ошибка .. locat показывает ошибку в ViewActivity.onCreate(ViewActivity.java:34)!!

2. Это правильно. Ваша ошибка в manifest.xml как я уже упоминал.

3. да, я сделал то, что вы сказали, но это выдает ту же ошибку!!

4. попробуйте поставить вместо finish(); Намерение intent = новое намерение (это, MainActivity. Класс); intent.setFlags(намерение. FLAG_ACTIVITY_CLEAR_TOP); startActivity(намерение); finish();