Log in to Webservice via Android

Asked

Viewed 2,708 times

3

And there folks all quiet?

My question is this::

I’m trying to create a login screen on Android and the registered data is in a Mysql database, to establish the communication I have a working Rest Webservice, the question is: I am sending a GET to my server if it finds the data I requested it return me the login and password after I take this data and compare with those that were typed by the user, I believe that this is not the best way to make an authentication. I would like after the login has been done on the next screen to appear the name of the person who logged in.

Follow below my Android client classes:

User class

public class Usuariorest {

private static final String URL_WS = "http://10.1.1.103:8084/ServidorWS/webresources/Usuario/";


public Usuario getUsuario(String login) throws Exception {

     String[] resposta = new Webservice().get(URL_WS+"Usuario/buscarLogin/"+login);

     if (resposta[0].equals("200")) {
         Gson gson = new Gson();
         Usuario usuario = gson.fromJson(resposta[1], Usuario.class);
         return usuario;
     } else {
         throw new Exception(resposta[1]);
     }
}

Webservice class

public class Webservice {

private HttpEntity entity;

public final String[] get(String url) {

     String[] result = new String[2];

     try {
         HttpGet httpget = new HttpGet(url);
         HttpResponse response;
         response = HttpClient.getHttpClientInstace().execute(httpget);
         entity = response.getEntity();

         if (entity != null) {
             result[0] = String.valueOf(response.getStatusLine().getStatusCode());
             InputStream instream = entity.getContent();
             result[1] = toString(instream);
             instream.close();
             Log.i("get", "Resultado para o post JsonPost : " + result[0] + " : " + result[1]);
         }
     } catch (Exception e) {
         Log.e("NGVL", "Falha ao acessar Web service", e);
         //Log.e("NGVL", e.toString(), e);
         result[0] = "0";
         result[1] = "Falha de rede!";
     }
     return result;
    }

Mainactivity

public class Mainactivity extends Activity {

//private String id;
private String login;  
private String senha; 



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


    final EditText editLogin = (EditText) findViewById(R.id.txtLogin);
    final EditText editSenha = (EditText) findViewById(R.id.txtSenha);
    final TextView text = (TextView)findViewById(R.id.textView1);
    Button btnLogar = (Button) findViewById(R.id.butLogar);


    btnLogar.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {       

        AsyncTask<String, Void, Usuario> atBuscaUsuario = new AsyncTask<String, Void, Usuario>() {
        ProgressDialog progressDialog;


        @Override
        protected Usuario doInBackground(String... params) {
            login = editLogin.getText().toString();
            senha = editSenha.getText().toString();
            try {
                //testo se os campos login ou senha estão vazios
                if(editLogin.getText().toString().trim().equals("")){ 
                        gerarToast("Digite um login!");
                }else
                    if(editSenha.getText().toString().trim().equals("")){
                        gerarToast("Digite uma senha!");
                }else{
                    UsuarioREST rest = new UsuarioREST();
                    Usuario usuario = rest.getUsuario(login);
                    return usuario;
                }
            } catch (NumberFormatException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
                gerarToast(e.getMessage());
            }
            return null;
        }


        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(MainActivity.this, "Aguarde", "Efetuando login...");
        }



        @Override
        protected void onPostExecute(Usuario usuario) {
            super.onPostExecute(usuario);

            if (usuario != null) {
                 if(login.equals(usuario.getLogin().toString().trim()) && senha.equals(usuario.getSenha().toString().trim())){
                    Intent i = new Intent(MainActivity.this, PedidosActivity.class);
                    startActivity(i);

                 }else{
                     gerarToast("Senha incorreta!");
                 }
                //text.setText(usuario.getSenha().toString().trim());
            }

            progressDialog.dismiss();
        }
    };
    atBuscaUsuario.execute(login);
}



private void gerarToast(final String msg) {

    MainActivity.this.runOnUiThread(new Runnable() {
        @Override
        public void run() {
            Toast.makeText(MainActivity.this, msg, Toast.LENGTH_LONG).show();
        }
    });

        }//fim do metodo onClick




    });//fim do evento setOnClickListener

}

  • Just to understand: The login is an Activity, and the Main screen (which you want the name to appear) is another Activity? You can add "extras" as parameter in the Call Intent to capture the value on the other screen.

  • See if this example helps: http://stackoverflow.com/questions/4233873/how-do-i-get-extra-data-intent-on-android

  • @Geferson The login screen is the main Activity (Mainactivity), my goal is to authenticate and then the user would be redirected to another Activity and in that Activity will have the options that it can execute, and of course since the user x logged in then would like his name to appear somewhere in this secondary Activity.

  • 1

    What you can do is what was suggested above, when calling Intent pass the login/name as extra, and in the other Activity, can be on onCreate, recover it with String s = getIntent(). getStringExtra("username");

  • Solved your doubt?

No answers

Browser other questions tagged

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