Unable to instantiate activity ComponentInfo; java.lang.IllegalStateException: System services not available to Activities before onCreate ()

1

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

It was all working perfectly until I put the code that makes the magic happen. The application closed and I did not know why it had already fixed all the errors of the code itself.

I went through the debug and found the error saying that I could not instantiate anything before onCreate() . As you can see there is nothing before him (visibly). I asked some teachers and they told me that the problem could be in the life cycle of my activity. I have not found the error yet. 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 registered to the 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) 
    
asked by anonymous 26.10.2018 / 02:50

1 answer

2

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

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

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

Example

In the class body:

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 to take a look at the Activities life cycle to have a idea about when to call certain methods and initialize their variables.

    
26.10.2018 / 03:13