Moudiz
Moudiz

Reputation: 7377

send data using okhttp without async task

Can I use this way to upload string to server using Okhttp ?

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.register);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

     usernam = (EditText) findViewById(R.id.username);
     passw = (EditText) findViewById(R.id.password);
     email = (EditText) findViewById(R.id.email);

     name = usernam.getText().toString();
     pass = passw.getText().toString();
     emails = email.getText().toString();

}


private final OkHttpClient client = new OkHttpClient();

public void run() throws Exception {
    String json = "";

    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("name",name );
    jsonObject.accumulate("password",pass );
    jsonObject.accumulate("email",emails );

    json = jsonObject.toString();

    RequestBody formBody = new FormEncodingBuilder()
            .add("result", json)
            .build();
    Request request = new Request.Builder()
            .url("https://justedhak.comlu.com/receiver.php")
            .post(formBody)
            .build();

    Response response = client.newCall(request).execute();
    if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);

    System.out.println(response.body().string());
}

Upvotes: 1

Views: 1950

Answers (2)

BNK
BNK

Reputation: 24114

If you want to use OkHttp without AsyncTask, you can refer to the following sample code, hope this helps!

public class MainActivity extends AppCompatActivity {
    private static final String LOG_TAG = "OkHttp";
    private TextView mTextView;
    private Handler mHandler;
    private String mMessage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mTextView = (TextView) findViewById(R.id.textView);
        mHandler = new Handler(Looper.getMainLooper());
        OkHttpClient client = new OkHttpClient();
        // GET request
        Request request = new Request.Builder()
                .url("http://...")
                .build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                mMessage = e.toString();
                Log.e(LOG_TAG, mMessage); // no need inside run()
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mTextView.setText(mMessage); // must be inside run()
                    }
                });
            }

            @Override
            public void onResponse(Response response) throws IOException {
                mMessage = response.toString();
                Log.i(LOG_TAG, mMessage); // no need inside run()
                mHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        mTextView.setText(mMessage); // must be inside run()
                    }
                });
            }
        });
    }
}

Upvotes: 2

Will Evers
Will Evers

Reputation: 942

network calls must be completed off of the UI thread, so no.

Also you never call your Run() method in your activity, so it would not be executed

EDIT: Max Pino is correct in that RXJava can be used to make this kind of call easily, however, that will still execute the call on a different thread

Upvotes: 1

Related Questions