Consuming JSON webservice with the use of Asynctaks

Asked

Viewed 1,100 times

1

Well, I’m trying to make an application that logs into a database, previously I was using the thread method to get, this working, but at the time of informing the error messages on the screen, or something like that, was not so. I modified to use asyncTaks, but the error is continuing.

LOG USING ASSYNC:

05-25 08:32:14.444    4091-4091/com.example.hotsystems.hs_celulas E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.hotsystems.hs_celulas, PID: 4091
android.os.NetworkOnMainThreadException
        at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1145)
        at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
        at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
        at libcore.io.IoBridge.connect(IoBridge.java:112)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
        at java.net.Socket.connect(Socket.java:843)
        at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
        at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
        at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
        at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
        at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
        at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
        at com.example.hotsystems.hs_celulas.Connection.getSetDataWeb(Connection.java:31)
        at com.example.hotsystems.hs_celulas.MainActivity.callServer(MainActivity.java:121)
        at com.example.hotsystems.hs_celulas.MainActivity.access$000(MainActivity.java:17)
        at com.example.hotsystems.hs_celulas.MainActivity$1.onClick(MainActivity.java:51)
        at android.view.View.performClick(View.java:4438)
        at android.view.View$PerformClick.run(View.java:18422)
        at android.os.Handler.handleCallback(Handler.java:733)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:136)
        at android.app.ActivityThread.main(ActivityThread.java:5017)
        at java.lang.reflect.Method.invokeNative(Native Method)
        at java.lang.reflect.Method.invoke(Method.java:515)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
        at dalvik.system.NativeStart.main(Native Method)

My main code is like this:

 protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_hs_cell);

    //Chamar os objetos
    email = (EditText) findViewById(R.id.TXT_EMAIL_LOGIN);
    senha = (EditText) findViewById(R.id.TXT_SENHA_LOGIN);
    cod_igrej = (EditText) findViewById(R.id.COD_IGREJ_LOGIN);
    entrar = (Button) findViewById(R.id.BTN_ENTRA_APLIC);
    sair = (Button) findViewById(R.id.BTN_SAIRX_APLIC);



    entrar.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View view) {
            Usuario usr = new Usuario();

            String json = generateJson(usr);
            callServer("send-json", json);

        }
    });

And the part about callServer:

private void callServer(final String method, final String data){
    final ProgressDialog progresso = new ProgressDialog(this);
    progresso.setMessage("Entrando");
    progresso.show();
     asw = Connection.getSetDataWeb("http://192.168.1.20/renan/process.php", method, data);

    new AsyncTask<String, String, String>(){



        protected void onPreExecute(){
            progresso.setMessage("Aguarde");

        }
        protected String doInBackground(String... asw){
            if(asw.equals("3"))
                progresso.setMessage("Creaódigo da igreja inesistente, por favor escreva um código válido.");
            else if (asw.equals("2")){
                progresso.setMessage("Senha incorreto, por favor escreva uma senha válida.");
                // makeText(MainActivity.this, "Senha incorreto, por favor escreva uma senha válida.", LENGTH_SHORT).show();
            }else if (asw.equals("1"))
            {
                progresso.setMessage("E-mail incorreto, por favor escreva um email válido.");
                // makeText(MainActivity.this, "E-mail incorreto, por favor escreva um email válido.", LENGTH_SHORT).show();
            }

            return null;
        }
        protected void onProgressUpdate(){

        }
        protected void onPostExecute(){
            progresso.setMessage("Seja Bem vindo.");
            progresso.show();
            Intent it = new Intent(MainActivity.this, MC_Home.class);
            startActivity(it);
            progresso.dismiss();

        }



         /*public void run(){

            if (data.isEmpty()){
                degenerateJson(asw);
           }

             Atividade_Entrar(asw, null,null);
             //makeText(MainActivity.this, "Código da igreja inesistente, por favor escreva um código válido.", LENGTH_SHORT).show();

        }*/
    }.execute();
   }

}

Class Conection:

package com.example.hotsystems.hs_celulas;

import android.app.Activity;

import java.io.IOException;
import java.util.ArrayList;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class Connection extends Activity{
    public static String getSetDataWeb(String url, String method, String data){

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);
        String answer = "";

        try{
            ArrayList<NameValuePair> valores = new ArrayList<NameValuePair>();
            valores.add(new BasicNameValuePair("method", method));
            valores.add(new BasicNameValuePair("json", data));

            httpPost.setEntity(new UrlEncodedFormEntity(valores));
            HttpResponse resposta = httpClient.execute(httpPost);
            answer = EntityUtils.toString(resposta.getEntity());
        }
        catch(NullPointerException e){ e.printStackTrace(); }
        catch(ClientProtocolException e){ e.printStackTrace(); }
        catch(IOException e){ e.printStackTrace(); }

        return(answer);
    }
}

