-1

I am new to android I know this question asked before many times but I can not find suitable solutions for my case. I want to send password and username to server and check it. It returns JSON object and I check on value of object if it is zero or one. The problem is getting message in catch

requested failed:android.os.networkonmainthreadException

that's my code

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_loginpage);
   editTextUserName = (EditText) findViewById(R.id.user);
    editTextPassword = (EditText) findViewById(R.id.password);
    message=(TextView) findViewById(R.id.mess);
    String username = editTextUserName.getText().toString();
    String password = editTextPassword.getText().toString();
    Button send =(Button)findViewById(R.id.send);
    send.setOnClickListener(
            new View.OnClickListener(){
                @Override
                public void onClick(View view) {

                  // invokeLogin();
                    clickbuttonRecieve();

                }
            }

    );
}


public void clickbuttonRecieve() {
    try {
        JSONObject json = new JSONObject();
        String username = editTextUserName.getText().toString();
        String password = editTextPassword.getText().toString();
        json.put("userName",username);
        json.put("password", password);
        int timeconnection=3000;
        HttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams,
                timeconnection);
        HttpConnectionParams.setSoTimeout(httpParams, timeconnection);
        HttpClient client = new DefaultHttpClient(httpParams);
        //
        //String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
        //             "json={\"UserName\":1,\"FullName\":2}";
        String url = "http://phone.tmsline.com/checkuser";

        HttpPost request = new HttpPost(url);
        request.setEntity(new ByteArrayEntity(json.toString().getBytes(
                "UTF8")));
        request.setHeader("json", json.toString());
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        // If the response does not enclose an entity, there is no need
        if (entity != null) {
            JSONObject jsonget = new JSONObject();
            String login = jsonget.getString("msg");
            if (login.toString().equalsIgnoreCase("1")){
                Toast.makeText(this, "Request success: " + login,
                        Toast.LENGTH_LONG).show();

            }
            else{
                Toast.makeText(this, "Request failed: " + login,
                        Toast.LENGTH_LONG).show();
            }

        }
    } catch (Throwable t) {
        Toast.makeText(this, "Request failed: " + t.toString(),
                Toast.LENGTH_LONG).show();
    }
}

php code(note : i didn't write php code , another one is responsible or that)

public function check_user(Request $request){
    $username = $request->username;
    $password = $request->password;
     if (Auth::attempt(['username' => $username, 'password' => $password])) {
    // return view('test',['user'=>$username]);
        return response()->json(['msg','1']);
}

return response()->json(['msg','0']);
}
Saugat Bhattarai
  • 2,614
  • 4
  • 24
  • 33
Shorouk Adel
  • 127
  • 3
  • 20

3 Answers3

0

You should use different thread to send HTTP requests rather than on main (UI) thread. You can simply use AsyncTask, Here is good example. Or even better to use volley or okhttp as they by default handles requests asynchronously.

Junaid Hafeez
  • 1,618
  • 1
  • 16
  • 25
0

requested failed:android.os.networkonmainthreadException

You cannot run network request in main thread. You should create new thread. The simplest way to get it is use Async Task https://stackoverflow.com/a/24399320/2717821

But in production it is not recommended. Very popular method is use RxJava https://github.com/ReactiveX/RxJava

Community
  • 1
  • 1
Deni Erdyneev
  • 1,779
  • 18
  • 26
0

I have changed your method(clickbuttonRecieve) and write Convertor Method for Convert InputStream To String(ConvertInputStreamToString):

public void clickbuttonRecieve() {
try {
    JSONObject json = new JSONObject();
    String username = editTextUserName.getText().toString();
    String password = editTextPassword.getText().toString();
    json.put("userName",username);
    json.put("password", password);
    int timeconnection=3000;
    HttpParams httpParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParams,
            timeconnection);
    HttpConnectionParams.setSoTimeout(httpParams, timeconnection);
    HttpClient client = new DefaultHttpClient(httpParams);
    //
    //String url = "http://10.0.2.2:8080/sample1/webservice2.php?" +
    //             "json={\"UserName\":1,\"FullName\":2}";
    String url = "http://phone.tmsline.com/checkuser";

    HttpPost request = new HttpPost(url);
    request.setEntity(new ByteArrayEntity(json.toString().getBytes(
            "UTF8")));
    request.setHeader("json", json.toString());
    HttpResponse response = client.execute(request);
    HttpEntity entity = response.getEntity();


    InputStream inputStream = response.getEntity().getContent();
    String result = ConvertInputStreamToString(inputStream);
    // If the response does not enclose an entity, there is no need
    if (result!= null) {
        JSONObject jsonget = new JSONObject(result);

       if(jsonget.has("msg")){
        String login = jsonget.getString("msg");
        if (login.toString().equalsIgnoreCase("1")){
            Toast.makeText(this, "Request success: " + login,
                    Toast.LENGTH_LONG).show();

        }
        else{
            Toast.makeText(this, "Request failed: " + login,
                    Toast.LENGTH_LONG).show();
        }
      }
    }
  } catch (Throwable t) {
    Toast.makeText(this, "Request failed: " + t.toString(),
            Toast.LENGTH_LONG).show();
  }
}

private static String ConvertInputStreamToString(InputStream inputStream)
        throws NaabException {
    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                inputStream));
        StringBuilder builder = new StringBuilder();

        String line = "";

        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
        return builder.toString();
    } catch (IOException e) {
        throw new NaabException(e);
    } catch (Exception e) {
        throw new NaabException(e);
    }

}
amin
  • 561
  • 6
  • 18