Post android error method

1

I would like to have the string username sent to the bank after the button is clicked, but it is giving error in the lines:

  

at com.example.thiago.myapplication.PostTest.tryLogin (PostTest.java:94)
  at com.example.thiago.myapplication.PostTest $ 1.onClick (PostTest.java:68)

Here's my code:

public class PostTeste extends AppCompatActivity {
    private Button button1;
    private EditText username;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);

        button1 = (Button) findViewById(R.id.button1);
        username = (EditText) findViewById(R.id.etpost);

        button1.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                String   mUsername = username.getText().toString();
               // String  mPassword = password.getText().toString();

                    tryLogin(mUsername);
            }
        });
    }

    protected void tryLogin(String mUsername)
    {
        HttpURLConnection connection;
        OutputStreamWriter request = null;

        URL url = null;
        String response = null;
        String parameters = "email="+mUsername;

        try
        {
            url = new URL("http://192.168.1.207/api/v2/bookdemo/_table/logins");
            connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setRequestProperty("Accept", "application/json");
            connection.setRequestProperty("X-DreamFactory-Api-Key", "XXXXXXXXXXXXXXXXXXXXXX");
            connection.setRequestProperty("X-DreamFactory-Session-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjE0LCJ1c2VyX2lkIjoxNCwiZW1haWwiOiJ0aGlhZ28uY2FtYXJnb0Bldm9sdXRpb25pdC5jb20uYnIiLCJmb3JldmVyIjpmYWxzZSwiaXNzIjoiaHR0cDpcL1wvMTkyLjE2OC4xLjIwN1wvYXBpXC92Mlwvc3lzdGVtXC9hZG1pblwvc2Vzc2lvbiIsImlhdCI6MTQ5NDUyMjk4OSwiZXhwIjoxNDk0NTI2NTg5LCJuYmYiOjE0OTQ1MjI5ODksImp0aSI6Ijg2NTNlOTRkM2E2ZmI0ZGM0YmY5OWFkNzNhNmU0N2QxIn0.XXXXXXXXXXXXXXXXXXXXXXXXXXxgYC0IGsdoGgUYps ");
            connection.setRequestProperty("Authorization", "dGhpYWdvLmNhbWFyZ29AZXZvbHV0aW9uaXQuY29tLmJyOmluaWNpYWwyMDE3");

            connection.setRequestMethod("POST");



            request = new OutputStreamWriter(connection.getOutputStream());
            request.write(parameters);
            request.flush();
            request.close();
            String line = "";
            InputStreamReader isr = new InputStreamReader(connection.getInputStream());
            BufferedReader reader = new BufferedReader(isr);
            StringBuilder sb = new StringBuilder();
            while ((line = reader.readLine()) != null)
            {
                sb.append(line + "\n");
            }
            // Response from server after login process will be stored in response variable.
            response = sb.toString();
            // You can perform UI operations here
            Toast.makeText(this,"Message from Server:"+ response, 0).show();
            isr.close();
            reader.close();

        }
        catch(IOException e)
        {
            // Error
        }
    }
}
    
asked by anonymous 11.05.2017 / 21:07

1 answer

1

In order for the application screen to not lock to the user, it is not possible to perform a large operation on the Application% UserInterface (UI)%.

Then, when making a request, you should create a AsyncTask

Here's an example:

/**
     * Classe que irá fazer a conexão fora da Thread da UI
     * Vamos passar uma String como parametro, e ao executar, vamos retornar outra STring
     */
    class TryLogin extends AsyncTask<String, Void, String>{

        /*
        Este método irá executar em background
         */
        @Override
        protected String doInBackground(String... params) {

            final String mUsername = params[0];
            if(null == mUsername){
                return "Username não informado";
            }

            HttpURLConnection connection;
            OutputStreamWriter request = null;

            URL url = null;
            String response = null;
            String parameters = "email="+mUsername;

            try
            {
                url = new URL("http://192.168.1.207/api/v2/bookdemo/_table/logins");
                connection = (HttpURLConnection) url.openConnection();
                connection.setDoOutput(true);
                connection.setRequestProperty("Accept", "application/json");
                connection.setRequestProperty("X-DreamFactory-Api-Key", "XXXXXXXXXXXXXXXXXXXXXX");
                connection.setRequestProperty("X-DreamFactory-Session-Token", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjE0LCJ1c2VyX2lkIjoxNCwiZW1haWwiOiJ0aGlhZ28uY2FtYXJnb0Bldm9sdXRpb25pdC5jb20uYnIiLCJmb3JldmVyIjpmYWxzZSwiaXNzIjoiaHR0cDpcL1wvMTkyLjE2OC4xLjIwN1wvYXBpXC92Mlwvc3lzdGVtXC9hZG1pblwvc2Vzc2lvbiIsImlhdCI6MTQ5NDUyMjk4OSwiZXhwIjoxNDk0NTI2NTg5LCJuYmYiOjE0OTQ1MjI5ODksImp0aSI6Ijg2NTNlOTRkM2E2ZmI0ZGM0YmY5OWFkNzNhNmU0N2QxIn0.XXXXXXXXXXXXXXXXXXXXXXXXXXxgYC0IGsdoGgUYps ");
                connection.setRequestProperty("Authorization", "dGhpYWdvLmNhbWFyZ29AZXZvbHV0aW9uaXQuY29tLmJyOmluaWNpYWwyMDE3");

                connection.setRequestMethod("POST");



                request = new OutputStreamWriter(connection.getOutputStream());
                request.write(parameters);
                request.flush();
                request.close();
                String line = "";
                InputStreamReader isr = new InputStreamReader(connection.getInputStream());
                BufferedReader reader = new BufferedReader(isr);
                StringBuilder sb = new StringBuilder();
                while ((line = reader.readLine()) != null)
                {
                    sb.append(line + "\n");
                }
                // Response from server after login process will be stored in response variable.
                response = sb.toString();
                /**
                 Não podemos interar com a tela!, vamos mandar para o método onPostExecute
                 */
                // Toast.makeText(this,"Message from Server:"+ response, 0).show();
                isr.close();
                reader.close();
                return response;

            }
            catch(IOException e)
            {
                e.printStackTrace();
                return e.getMessage();
            }

        }
  /**
     * Este método irá rodar na Thread de UI após executar a ação! 
     * @param s
     */

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
            if(s != null){
                Toast.makeText(getApplicationContext(),  s, Toast.LENGTH_SHORT).show();
            }
        }
    }

This could be a sub SubClasse , within its Thread !

To invoke your AsyncTask do the following:

new TryLogin().execute("ThiagoDomacoski");
    
11.05.2017 / 21:21