How to Catch Data with JSON on Android

Asked

Viewed 1,244 times

4

Hello how do I get the data from a web-service that I have?

I have the following code in JAVA Android to save the information:

        wd.setUrl("http://www.cordeiro-it.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(); 
                            }
                        }
                });
            }
        };
     }

Then the WD class:

package br.com.example.souprogresso.domain;

public class WrapData {
private String url;
private String method;
private String nome;
private String cpf;
private String bairro;
private String email;
private String telefone;

public WrapData(String url, String method, String nome, String cpf, String bairro, String email, 
String telefone     
){
    this.url = url;
    this.method = method;
    this.nome = nome;
    this.cpf = cpf;
    this.bairro = bairro;
    this.email = email;
    this.telefone = telefone;

}
public String getUrl() {
    return url;
}
public void setUrl(String url) {
    this.url = url;
}
public String getMethod() {
    return method;
}
public void setMethod(String method) {
    this.method = method;
}
public String getName() {
    return nome;
}
public void setName(String nome) {
    this.nome = nome;
}
public String getCpf() {
    return cpf;
}
public void setCpf(String cpf) {
    this.cpf = cpf;
}
public String getBairro() {
    return bairro;
}
public void setBairro(String bairro) {
    this.bairro = bairro;
}
public String getEmail() {
    return email;
}
public void setEmail(String email) {
    this.email = email;
}
public String getTelefone() {
    return telefone;
}
public void setTelefone(String telefone) {
    this.telefone = telefone;
}

}

And PHP

<?php

session_start();

    if(preg_match('/^(save-form){1}$/', $_POST['method'])){
        fwrite($f, 'ID: '.$id."\r\n");
        $id = uniqid( time() );
        $f = fopen('USUARIO.txt', 'w');


        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 '1';
    }
?>

How to return this data to android without using a listview?

  • You meant to return the data you sent or returned from the web service?

4 answers

1

Try to return your post as in the example below, if this is what you need, I advise you to handle the post data before sending the array.

<?php 
  $data = $_POST; 
  // onde data deve ser um array
  return json_encode($data);
?>

0

I don’t quite understand. I just want to bring this PHP data to android turning them into an object, like bring the name to a name variable created in android java

0

You can create an object in java exactly like the json that will return in php and use the Gson library to do the conversion.

0

How could you do that? Do you have any tutorial doing that? I’m trying the following code, but I’m not getting it:

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/ServerUsuario.php");
    //TextView textView = (TextView)findViewById(R.id.txtMessage);

    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;
}

}

In that I created an array in php as follows:

$data = array('nome' => '.$_POST['nome'].', 'cpf'=> '.$_POST['cpf'].', 'bairro'=> '.$_POST['bairro'].', 'email' => '.$_POST['email'].', 'telefone' => '.$_POST['telefone'].');

    print (json_encode($data));

Browser other questions tagged

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