How to return data with JSON?

0

I have the following code:

wd.setUrl("http://www.cordeiroit.com.br/SOUPROGRESSO/Ctrl/ServerUsuario.php");
wd.setMethod("new-usuario");

wd.setName(campoNome.getText().toString());
wd.setCpf(campoCpf.getText().toString());
wd.setBairro(campoBairro.getText().toString());
wd.setEmail(campoEmail.getText().toString());
wd.setTelefone(campoTelefone.getText().toString());

new Thread() {
    public void run() {
        answer = HttpConnection.getSetDataWeb(wd);

        runOnUiThread(new Runnable() {
            public void run() {

                try {
                    answer = Integer.parseInt(answer) == 1 ? "Cadastro efetuado com sucesso!" : "FALHA. Não foi possível enviar!";
                    Toast.makeText(GerenciarUsuarioActivity.this, answer, Toast.LENGTH_SHORT).show();
                }
                catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        });
    }
};

PHP:

<?php
    /*$f = fopen('POST_DATA.txt', 'a');

    fwrite($f, 'ID: '.$id."\r\n");

    $id = uniqid( time() );

    fwrite($f, 'Nome: '.$_POST['nome']."\r\n");
    fwrite($f, 'Cpf: '.$_POST['cpf']."\r\n");
    fwrite($f, 'Bairro: '.$_POST['bairro']."\r\n");
    fwrite($f, 'E-mail: '.$_POST['email']."\r\n");
    fwrite($f, 'Telefone: '.$_POST['telefone']."\r\n\r\n");

    fclose($f);

    echo 'Dados enviados com sucesso';*/

    /*$data = array('nome' => 'felipe',
    'email' => '',
    'bairro' => '', 
    'Telefone' => '');
    print (json_encode($data));

    //echo 'nome-SPDATA-idade-SPDATA-país'
?>

How do I return this data on Android?

I made the following code and it returns me the following error in HTTPClient when I give a system in the variable that returns the http:

package br.com.example.souprogresso;

// classe responsável por retornar o nosso usuário cadastrado

import android.app.Activity;
import android.os.Bundle;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import android.widget.TextView;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;

public class retornaUsuario extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost("http://www.cordeiro-it.com.br/SOUPROGRESSO/Ctrl/server2.php");
        TextView textView = (TextView)findViewById(R.id.txtMessage);

        System.out.println(httpPost);

        try
        {
            HttpResponse response = httpClient.execute(httpPost);
            String jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
            JSONObject object = new JSONObject(jsonResult);

            /*String nome = object.getString("nome");
            String cpf = object.getString("cpf");
            String bairro = object.getString("bairro");
            String email = object.getString("email");
            String telefone = object.getString("telefone");*/

            //System.out.println(nome);
        }
        catch(JSONException e)
        {
            // Ocorreu um erro
            System.out.println("Ocorreu um erro número 1");
            e.printStackTrace();
        }
        catch(ClientProtocolException e)
        {
            // Ocorreu um segundo erro
            System.out.println("Ocorreu um erro número 2");
            e.printStackTrace();
        }
        catch(IOException e)
        {
            // Ocorreu um terceiro erro
            System.out.println("Ocorreu um erro número 3");
            e.printStackTrace();
        }
    }

    private StringBuilder inputStreamToString(InputStream is)
    {
        String rLine = "";
        StringBuilder answer = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));

        try
        {
            while ((rLine = rd.readLine()) != null)
            {
                answer.append(rLine);
            }
        }
        catch(IOException e)
        {
            e.printStackTrace();
        }
        return answer;
    }
}

Error generated:

  

org.apache.http.client.methodos.HTTPPost@41088

stacktrace:

