Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

With what can I replace http deprecated methods?

I was following a tutorial and I got to a point where a lot of the code is deprecated.

ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("name", user.name));
dataToSend.add(new BasicNameValuePair("age", user.age));

HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParamas.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
HttpConnectionParamas.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS + "Register.php");

try{
    post.setEntity(new UrlEncodedFormEntity(dataToSend));
    client.execute(post);
}catch (Exception e){
    e.printStackTrace();
}

and another POST method that is returning a result

    HttpResponse httpResponse = client.execute(post);

    HttpEntity entity = httpResponse.getEntity();
    String result = EntityUtils.toString(entity);
    JSONObject jObject = new JSONObject(result);

I found that I can replace NameValuePair with

ContentValues values = new ContentValues();
values.put("name", user.name);
values.put("age", user.age + "");

but I have no idea about the others.

like image 941
Bogdan Daniel Avatar asked May 01 '15 21:05

Bogdan Daniel


People also ask

What happens if we use deprecated methods in Android?

What happens if i continue using Deprecated methods? Code would continue running as it is until method is removed from SDK. If you are using deprecated method then you must keep track of removed apis whenever you upgrade to newest SDK. If you don't want a change at all then check for the reason behind deprecation.

How do you find deprecated functions?

Go to Code > Run Inspection by Name and click on it. A dialog box will open then type deprecated in the text field. You can now select the option based on your search for deprecated usages. On your selection, PHPStorm will automatically search for deprecated usages and list them down for you.


1 Answers

I found that I can replace NameValuePair with

Not really.

but I have no idea about the others

The entire HttpClient API that ships with Android itself is deprecated. The solution is to use a different HTTP client:

  • HttpUrlConnection, from standard Java
  • third-party ones, like OkHttp
  • Apache's repackaged HttpClient for Android

With respect to the tutorial, either:

  • Use tutorials that do not use a deprecated HTTP API, or
  • Port the tutorial to use Apache's repackaged HttpClient for Android, or
  • Ignore the deprecation warnings
like image 81
CommonsWare Avatar answered Oct 03 '22 14:10

CommonsWare