java.lang.Runtimeexception: Unable to start Activity Componentinfo{}: java.lang.Nullpointerexception by checking my input

Asked

Viewed 220 times

0

I’m new to android development and am passing a swing chat for android. The idea is to use a server socket that makes the connection. This is the third attempt to make it work... I received the following errors:

E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.stevenilson.appchat/com.stevenilson.appchat.TelaChat}: java.lang.NullPointerException
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2114)
    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.NullPointerException
    at com.stevenilson.appchat.TelaChat.conectar(TelaChat.java:84)
    at com.stevenilson.appchat.TelaChat.onCreate(TelaChat.java:40)
    at android.app.Activity.performCreate(Activity.java:5203)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2078)
    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)

follows the main code:

package com.stevenilson.appchat;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

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

public class TelaChat extends AppCompatActivity {

    EditText textMessage;
    ListView mensagens;
    ArrayAdapter<String> adapter;
    ChatMessage message;
    Socket socket;
    ClienteService service;
    ObjectOutputStream outputStream;
    ObjectInputStream input;

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

        textMessage = findViewById(R.id.textBox);
        mensagens = findViewById(R.id.messagesView);

        adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);
        mensagens.setAdapter(adapter);

        conectar();//linha 40 que recebe erro
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();

        Toast.makeText(TelaChat.this, "Você saiu do Chat!", Toast.LENGTH_SHORT).show();
    }

    private class Run implements Runnable {
        public void run() {
            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)) {
                        socket.close();
                        onDestroy();
                    } else if(action.equals(ChatMessage.Action.SEND_ONE)) {
                        receive(message);
                    }
                }
            } catch (IOException ex) {
                Logger.getLogger(TelaChat.class.getName()).log(Level.SEVERE, null, ex);
            } catch (ClassNotFoundException ex) {
                Logger.getLogger(TelaChat.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public void enviarMensagem(View view) {
        sendMessage();
    }

    private void sendMessage(){
        adapter.add(textMessage.getText().toString());
        this.message.setAction(ChatMessage.Action.SEND_ALL);

    }

    public void conectar() {

        try {
            this.input = new ObjectInputStream(socket.getInputStream()); // linha 84 que recebe erro;
        } catch (IOException ex) {
            Logger.getLogger(TelaChat.class.getName()).log(Level.SEVERE, null, ex);
        }

        new Thread(new Run()).start();

        this.message.setAction(ChatMessage.Action.CONNECT);
        this.socket = this.service.connect();
        Toast.makeText(TelaChat.this, "Você está conectado!", Toast.LENGTH_SHORT).show();
    }
    private void connected(ChatMessage message) {
        if (message.getText().equals("NO")) {
            Toast.makeText(TelaChat.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);
            onDestroy();
            return;
        }
        Toast.makeText(TelaChat.this, "Você está conectado no chat!", Toast.LENGTH_SHORT).show();
    }

    private void receive(ChatMessage message) {
        adapter.add(message.getText());
    }


}

xml code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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="enviarMensagem"
            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>
</RelativeLayout>

if you need more information about the other classes just ask.

Obs: project of fair for day 20 November;

  • @Isac looking for more sinking found several mattes and posts about nullPointer but do not fit my problem ;-;

  • 1

    apparently what is null is your socket, please confirm

  • What do you mean "they don’t fit your problem"? If you have NullPointerException is because you’re using something that’s null, as indicated in the question that Inked. You have to understand which line gives the error and which object is null, and understand why it is null, to know how to prevent it from being null. In your specific case the message tells you that you are accessing something null on line 84 which is in the method connectar.

  • Please don’t get mad at me. I’m very new to programming. @Lucasmiranda como posso evitar o socket null se é nesse metodo que eu conecto ele?

  • @Isac, I tried to change the way to connect the socket but I keep failing miserably. Have any idea how I could do it?

  • @Alcedeterno It’s like I said, and don’t assume it’s anger, you have to realize which object is null. Only from there can you start trying to solve the problem. I don’t know which object is null, because I don’t know which code on line 84, so I can’t help.

  • the 84 line code is commented as 84 :/ line is an inputStream @Isac instantiation

  • Isac, you need to start your variable socket at some point. It is not "receiving" anything at any time before line 84

  • @cpll I am not the author of the question, but your tip is valid for the author of the question and follows precisely what I pointed back.

  • thanks to all for the help. I managed to arrange instantiating the socket;

Show 6 more comments
No answers

Browser other questions tagged

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