Unable to instantiate Activity Componentinfo; java.lang.Illegalstateexception: System services not available to Activities before onCreate()

Asked

Viewed 670 times

1

I have a project of a chat socket running in Swing and now I’m passing it to Android.

Everything was working perfectly until I put in the code that makes the magic happen. The application closed and I didn’t know because I had fixed all the errors of the code itself.

I went through the debug and found such a mistake saying that I could not instantiate anything before the onCreate(). As you can see there is nothing before it (visibly). I asked some teachers and they told me that the problem could be in the life cycle of my Activity. I have not yet discovered the mistake. In theory the code is right.

my Mainactivity.java:

package com.lucas.appchat;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;


public class MainActivity extends AppCompatActivity {

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

        this.message = new ChatMessage();
        this.message.setAction(ChatMessage.Action.CONNECT);
        this.message.setName(nome);

        this.service = new ClienteService();
        this.socket = this.service.connect();

        new Thread(new ListenerSocket(this.socket)).start();

        this.service.send(message);
    }

    public void btnEnviar(View view) {
        btnEnviarActionPerformed();
    }

    public MessageViewHolder holder = new MessageViewHolder();
    public LayoutInflater messageInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

    private Socket socket;
    private ChatMessage message;
    private ClienteService service;
    private ObjectOutputStream outputStream;
    public EditText txtAreaSend = findViewById(R.id.textBox);

    ListView listOnlines2;
    String[] array;
    ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array);


    private class ListenerSocket implements Runnable {

        private ObjectInputStream input;

        public ListenerSocket(Socket socket) {
            try {
                this.input = new ObjectInputStream(socket.getInputStream());
            } catch (IOException ex) {
                Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        @Override
        public void run() {
            ChatMessage message;
            try {
                while ((message = (ChatMessage) input.readObject()) != null) {
                    ChatMessage.Action action = message.getAction();

                    if (action.equals(ChatMessage.Action.CONNECT)) {
                        connected(message);
                    } else if (action.equals(ChatMessage.Action.DISCONNECT)) {
                        refreshOnlines(message);
                        disconnected();
                        socket.close();
                    } else if (action.equals(ChatMessage.Action.SEND_ONE)) {
                        receive(message);
                    } else if (action.equals(ChatMessage.Action.USERS_ONLINE)) {
                        refreshOnlines(message);
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(MainActivity.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        private void connect(ChatMessage message1) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    }

    private void connected(ChatMessage message) {
        if (message.getText().equals("NO")) {
            Toast.makeText(MainActivity.this, "Coneão não realizada!\nTente novamente com um novo nome.", Toast.LENGTH_SHORT).show();
            message.setAction(ChatMessage.Action.DISCONNECT);
            this.service.send(message);
            disconnected();
            return;
        }
        Toast.makeText(MainActivity.this, "Você está conectado no chat!", Toast.LENGTH_SHORT).show();

    }
    private void disconnected() {
        Toast.makeText(MainActivity.this, "Você saiu do Chat!", Toast.LENGTH_SHORT).show();
    }

    private void receive(ChatMessage message) {

        View convertView;

            convertView = messageInflater.inflate(R.layout.their_message, null);
            holder.avatar = (View) convertView.findViewById(R.id.avatar);
            holder.name = (TextView) convertView.findViewById(R.id.name);
            holder.messageBody = (TextView) convertView.findViewById(R.id.message_body);
            convertView.setTag(holder);

            holder.name.setText(message.getName());
            holder.messageBody.setText(message.getText());
            GradientDrawable drawable = (GradientDrawable) holder.avatar.getBackground();
            drawable.setColor(Color.parseColor(message.getRandomColor()));


    }

    private void refreshOnlines(ChatMessage message) {
        System.out.println(message.getSetOnlines().toString());

        Set<String> names = message.getSetOnlines();

        names.remove(message.getName());

        array = (String[]) names.toArray(new String[names.size()]);



        listOnlines2.setAdapter(arrayAdapter);

    }



    private void btnEnviarActionPerformed() {
        String text = this.txtAreaSend.getText().toString();
        String name = this.message.getName();

        this.message = new ChatMessage();


        this.message.setAction(ChatMessage.Action.SEND_ALL);


        if (!text.isEmpty()) {
            this.message.setName(name);
            this.message.setText(text);


            View convertView;

            convertView = messageInflater.inflate(R.layout.my_message, null);
            holder.messageBody = (TextView) convertView.findViewById(R.id.message_body);
            convertView.setTag(holder);
            holder.messageBody.setText(message.getText());


            this.service.send(this.message);
        }

        this.txtAreaSend.setText("");
    }

    private void btnSairActionPerformed() {
        ChatMessage message = new ChatMessage();
        message.setName(this.message.getName());
        message.setAction(ChatMessage.Action.DISCONNECT);
        this.service.send(message);
        disconnected();
    }


}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:clipToPadding="false"
android:focusableInTouchMode="true"
tools:context=".MainActivity">

<ListView
    android:id="@+id/messagesView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="2"
    android:divider="#fff" />

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="#fff"
    android:orientation="horizontal">

    <EditText
        android:id="@+id/textBox"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="2"
        android:ems="10"
        android:hint="Escrever..."
        android:inputType="text"
        android:paddingHorizontal="10dp"
        android:text="" />

    <ImageButton
        android:id="@+id/buttonSend"
        android:onClick="btnEnviar"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginHorizontal="10dp"
        android:padding="20dp"
        android:scaleType="fitCenter"
        android:src="@android:drawable/ic_menu_send" />

</LinearLayout>

Errors recorded in debug:

E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.stevenilson.appchat/com.stevenilson.appchat.MainActivity}: java.lang.IllegalStateException: System services not available to Activities before onCreate()
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2038)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
    at android.app.ActivityThread.access$700(ActivityThread.java:143)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:137)
    at android.app.ActivityThread.main(ActivityThread.java:4960)
    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:1038)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
    at dalvik.system.NativeStart.main(Native Method)
 Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()
    at android.app.Activity.getSystemService(Activity.java:4582)
    at com.stevenilson.appchat.MainActivity.<init>(MainActivity.java:49)
    at java.lang.Class.newInstanceImpl(Native Method)
    at java.lang.Class.newInstance(Class.java:1319)
    at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2029)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139) 
    at android.app.ActivityThread.access$700(ActivityThread.java:143) 
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241) 
    at android.os.Handler.dispatchMessage(Handler.java:99) 
    at android.os.Looper.loop(Looper.java:137) 
    at android.app.ActivityThread.main(ActivityThread.java:4960) 
    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:1038) 
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805) 
    at dalvik.system.NativeStart.main(Native Method) 