1 answer

3


The exception Networkonmainthreadexception is launched when a program target API level 11 or higher accesses the internet on application’s main thread.

From what I see in your code what probably (I don’t know what this class is Connection) is provoking that is the line:

asw = Connection.getSetDataWeb("http://192.168.1.20/renan/process.php", method, data);  

If applicable, pass it into the method doInBackground can solve the problem.

From the Api level 9, Android, introduced a mechanism to alert the programmer when he, inadvertently or not, accesses the disk or the network(network) in application’s main thread. This mechanism makes an exception when this happens.

This behavior can be disabled by placing the following code in the method onCreate() of Activity:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);

The code that is in the method getSetDataWeb() must be executed asynchronously, must use its Asynctask to execute it.

She must be something like this:

private ProgressDialog progresso = new ProgressDialog(this);

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

    private String url, method, data;

    public GetSetDataWeb(String url, String method, String data){
        this.url = url;
        this.method = method;
        this.data = data;
    }


    @Override
    protected void onPreExecute() {

        progresso.setMessage("Aguarde...");
        progresso.show();
    }


    protected String doInBackground(Void... params) {
        String answer = "";
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        try{
            ArrayList<NameValuePair> valores = new ArrayList<NameValuePair>();
            valores.add(new BasicNameValuePair("method", method));
            valores.add(new BasicNameValuePair("json", data));

            httpPost.setEntity(new UrlEncodedFormEntity(valores));
            HttpResponse resposta = httpClient.execute(httpPost);
            answer = EntityUtils.toString(resposta.getEntity());
        }
        catch(NullPointerException e){ e.printStackTrace(); }
        catch(ClientProtocolException e){ e.printStackTrace(); }
        catch(IOException e){ e.printStackTrace(); }
        return answer;
    }


    protected void onPostExecute(String result) {
        progresso.dismiss();
        if(result.equals("3")){
            Toast.makeText(MainActivity.this, "Código da igreja inesistente, por favor escreva um código válido.", 
                   Toast.LENGTH_SHORT).show();
             return;
        }else if (result.equals("2")){
            Toast.makeText(MainActivity.this, "Senha incorreto, por favor escreva uma senha válida.", 
                           Toast.LENGTH_SHORT).show();
             return;
        }else if (result.equals("1"))
        {
            progresso.setMessage("E-mail incorreto, por favor escreva um email válido.");
            Toast.makeText(MainActivity.this, "E-mail incorreto, por favor escreva um email válido.",
                           Toast.LENGTH_SHORT).show();
            return;
        }

        Toast.makeText(MainActivity.this, "Seja bem vindo", Toast.LENGTH_SHORT).show();
        Intent it = new Intent(MainActivity.this, MC_Home.class);
        startActivity(it);
    }

}

Put this code on Mainactivity and to call the service do so:

new GetSetDataWeb("http://192.168.1.20/renan/process.php", method, data).execute();
  • If in case I put it inside the Ackground, it gives an error, and does not let me compile the program. Incompatibility of types.

  • What class is this: Connection?

  • It’s the class that does all the dirty work, of actually connecting to the webservice, and such.

  • So you really have to go inside doInBackgroud. What does she return?

  • It returns me a number, if it is 3 is the code that is wrong, if it is 2 is the password and if it is 1 is the email. However I need to send him the url, and tbem the method, besides the date, this date, is because if it is to send an acquisition in the form of json. got ?

  • All that code you posted is on Activity Connection?

  • Yes, it’s actually in the main, and it has a Connection class, where I call her to do the job.

  • please, it all worked out, but at the moment it validates, and wrong he enters the program, as I do for when it validates and goes wrong, he abort, and not let the person access the page ?

  • I think when you say you’re on the page you mean you’re on the Activity Mc_home. By mistake I didn’t include a return after each Toast. At the end of each if(result.equals()) it is necessary to put return

  • Is to put only the Return ? no place link

  • I don’t understand what you mean. What the code in the onPostExecute is to hide the Progressdialog and analyze the result. If 1,2 or 3 shows the corresponding message using a Toast and leaves, if not, to present the message "Welcome" and opens the Activity Mc_home.

  • I conceguir here, thank you very much, you helped me a lot in this part of my project.

Show 7 more comments

Browser other questions tagged

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