Getting data with JSON on Android

3

Hello, how do I get the data from a web-service 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 the use of a listview?

    
asked by anonymous 11.06.2015 / 19:56

4 answers

1

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

<?php 
  $data = $_POST; 
  // onde data deve ser um array
  return json_encode($data);
?>
    
11.06.2015 / 20:04
0

I did not quite understand. I want to just bring this data from PHP to android by turning them into an object, type the name for a variable name created in android java

    
12.06.2015 / 14:37
0

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

    
12.06.2015 / 16:14
0

How could you do this? Do you have any tutorials doing this? 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 this 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));
    
15.06.2015 / 19:42