web-dev-qa-db-fra.com

Obtenir IllegalStateException en cliquant sur un bouton

En cliquant sur un bouton pour migrer vers une autre activité, l'application se bloque et le journal indique:

Java.lang.IllegalStateException: Could not execute method for Android:onClick

Pour déboguer, j'ai essayé de migrer vers une activité vide tout en affichant la même erreur. Je ne comprends pas pourquoi!

Il s’agit du fichier Java de mon activité principale qui indique une erreur dans la fonction d’intention de Host ():

package com.example.unholyalliance.infinitestream;

import Android.content.Context;
import Android.content.Intent;
import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;
import Android.view.View;
import Android.widget.Toast;

public class MainActivity extends AppCompatActivity {

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

    public void Host(View v)
    {
        Intent i = new Intent(this,Host.class);
        try
        {
            startActivity(i);
        }catch(IllegalStateException e)
        {
            Context context = getApplicationContext();
            CharSequence text = e.getMessage();
            int duration = Toast.LENGTH_SHORT;

            Toast toast = Toast.makeText(context, text, duration);
            toast.show();
        }
    }

    public void search(View v)
    {

    }
}



This is my Host.Java file:

import Android.content.Context;

import Android.net.nsd.NsdManager;
import Android.net.nsd.NsdServiceInfo;
import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;
import Android.widget.TextView;

import Java.io.IOException;
import Java.net.ServerSocket;

public class Host extends AppCompatActivity {

    public String mServiceName="Stream";
    ServerSocket mServerSocket=null;
    NsdManager.RegistrationListener mRegistrationListener=null;
    private NsdManager mNsdManager=null;
    int port=9000;
    TextView service_status = (TextView) findViewById(R.id.textView1);
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_Host);
        mNsdManager = (NsdManager) getSystemService(Context.NSD_SERVICE);
        try {
            initializeServerSocket();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void initializeServerSocket() throws IOException {
        //Initialize a server socket on the next available port.
        mServerSocket = new ServerSocket(0);

        // Store the chosen port.
        port =  mServerSocket.getLocalPort();
        registerService(port);

    }

    public void registerService(int port) {
        // Create the NsdServiceInfo object, and populate it.
        NsdServiceInfo serviceInfo  = new NsdServiceInfo();

        // The name is subject to change based on conflicts
        // with other services advertised on the same network.
        serviceInfo.setServiceName("Stream");
        serviceInfo.setServiceType("_http._tcp.");
        serviceInfo.setPort(port);
        mNsdManager.registerService(
                serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
        initializeRegistrationListener();


    }



    public void initializeRegistrationListener() {
        mRegistrationListener = new NsdManager.RegistrationListener() {

            @Override
            public void onServiceRegistered(NsdServiceInfo NsdServiceInfo) {
                // Save the service name.  Android may have changed it in order to
                // resolve a conflict, so update the name you initially requested
                // with the name Android actually used.
                mServiceName = NsdServiceInfo.getServiceName();
              service_status.setText("Success");
            }

            @Override
            public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
                // Registration failed!  Put debugging code here to determine why.
                service_status.setText("Registration Failed!");
            }

            @Override
            public void onServiceUnregistered(NsdServiceInfo arg0) {
                // Service has been unregistered.  This only happens when you call
                // NsdManager.unregisterService() and pass in this listener.
                service_status.setText("Registration not done");
            }

            @Override
            public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
                // Unregistration failed.  Put debugging code here to determine why.
                service_status.setText("Unregistration failed");
            }
        };
    }
}

Trace de pile complète:

