___ ___ erkimt problems StrictMode.ThreadPolicy ______ qstntxt ___

Hello, I have the link below

link

handing me a string %code% % type

%pre%

So, in %code% , handle it with% %code% below:

%pre%

This %code% % works normally. However, you need to put the code snippet below;

%pre%

Otherwise, the connection to the internet is NOT established.

However, I've added the INTERNET access permission on the %code% .

%pre%

But no use.

If I remove this block of code

%pre%

The connection to %code% does not.

The problem is that if I work that way, as often as the ones I need to access the %code% % is the same number of times you have to make use of this code snippet.

Is not there a general configuration file for this in %code% %?

Following the %code% % JsonClass

%pre%     
______ azszpr352394 ___

What happens is that your %code% tries to access the network (a blocking operation) in the main Android thread, which is not allowed.

You can read more about this , but to summarize: A The main Android thread is responsible for updating the views.

Doing blocking tasks such as accessing the network or the database in this thread causes the view to crash, giving that impression of lag in the application.

The above link also gives you an alternative to solve this problem: do this type of tasks within AsyncTasks .

I particularly prefer to delegate all this work to libraries like Retrofit .

Doing what you want with this lib is very trivial:

After adding dependencies , define the contract on an interface:

%pre%

Starts the service instance:

%pre%

And to consume the service in a non-blocking way, just call:

%pre%

Now, within the callback %code% you already have the webservice response parseada and ready to use.

    
___

1

Hello, I have the link below

link

handing me a string json % type

{
  "clientes":[
     {
       "idClientesT":"1",
       "tipo":"s",
       "nome":"Carlos"},
     {
       "idClientesT":"2",
       "tipo":"s",
       "nome":"Rogério"
     }
  ]
}

So, in AndroidStudio , handle it with% Classe below:

package carcleo.com.radiosingular;

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

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import carcleo.com.radiosingular.classes.Clientes;
import carcleo.com.radiosingular.classes.JsonClass;

public class form extends AppCompatActivity {

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

    public void listaClientes (View View) {

        if (android.os.Build.VERSION.SDK_INT > 9){
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        String url = "http://hotplateprensas.com.br/ws/clientest.php";
        JsonClass json = new JsonClass();
        ArrayList<Clientes> clientesLista = json.getJSONFromUrl(url);

        Log.v("Cliente 2", clientesLista.get(1).getNome());

    }

}

This código % works normally. However, you need to put the code snippet below;

if (android.os.Build.VERSION.SDK_INT > 9){
   StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
   StrictMode.setThreadPolicy(policy);
}

Otherwise, the connection to the internet is NOT established.

However, I've added the INTERNET access permission on the AndroidManifest .

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="carcleo.com.radiosingular">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".login">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".form" />
    </application>

</manifest>

But no use.

If I remove this block of code

if (android.os.Build.VERSION.SDK_INT > 9){
   StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
   StrictMode.setThreadPolicy(policy);
}

The connection to INTERNET does not.

The problem is that if I work that way, as often as the ones I need to access the INTERNET % is the same number of times you have to make use of this code snippet.

Is not there a general configuration file for this in AndroidStudio %?

Following the classe % JsonClass

package carcleo.com.radiosingular.classes;

import android.util.Log;
import android.widget.Toast;

import com.google.gson.JsonArray;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Array;
import java.util.ArrayList;

import cz.msebera.android.httpclient.HttpEntity;
import cz.msebera.android.httpclient.HttpResponse;
import cz.msebera.android.httpclient.client.ClientProtocolException;
import cz.msebera.android.httpclient.client.methods.HttpPost;
import cz.msebera.android.httpclient.impl.client.DefaultHttpClient;

public class JsonClass {

    InputStream input = null;
    JSONObject jObect = null;
    String json = "";

    //Recebe sua url
    public ArrayList<Clientes> getJSONFromUrl(String url) {
        //HTTP request
        try {
            // default HttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            input = httpEntity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(input, "UTF-8"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            input.close();

            json = sb.toString();//

            // Transforma a String de resposta em um JSonObject
            jObect = new JSONObject(json);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        // retorna o objeto
        return Clientes(jObect);

    }

    private ArrayList<Clientes> Clientes (JSONObject jObect) {
       // Cria o Array List de Clientes
        ArrayList<Clientes> aCli = null;

        try {

            aCli = new ArrayList<>();
            //Pega o primeiro índice do Array de Objetos, no caso, o array Clientes
            JSONArray clientesLista = jObect.getJSONArray("clientes"); // aqui você faz o resgate da lista

            // Transforma a JSONArray de resposta em um Array de objjeo da Classe Clientes
            for (int i = 0; i < clientesLista.length(); i++) {
                //Pega cada íncide do array e atribui a uma variável
                JSONObject jSobj = clientesLista.getJSONObject(i);
                //Indetifica os campos do objeto
                int id =  Integer.parseInt(jSobj.getString("idClientesT"));
                //int id =  jSobj.getInt("idClientesT");
                String tipo = jSobj.getString("tipo");
                String nome = jSobj.getString("nome");
               //popula o objeto da classe de clientes
                Clientes cliente = new Clientes(id, tipo, nome);
                //Adiciona o objeto de Classe criado ào Array de Clientes
                aCli.add(cliente);
            }

        } catch (JSONException e) {
            Log.e("JSON Parser", "Erro no parsing doo objeto " + e.toString());
        }
        //Retorno o array de Clientes.
        return aCli;

    }

}
    
asked by anonymous 20.12.2018 / 14:43

1 answer

1

What happens is that your JsonClass tries to access the network (a blocking operation) in the main Android thread, which is not allowed.

You can read more about this , but to summarize: A The main Android thread is responsible for updating the views.

Doing blocking tasks such as accessing the network or the database in this thread causes the view to crash, giving that impression of lag in the application.

The above link also gives you an alternative to solve this problem: do this type of tasks within AsyncTasks .

I particularly prefer to delegate all this work to libraries like Retrofit .

Doing what you want with this lib is very trivial:

After adding dependencies , define the contract on an interface:

public interface HotPlateService {
  @GET("clientest.php")
  Call<List<Clientes>> listClientes();
}

Starts the service instance:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("http://www.hotplateprensas.com.br/ws/")
    .addConverterFactory(GsonConverterFactory.create())
    .build();

HotPlateService service = retrofit.create(HotPlateService.class);

And to consume the service in a non-blocking way, just call:

service.listClientes().enqueue(new Callback<List<Clientes>>() {
  @Override public void onResponse(Call<List<Clientes>> call, Response<List<Clientes>> response) {

  }

  @Override public void onFailure(Call<List<Clientes>> call, Throwable t) {

  }
});

Now, within the callback onResponse you already have the webservice response parseada and ready to use.

    
20.12.2018 / 18:25