06-15 21:07:46.391: I/dalvikvm(5499): threadid=3: reacting to signal 3
06-15 21:07:46.451: I/dalvikvm(5499): Wrote stack traces to '/data/anr/traces.txt'
06-15 21:07:46.812: D/AndroidRuntime(5499): Shutting down VM
06-15 21:07:46.812: W/dalvikvm(5499): threadid=1: thread exiting with uncaught exception (group=0x409bf1f8)
06-15 21:07:46.831: E/AndroidRuntime(5499): FATAL EXCEPTION: main
06-15 21:07:46.831: E/AndroidRuntime(5499): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.example.souprogresso/br.com.example.souprogresso.retornaUsuario}: android.os.NetworkOnMainThreadException
06-15 21:07:46.831: E/AndroidRuntime(5499):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at android.os.Looper.loop(Looper.java:137)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at android.app.ActivityThread.main(ActivityThread.java:4424)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at java.lang.reflect.Method.invokeNative(Native Method)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at java.lang.reflect.Method.invoke(Method.java:511)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at dalvik.system.NativeStart.main(Native Method)
06-15 21:07:46.831: E/AndroidRuntime(5499): Caused by: android.os.NetworkOnMainThreadException
06-15 21:07:46.831: E/AndroidRuntime(5499):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at br.com.example.souprogresso.retornaUsuario.onCreate(retornaUsuario.java:33)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at android.app.Activity.performCreate(Activity.java:4466)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
06-15 21:07:46.831: E/AndroidRuntime(5499):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
06-15 21:07:46.831: E/AndroidRuntime(5499):     ... 11 more
06-15 21:07:46.931: I/dalvikvm(5499): threadid=3: reacting to signal 3
06-15 21:07:46.992: I/dalvikvm(5499): Wrote stack traces to '/data/anr/traces.txt'
06-15 21:07:47.002: D/dalvikvm(5499): GC_CONCURRENT freed 218K, 5% free 6706K/7047K, paused 6ms+3ms
06-15 21:07:47.411: I/dalvikvm(5499): threadid=3: reacting to signal 3
06-15 21:07:47.421: I/dalvikvm(5499): Wrote stack traces to '/data/anr/traces.txt'
06-15 21:07:50.391: I/Process(5499): Sending signal. PID: 5499 SIG: 9
06-15 21:12:53.851: I/dalvikvm(6092): threadid=3: reacting to signal 3
06-15 21:12:54.001: I/dalvikvm(6092): Wrote stack traces to '/data/anr/traces.txt'
06-15 21:12:54.191: I/System.out(6092): org.apache.http.client.methods.HttpPost@4105f948
06-15 21:12:54.231: D/AndroidRuntime(6092): Shutting down VM
06-15 21:12:54.231: W/dalvikvm(6092): threadid=1: thread exiting with uncaught exception (group=0x409bf1f8)
06-15 21:12:54.251: E/AndroidRuntime(6092): FATAL EXCEPTION: main
06-15 21:12:54.251: E/AndroidRuntime(6092): java.lang.RuntimeException: Unable to start activity ComponentInfo{br.com.example.souprogresso/br.com.example.souprogresso.retornaUsuario}: android.os.NetworkOnMainThreadException
06-15 21:12:54.251: E/AndroidRuntime(6092):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at android.app.ActivityThread.access$600(ActivityThread.java:123)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at android.os.Looper.loop(Looper.java:137)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at android.app.ActivityThread.main(ActivityThread.java:4424)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at java.lang.reflect.Method.invokeNative(Native Method)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at java.lang.reflect.Method.invoke(Method.java:511)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at dalvik.system.NativeStart.main(Native Method)
06-15 21:12:54.251: E/AndroidRuntime(6092): Caused by: android.os.NetworkOnMainThreadException
06-15 21:12:54.251: E/AndroidRuntime(6092):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at java.net.InetAddress.getAllByName(InetAddress.java:220)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at br.com.example.souprogresso.retornaUsuario.onCreate(retornaUsuario.java:35)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at android.app.Activity.performCreate(Activity.java:4466)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
06-15 21:12:54.251: E/AndroidRuntime(6092):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
06-15 21:12:54.251: E/AndroidRuntime(6092):     ... 11 more
06-15 21:12:54.381: I/dalvikvm(6092): threadid=3: reacting to signal 3
06-15 21:12:54.441: I/dalvikvm(6092): Wrote stack traces to '/data/anr/traces.txt'
06-15 21:12:54.451: D/dalvikvm(6092): GC_CONCURRENT freed 219K, 5% free 6710K/7047K, paused 4ms+3ms
06-15 21:12:54.821: I/dalvikvm(6092): threadid=3: reacting to signal 3
06-15 21:12:54.841: I/dalvikvm(6092): Wrote stack traces to '/data/anr/traces.txt'
06-15 22:32:45.741: I/Process(6092): Sending signal. PID: 6092 SIG: 9
    
asked by anonymous 16.06.2015 / 00:43

0 answers