E/AndroidRuntime: FATAL EXCEPTION: main
 Java.lang.IllegalStateException: Could not execute method for Android:onClick
     at Android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.Java:293)
     at Android.view.View.performClick(View.Java:4278)
     at Android.view.View$PerformClick.run(View.Java:17429)
     at Android.os.Handler.handleCallback(Handler.Java:725)
     at Android.os.Handler.dispatchMessage(Handler.Java:92)
     at Android.os.Looper.loop(Looper.Java:137)
     at Android.app.ActivityThread.main(ActivityThread.Java:5099)
     at Java.lang.reflect.Method.invokeNative(Native Method)
     at Java.lang.reflect.Method.invoke(Method.Java:511)
     at com.Android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.Java:803)
     at com.Android.internal.os.ZygoteInit.main(ZygoteInit.Java:570)
     at dalvik.system.NativeStart.main(Native Method)
  Caused by: Java.lang.reflect.InvocationTargetException
     at Java.lang.reflect.Method.invokeNative(Native Method)
     at Java.lang.reflect.Method.invoke(Method.Java:511)
     at Android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.Java:288)
     at Android.view.View.performClick(View.Java:4278) 
     at Android.view.View$PerformClick.run(View.Java:17429) 
     at Android.os.Handler.handleCallback(Handler.Java:725) 
     at Android.os.Handler.dispatchMessage(Handler.Java:92) 
     at Android.os.Looper.loop(Looper.Java:137) 
     at Android.app.ActivityThread.main(ActivityThread.Java:5099) 
     at Java.lang.reflect.Method.invokeNative(Native Method) 
     at Java.lang.reflect.Method.invoke(Method.Java:511) 
     at com.Android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.Java:803) 
     at com.Android.internal.os.ZygoteInit.main(ZygoteInit.Java:570) 
     at dalvik.system.NativeStart.main(Native Method) 
  Caused by: Android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.unholyalliance.infinitestream/com.example.unholyalliance.infinitestream.Host}; have you declared this activity in your AndroidManifest.xml?
     at Android.app.Instrumentation.checkStartActivityResult(Instrumentation.Java:1633)
     at Android.app.Instrumentation.execStartActivity(Instrumentation.Java:1425)
     at Android.app.Activity.startActivityForResult(Activity.Java:3370)
     at Android.app.Activity.startActivityForResult(Activity.Java:3331)
     at Android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.Java:843)
     at Android.app.Activity.startActivity(Activity.Java:3566)
     at Android.app.Activity.startActivity(Activity.Java:3534)
     at com.example.unholyalliance.infinitestream.MainActivity.Host(MainActivity.Java:23)
     at Java.lang.reflect.Method.invokeNative(Native Method) 
     at Java.lang.reflect.Method.invoke(Method.Java:511) 
     at Android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.Java:288) 
     at Android.view.View.performClick(View.Java:4278) 
     at Android.view.View$PerformClick.run(View.Java:17429) 
     at Android.os.Handler.handleCallback(Handler.Java:725) 
     at Android.os.Handler.dispatchMessage(Handler.Java:92) 
     at Android.os.Looper.loop(Looper.Java:137) 
     at Android.app.ActivityThread.main(ActivityThread.Java:5099) 
     at Java.lang.reflect.Method.invokeNative(Native Method) 
     at Java.lang.reflect.Method.invoke(Method.Java:511) 
     at com.Android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.Java:803) 
     at com.Android.internal.os.ZygoteInit.main(ZygoteInit.Java:570) 
     at dalvik.system.NativeStart.main(Native Method) 

fichier activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<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"
    Android:paddingBottom="@dimen/activity_vertical_margin"
    Android:paddingLeft="@dimen/activity_horizontal_margin"
    Android:paddingRight="@dimen/activity_horizontal_margin"
    Android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.unholyalliance.infinitestream.MainActivity">

    <Button
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:text="Host"
        Android:id="@+id/Host_button"
        Android:layout_alignParentTop="true"
        Android:layout_centerHorizontal="true"
        Android:layout_marginTop="104dp"
        Android:clickable="true"
        Android:onClick="Host" />

    <Button
        Android:layout_width="wrap_content"
        Android:layout_height="wrap_content"
        Android:text="Search"
        Android:id="@+id/search_button"
        Android:layout_centerVertical="true"
        Android:layout_centerHorizontal="true"
        Android:onClick="search"
        Android:clickable="true" />
</RelativeLayout>
8
yash1996

La partie clé de la trace de pile complète se trouve ici:

Causée par: Android.content.ActivityNotFoundException: impossible de trouver la classe d'activité explicite {Com.example.unholyalliance.infinitestream/com.example.unholyalliance.infinitestream.Host}; avez-vous déclaré cette activité dans votre AndroidManifest.xml

Il semble que cette activité Host ne soit pas déclarée dans votre fichier manifeste. Ouvrez AndroidManifest.xml et vérifiez ou ajoutez les éléments suivants:

<activity
    Android:name=".Host" />

Assurez-vous également de résoudre le problème dans Host pour ne déclarer d'abord que votre TextView, puis attribuez la valeur dans onCreate() après setContentView().

private TextView service_status;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_Host);
    service_status = (TextView) findViewById(R.id.textView1);
    ...
}
7
George Mulligan

Assurez-vous que votre onClick dans la vue Bouton dans activity_main.xml est comme ceci Android:onClick="Host"

Exemple:

<Button
    Android:id="@+id/main_activity_bt_Host"
    Android:layout_width="wrap_content"
    Android:layout_height="wrap_content"
    Android:text="@string/Host"
    Android:onClick="Host" />
0
Miguel Benitez

Les réponses ci-dessus sont correctes, mais vérifiez aussi d’enregistrer votre classe dans Manifest.

 <activity Android:name=".Downloaded"

            Android:label="@string/app_name">

        </activity>

.Downloaded est le nom de votre classe ci-dessus.

0
Praveen Kashyap