-4

I'm trying to create an app which will send some data to a web server when a button will be clicked and the data will be from the form. The data types are first name, last name and others. I'm a beginner developer and trying OKHTTPFClient plugin for sending HTTP request from the app. What I need is on click the form data will be send to the PHP and then PHP will give a success response which will then the app get and then the activity will be redirected to thank you activity. Here's the code I'm trying now -

submitRequest.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if ( firstName.getText().toString().length() == 0 ) {
                firstName.setError("Please enter your first name!");
            }
            if ( firstName.getText().toString().length() != 0 ) {

                Toast.makeText(getApplicationContext(), firstName.getText().toString(), Toast.LENGTH_SHORT).show();

                requestHTTP(firstName.getText().toString());

            } else {

            }
        }
    });

And here is the method for OKHTTPClient -

private void requestHTTP(String first_name) {
    OkHttpClient httpClient = new OkHttpClient();
    String url = "https://www.example.com/action.php";

    RequestBody formBody = new FormBody.Builder()
            .add("first_name", first_name)
            .build();
    Request request = new Request.Builder()
            .url(url)
            .post(formBody)
            .build();
    Response response = null;
    try {
        response = httpClient.newCall(request).execute();
        if (response.isSuccessful()) {
            Toast.makeText(getApplicationContext(), firstName.getText().toString(), Toast.LENGTH_SHORT).show();
        }

    } catch (IOException e) {

    }
}

UPDATE :

Here's the errors showing on Android Run section -

E/AndroidRuntime: FATAL EXCEPTION: main
              Process: com.example.androidapp, PID: 11592
              android.os.NetworkOnMainThreadException
                  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)
                  at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:86)
                  at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:74)
                  at java.net.InetAddress.getAllByName(InetAddress.java:752)
                  at okhttp3.Dns$1.lookup(Dns.java:39)
                  at okhttp3.internal.connection.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:185)
                  at okhttp3.internal.connection.RouteSelector.nextProxy(RouteSelector.java:149)
                  at okhttp3.internal.connection.RouteSelector.next(RouteSelector.java:84)
                  at okhttp3.internal.connection.StreamAllocation.findConnection(StreamAllocation.java:213)
                  at okhttp3.internal.connection.StreamAllocation.findHealthyConnection(StreamAllocation.java:134)
                  at okhttp3.internal.connection.StreamAllocation.newStream(StreamAllocation.java:113)
                  at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.java:42)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
                  at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.java:93)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
                  at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.java:93)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
                  at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.java:125)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:147)
                  at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.java:121)
                  at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.java:200)
                  at okhttp3.RealCall.execute(RealCall.java:77)
                  at org.goldenfs.payoffcalculator.advisor.requestHTTP(advisor.java:220)
                  at org.goldenfs.payoffcalculator.advisor.access$000(advisor.java:38)
                  at org.goldenfs.payoffcalculator.advisor$4.onClick(advisor.java:188)
                  at android.view.View.performClick(View.java:6261)
                  at android.widget.TextView.performClick(TextView.java:11180)
                  at android.view.View$PerformClick.run(View.java:23748)
                  at android.os.Handler.handleCallback(Handler.java:751)
                  at android.os.Handler.dispatchMessage(Handler.java:95)
                  at android.os.Looper.loop(Looper.java:154)
                  at android.app.ActivityThread.main(ActivityThread.java:6776)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1520)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1410)

Application terminated.

Please help me to solve that issue. I really appreciate your help... :)

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
eatherpro
  • 63
  • 1
  • 9

2 Answers2

3

android.os.NetworkOnMainThreadException at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1303)

You should use THREAD .

    //A thread is a thread of execution in a program.
    // The Java Virtual Machine allows an application to have multiple threads of execution running concurrently.
    Thread thread = new Thread(new Runnable() {

        @Override
        public void run() {
            try
            {

                            OkHttpClient httpClient = new OkHttpClient();
                            String url = "https://www.example.com/action.php";

                            RequestBody formBody = new FormBody.Builder()
                                    .add("first_name", first_name)
                                    .build();
                            Request request = new Request.Builder()
                                    .url(url)
                                    .post(formBody)
                                    .build();
                            Response response = null;
                            try {
                                response = httpClient.newCall(request).execute();
                                if (response.isSuccessful()) {
                                    Toast.makeText(getApplicationContext(), firstName.getText().toString(), Toast.LENGTH_SHORT).show();
                                }

                            } catch (IOException e) {

                            }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    thread.start();

From OkHttp.

IntelliJ Amiya
  • 74,896
  • 15
  • 165
  • 198
  • `W/System.err: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare() W/System.err: at android.os.Handler.(Handler.java:200) W/System.err: at android.os.Handler.(Handler.java:114) W/System.err: at android.widget.Toast$TN.(Toast.java:625) W/System.err: at android.widget.Toast.(Toast.java:138) W/System.err: at android.widget.Toast.makeText(Toast.java:388) W/System.err: at org.goldenfs.payoffcalculator.advisor$4$1.run(advisor.java:209) W/System.err: at java.lang.Thread.run(Thread.java:762)` – eatherpro Nov 11 '17 at 09:06
  • @EatherAhmed https://stackoverflow.com/questions/3875184/cant-create-handler-inside-thread-that-has-not-called-looper-prepare – IntelliJ Amiya Nov 11 '17 at 09:06
  • @EatherAhmed https://stackoverflow.com/a/27599969/3395198 – IntelliJ Amiya Nov 11 '17 at 09:10
  • 1
    Using a thread is ok. But you cannot display a Toast in a thread. Then you get such kind of errors. – greenapps Nov 11 '17 at 09:42
  • @greenapps for that case we should `runOnUiThread` – IntelliJ Amiya Nov 11 '17 at 09:45
  • I do not see you using runOnUiThread(). – greenapps Nov 11 '17 at 09:47
  • @greenapps sorry, In here i'm not added this. – IntelliJ Amiya Nov 11 '17 at 09:49
2

It throws error because you are trying perform Network operation on MainThread which should not be done. Please add below lines and try,

  public void onViewCreated(View view, Bundle savedInstanceState) 
    {
        int SDK_INT = android.os.Build.VERSION.SDK_INT;
        if (SDK_INT > 8) 
        {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                    .permitAll().build();
            StrictMode.setThreadPolicy(policy);
            //your codes here

        }
    }

OR You can call your method in AsyncTask which does not run on MainThread.

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

        String data;
        public YourAsyncTaskName(String data){
            this.data= data;
         }

        @Override
        protected String doInBackground(String... params) {
            requestHTTP(data);
            return null;
        }

        @Override
        protected void onPostExecute(String result) {
        }

        @Override
        protected void onPreExecute() {
        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }

And now execute your AsyncTask

submitRequest.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if ( firstName.getText().toString().length() == 0 ) {
                firstName.setError("Please enter your first name!");
            }
            if ( firstName.getText().toString().length() != 0 ) {

                Toast.makeText(getApplicationContext(), firstName.getText().toString(), Toast.LENGTH_SHORT).show();

                new YourAsyncTaskName(firstName.getText().toString()).execute();


            } else {

            }
        }
    });
Kuls
  • 2,047
  • 21
  • 39