1 answer

2

The error occurs because you are trying to access Android components before the Activity is created, ie before the method onCreate() be called. Two examples of these calls illegal are in:

public EditText txtAreaSend = findViewById(R.id.textBox);
public LayoutInflater messageInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);

Note that these variables are being initialized in the class body, when in fact they should be initialized after or within the method onCreate(). Thus, one solution would be to declare these variables in the class body, but only initialize them within the onCreate()or some other method;

Example

In the body of the class:

public EditText txtAreaSend;
public LayoutInflater messageInflater;

Within the method onCreate()or some other method:

messageInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
txtAreaSend = findViewById(R.id.textBox);

Extra

It would be nice for you to take a look at life cycle of activities to get a better idea about when to call certain methods and initialize their variables.

  • I tried to put inside onCreat() the instantiation of everything (3 variables) continued to fail. I created a method and put the instantiation of the variables inside him and called him on onCreat() which also went wrong. The errors are now:

  • ' java.lang.Runtimeexception: Unable to start Activity Componentinfo{com.stevenilson.appchat/com.stevenilson.appchat.Mainactivity}: java.lang.Nullpointerexception' ' Caused by: java.lang.Nullpointerexception' I think it has something to do with the string array

Browser other questions tagged

You are not signed in. Login or sign up in order to post.