0

I try to develop simple application (named Noti) with notifications using Firebase platform. I need to save the token into database using php script saved on my server. The issue is I receive message Noti has stopped after pushing the button.

package com.example.jaroslavvystavel.noti;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.firebase.iid.FirebaseInstanceId;

import java.io.IOException;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button btnShowToken = (Button)findViewById(R.id.button_show_token);
        btnShowToken.setOnClickListener(new View.OnClickListener() {
            @Override

            public void onClick(View v) {
                //Get the token
                String token = FirebaseInstanceId.getInstance().getToken();
                Log.d(TAG, "Token: " + token);
                Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
                registerToken(token);

            }

        });

    }
    private void registerToken(String token) {

        OkHttpClient client = new OkHttpClient();
        RequestBody body = new FormBody.Builder()
                .add("Token",token)
                .build();

        Request request = new Request.Builder()
                .url("http://www.stud.fit.vutbr.cz/~xvose02/testuji.php")
                .post(body)
                .build();

        try {
            client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I was inspired by this Youtube tutorial where everything works fine. I just slightly modified author's code to call the registerToken method every time user pushes the button.

Android Monitor log (from the moment of pushing the button):

    04-24 05:42:58.601 28949-28949/com.example.jaroslavvystavel.noti D/MainActivity: Token: c7J9CHxblE8:APA91bEnZA6zU5nnzKVba19G5ViznKy5jR5-_arjavZWQcpLXsK4M5VOTxc50g1ANFSmFPJ-ADRXfhX-aDa3ZsRwkEhyrIFQXEJX5x3OcQDt7ejNMfF3Q8qeTSsmWbGB4fFxIe1QR0gc
04-24 05:42:58.701 28949-28949/com.example.jaroslavvystavel.noti D/AndroidRuntime: Shutting down VM
04-24 05:42:58.701 28949-28949/com.example.jaroslavvystavel.noti W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x417a1930)
04-24 05:42:58.741 28949-28949/com.example.jaroslavvystavel.noti E/AndroidRuntime: FATAL EXCEPTION: main
                                                                                   android.os.NetworkOnMainThreadException
                                                                                       at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1128)
                                                                                       at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
                                                                                       at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
                                                                                       at java.net.InetAddress.getAllByName(InetAddress.java:214)
                                                                                       at okhttp3.Dns$1.lookup(Dns.java:39)
                                                                                       at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:170)
                                                                                       at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:136)
                                                                                       at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:81)
                                                                                       at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:171)
                                                                                       at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:121)
                                                                                       at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:100)
                                                                                       at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
                                                                                       at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                                                       at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
                                                                                       at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
                                                                                       at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                                                       at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
                                                                                       at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
                                                                                       at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                                                       at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:120)
                                                                                       at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:92)
                                                                                       at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:67)
                                                                                       at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:185)
                                                                                       at okhttp3.RealCall.execute(RealCall.java:69)
                                                                                       at com.example.jaroslavvystavel.noti.MainActivity.registerToken(MainActivity.java:57)
                                                                                       at com.example.jaroslavvystavel.noti.MainActivity.access$000(MainActivity.java:20)
                                                                                       at com.example.jaroslavvystavel.noti.MainActivity$1.onClick(MainActivity.java:37)
                                                                                       at android.view.View.performClick(View.java:4439)
                                                                                       at android.widget.Button.performClick(Button.java:139)
                                                                                       at android.view.View$PerformClick.run(View.java:18395)
                                                                                       at android.os.Handler.handleCallback(Handler.java:725)
                                                                                       at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                                       at android.os.Looper.loop(Looper.java:176)
                                                                                       at android.app.ActivityThread.main(ActivityThread.java:5319)
                                                                                       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:1102)
                                                                                       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)
                                                                                       at dalvik.system.NativeStart.main(Native Method)

AsyncTask class:

class updateDb extends AsyncTask<OkHttpClient, RequestBody, Request> {

    private Exception exception;



    @Override
    protected Request doInBackground(String... params) {
        try {
            OkHttpClient client = new OkHttpClient();
            RequestBody body = new FormBody.Builder()
                    .add("Token",token)
                    .build();

            Request request = new Request.Builder()
                    .url("http://www.stud.fit.vutbr.cz/~xvose02/testuji.php")
                    .post(body)
                    .build();

            try {
                client.newCall(request).execute();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            this.exception = e;


        }
        return null;
    }


}

Not sure about parameters of method...

Funk Forty Niner
  • 74,450
  • 15
  • 68
  • 141
user7303261
  • 128
  • 12
  • Hi. Could you also post the error logs? – AL. Apr 24 '17 at 03:04
  • @AL. Hello. Can you tell me where can i find them? Sorry, I'm totally beginner in android development. – user7303261 Apr 24 '17 at 03:06
  • 1
    Hi. Sure. The logs should be visible in the Android Monitor section. See [here](https://developer.android.com/studio/profile/android-monitor.html). – AL. Apr 24 '17 at 03:11
  • @AL. Thanks. Done. – user7303261 Apr 24 '17 at 03:23
  • 1
    Cool. Thanks. Code is identical to the repo from the Tutorial so I don't think that's where the concern is. What I'm thinking is there's something missing in the libraries due to the `NoClassDefFoundError: okio.Buffer`. See this [post](http://stackoverflow.com/q/28124587/4625829). – AL. Apr 24 '17 at 03:33
  • Good idea @AL. I imported `okio` library. Anyway, it didn't influence the result. Still the same situation. EDIT: I just updated the error logs. – user7303261 Apr 24 '17 at 03:42
  • Owww. Okay. So the error upon button click was actually `NetworkOnMainThreadException`. This makes more sense. Usually, when creating HTTP requests, it is ran in a separate thread. Try putting the code in your `registerToken()` inside an AsyncTask (as mentioned [here](http://stackoverflow.com/q/6343166/4625829)) and see if this fixes the issue. – AL. Apr 24 '17 at 03:49
  • @AL. Can you, please, look at my edit and give me an advice about parameters? – user7303261 Apr 24 '17 at 04:14

1 Answers1

1

Adding an answer to provide sample code

The request looks fine. The other parameters aren't really that necessary though. Below is how I think the code should be (simplified).

    private void registerToken(final String token) {

        new updateDb().execute(token);

    }

    private class updateDb extends AsyncTask<String, Void, Void> {

        @Override
        protected Void doInBackground(String... token) {
            try {
                OkHttpClient client = new OkHttpClient();
                RequestBody body = new FormBody.Builder()
                        .add("Token", token[0])
                        .build();

                Request request = new Request.Builder()
                        .url("http://www.stud.fit.vutbr.cz/~xvose02/testuji.php")
                        .post(body)
                        .build();

                client.newCall(request).execute();

            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
AL.
  • 36,815
  • 10
  • 142
  • 281