-1

I want to create a login system in my android app. I want to send a json with username and password to a server and to get a response from it to make the validation. If I get code 200 I want to open the next activity and save the header I have gotten from the server for future usage. I also created a costum exception WrongCodeException. I know I am working on the main thread, but I don't want to change my entire application to do the system asyncronum. How can I solve AndroidRuntime: FATAL EXCEPTION: main android.os.NetworkOnMainThreadException without changing my entire aplication.

Login Activity

public class MainActivity extends AppCompatActivity {

private EditText etNumeUtilizator, etParola;
private TextView tvAutentificare;
private Button btnLogare;
String header;

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

    etNumeUtilizator = findViewById(R.id.etUserName);
    etParola = findViewById(R.id.etPassword);
    tvAutentificare = findViewById(R.id.tvAutentificare);
    btnLogare = findViewById(R.id.btnAutentificare);

    btnLogare.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String inputNumeUtilizator = etNumeUtilizator.getText().toString();
            String inputParola = etParola.getText().toString();


            if (inputNumeUtilizator.isEmpty() || inputParola.isEmpty()) {
                Toast.makeText(MainActivity.this, "Introduceti credentiale!", Toast.LENGTH_SHORT).show();
            } else {
                JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("username", inputNumeUtilizator);
                    jsonObject.put("password", inputParola);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                try {
                    validare(jsonObject);
                } catch (WrongCodeException e) {
                    e.printStackTrace();
                }
            }
        }
    });
}

private void validare(JSONObject jsonContent) throws WrongCodeException {
    OkHttpClient client = new OkHttpClient.Builder().build();
    RequestBody body = RequestBody.create(MediaType.get("application/json"), String.valueOf(jsonContent));
    Request request = new Request.Builder()
            .url(URL)
            .post(body)
            .build();
    try {
        Response response = client.newCall(request).execute();

        response.close();
        if (response.code() != 200) {
            Toast.makeText(MainActivity.this,
                    "Credentiale incorecte! Incercati din nou!" + response.code(),
                    Toast.LENGTH_SHORT).show();
            throw new WrongCodeException();
        } else {
            header = response.body().toString();
            Toast.makeText(MainActivity.this, "Credentiale corecte!", Toast.LENGTH_SHORT).show();
            Intent intent = new Intent(MainActivity.this, SelectSocketActivity.class);
            startActivity(intent);

        }
    } catch (IOException exception) {
        throw new WrongCodeException();
    }
}

}

WrongCodeException Exception public class WrongCodeException extends Exception{ }

1 Answers1

1

The right way to do it is making it asynchronous with a callback or AsyncTask, but you can try calling your method inside a Thread.

Thread thread = new Thread(new Runnable() {

    @Override
    public void run() {
        try  {
            validare();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
});
thread.start(); 

This should work