Does Using Slideshow Background Slow Computer
Near of us accept developed voracious appetites for new data, what with the Internet being such an important part of our lives. Our attending spans too are shorter than ever, so building Android applications whose content is static can be a bad idea. Instead, you should consider edifice applications that can brandish fresh content every time the user opens them.
That might sound hard, but with more and more websites exposing their resources through Balance APIs, it'southward really quite easy. (Encounter our Beginner'due south Guide to HTTP and Residuum for a primer.)
In this tutorial, I'grand going to show you how to utilise the classes and methods available in the Android SDK to connect to remote spider web servers and interact with them using their REST APIs.
i. Enabling Net Access
Making employ of a REST API obviously involves using the Internet. Withal, Android applications can access the Cyberspace only if they have theandroid.permission.INTERNET
permission. Therefore, before you start writing any networking code, you must make sure that the post-obituses-permission
tag is present in your project's manifest file:
<uses-permission android:proper noun="android.permission.INTERNET" />
Becauseandroid.permission.Net
is not considered a unsafe permission, you don't have to request for it during runtime on devices running API Level 23 or higher.
two. Creating Background Threads
The Android platform does non let you to run network operations on the main thread of the application. Therefore, all your networking code must belong to a background thread. AnAsyncTask
subclass has the following methods for performing work off the main thread:
-
onPreExecute()
: This method runs on the UI thread, and is used for setting up your task (like showing a progress bar). -
doInBackground()
: This is where you implement the code to execute the work that is to be performed on the separate thread. -
onProgressUpdate()
: This is invoked on the UI thread and used for updating progress in the UI (such as filling up a progress bar). -
onPostExecute()
: Again on the UI thread, this is used for updating the results to the UI in one case theAsyncTask
has finished loading.
individual form MyTask extends AsyncTask<Void, Void, Void> { // All your networking logic // should be hither }
If you lot want to acquire more most running operations in background threads, I propose you read this tutorial well-nigh groundwork operations from the Android From Scratch series.
iii. Creating an HTTP Connection
By using theopenConnection()
method of theURL
course, y'all can rapidly gear up up a connection to any REST endpoint. The return value ofopenConnection()
must be cast to an example of eitherHttpURLConnection
orHttpsURLConnection
, depending on whether the endpoint is accessed over HTTP or HTTPS. BothHttpURLConnection
andHttpsURLConnection
allow you to perform operations such equally calculation request headers and reading responses.
The following lawmaking snippet shows yous how to fix a connection with the GitHub API'southward root endpoint:
// Create URL URL githubEndpoint = new URL("https://api.github.com/"); // Create connectedness HttpsURLConnection myConnection = (HttpsURLConnection) githubEndpoint.openConnection();
Note thatHttpsURLConnection
is a subclass of theHttpURLConnection
form.
4. Adding Request Headers
Most websites that offer Residuum APIs desire to be able to identify your app uniquely. The easiest way to help them exercise and so is to include a uniqueUser-Agent
header in all your requests.
To add aUser-Agent
header to your request, you must utilise thesetRequestProperty()
method of theHttpURLConnection
object. For example, hither's how you gear up theUser-Agent
header tomy-rest-app-v0.ane:
myConnection.setRequestProperty("User-Agent", "my-rest-app-v0.ane");
Yous can add multiple headers to your asking by calling thesetRequestProperty()
method multiple times. For example, the post-obit code snippet adds anAccept
header and a customContact-Me
header:
myConnection.setRequestProperty("Accept", "application/vnd.github.v3+json"); myConnection.setRequestProperty("Contact-Me", "hathibelagal@example.com");
5. Reading Responses
Once you lot have passed all the asking headers, yous tin can check if you accept a valid response using thegetResponseCode()
method of theHttpURLConnection
object.
if (myConnection.getResponseCode() == 200) { // Success // Further processing hither } else { // Error treatment code goes here }
If theHttpURLConnection
form gets a redirect response code, such as301, information technology handles it automatically and follows the redirect. Therefore, ordinarily, you will not have to write whatever actress code to check for redirects.
If you get no errors, yous can at present call the getInputStream()
method to get a reference to the input stream of the connection.
InputStream responseBody = myConnection.getInputStream();
About Remainder APIs these days return data formatted as valid JSON documents. Therefore, instead of reading from theInputStream
object direct, I suggest you create anInputStreamReader
for it.
InputStreamReader responseBodyReader = new InputStreamReader(responseBody, "UTF-8");
6. Parsing JSON Responses
The Android SDK has a class calledJsonReader, which makes information technology very easy for you to parse JSON documents. You tin create a new instance of theJsonReader
class past passing theInputStreamReader
object to its constructor.
JsonReader jsonReader = new JsonReader(responseBodyReader);
How you extract a specific piece of information from the JSON document depends on its structure. For example, the JSON document returned by the root endpoint of GitHub'south Remainder API looks like this:
{ "current_user_url": "https://api.github.com/user", "current_user_authorizations_html_url": "https://github.com/settings/connections/applications{/client_id}", "authorizations_url": "https://api.github.com/authorizations", "code_search_url": "https://api.github.com/search/code?q={query}{&page,per_page,sort,order}", "emails_url": "https://api.github.com/user/emails", "emojis_url": "https://api.github.com/emojis", "events_url": "https://api.github.com/events", "feeds_url": "https://api.github.com/feeds", "followers_url": "https://api.github.com/user/followers", "following_url": "https://api.github.com/user/post-obit{/target}", "gists_url": "https://api.github.com/gists{/gist_id}", "hub_url": "https://api.github.com/hub", "issue_search_url": "https://api.github.com/search/issues?q={query}{&page,per_page,sort,order}", "issues_url": "https://api.github.com/bug", "keys_url": "https://api.github.com/user/keys", "notifications_url": "https://api.github.com/notifications", "organization_repositories_url": "https://api.github.com/orgs/{org}/repos{?type,page,per_page,sort}", "organization_url": "https://api.github.com/orgs/{org}", "public_gists_url": "https://api.github.com/gists/public", "rate_limit_url": "https://api.github.com/rate_limit", "repository_url": "https://api.github.com/repos/{owner}/{repo}", "repository_search_url": "https://api.github.com/search/repositories?q={query}{&page,per_page,sort,order}", "current_user_repositories_url": "https://api.github.com/user/repos{?type,page,per_page,sort}", "starred_url": "https://api.github.com/user/starred{/possessor}{/repo}", "starred_gists_url": "https://api.github.com/gists/starred", "team_url": "https://api.github.com/teams", "user_url": "https://api.github.com/users/{user}", "user_organizations_url": "https://api.github.com/user/orgs", "user_repositories_url": "https://api.github.com/users/{user}/repos{?blazon,page,per_page,sort}", "user_search_url": "https://api.github.com/search/users?q={query}{&folio,per_page,sort,society}" }
As you lot can come across, the response is simply one large JSON object that contains several keys. To excerpt the value of the key calledorganization_url
from it, you will have to write the following code:
jsonReader.beginObject(); // Starting time processing the JSON object while (jsonReader.hasNext()) { // Loop through all keys Cord fundamental = jsonReader.nextName(); // Fetch the next key if (central.equals("organization_url")) { // Cheque if desired key // Fetch the value every bit a String Cord value = jsonReader.nextString(); // Practice something with the value // ... break; // Intermission out of the loop } else { jsonReader.skipValue(); // Skip values of other keys }
The above code processes the JSON response as a stream of tokens. Therefore, it consumes very little retention. However, considering it has to process every single token one after another, information technology tin exist slow while treatment large responses.
Subsequently you've extracted all the required information, you must ever telephone call theclose()
method theJsonReader
object so that it releases all the resource it holds.
jsonReader.shut();
You must also close the connection past calling thedisconnect()
method of theHttpURLConnection
object.
myConnection.disconnect();
vii. Using Different HTTP Methods
HTTP-based REST interfaces use HTTP methods to decide the type of operation that has to be performed on a resource. In the previous steps, we made use of the HTTPGo
method to perform a read operation. Because theHttpURLConnection
grade uses theGo
method by default, we didn't have to specify it explicitly.
To change the HTTP method of yourHttpURLConnection
object, you lot must use itssetRequestMethod()
method. For example, the following code snippet opens a connection to an endpoint that belongs to httpbin.org and sets its HTTP method toPOST
:
URL httpbinEndpoint = new URL("https://httpbin.org/post"); HttpsURLConnection myConnection = (HttpsURLConnection) httpbinEndpoint.openConnection(); myConnection.setRequestMethod("Mail");
As you might already know,Mail service
requests are used to ship data to the server. By writing to the output stream of the connexion, you can easily add together any data to the body of thePostal service
request. Withal, before you do and so, you must make sure that you phone call thesetDoOutput()
method of theHttpURLConnection
object and passtruthful
to it.
The following code snippet shows you lot how to ship a simple fundamental-value pair to the server:
// Create the data String myData = "message=Hello"; // Enable writing myConnection.setDoOutput(true); // Write the data myConnection.getOutputStream().write(myData.getBytes());
8. Caching Responses
It is always a adept thought to cache HTTP responses. By doing and so, you lot tin can not only reduce your app'south bandwidth consumption, but as well make it more responsive. From API level 13 onwards, the Android SDK offers a course chosenHttpResponseCache
, which allows y'all to easily implement caching without making any changes to your networking logic.
To install a cache for your application, you lot must call theinstall()
method of theHttpResponseCache
form. The method expects an absolute path specifying where the cache must be installed and a number specifying the size of the enshroud. Y'all can employ the getCacheDir()
method if you don't want to specify the absolute path manually.
The post-obit code snippet installs a cache whose size is 100,000 bytes:
HttpResponseCache myCache = HttpResponseCache.install( getCacheDir(), 100000L);
Once the cache is installed, theHttpURLConnection
class starts using it automatically. To check if your enshroud is working, you can use itsgetHitCount()
method, which returns the number of HTTP responses that were served from the cache.
if (myCache.getHitCount() > 0) { // The enshroud is working }
How to Build an Android App With an API
Prerequisites
Before you lot beginning developing whatever Android app, you should install Android Studio and take the latest Android SDK installed through Android Studio.
Getting Started
Open up Android Studio and create a new projection with an empty action.
ClickNext, configure the settings as shown, and click Finish.
Wait a few minutes for Android Studio to create your projection files. Your project structure should at present expect similar this.
The adjacent thing is to addINTERNET
permissions in the manifest file. Go tomanifests/AndroidManifest.xml and enableINTERNET
permission for the app to access API calls.
<uses-permission android:name="android.permission.Net" />
Our app UI will consist of the following elements:
- a button
- a progress dialog
- a text view
When the user clicks on the button, the progress dialog volition brandish a message letting the user know the information is beingness candy. One time the data is fetched from the API, it will be displayed by the text view.
Open the activity_main.xml file and add together the components as shown below.
<?xml version="ane.0" encoding="utf-8"?> <LinearLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="30dp" tools:context=".MainActivity"> <Button android:id="@+id/displayData" android:layout_width="200dp" android:layout_height="wrap_content" android:layout_gravity="heart" android:layout_marginTop="20dp" android:text="Click to Show Users" android:textColor="@color/cardview_dark_background" android:textSize="18sp" /> <TextView android:id="@+id/results" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginTop="50dp" android:visibility="gone" android:textColor="@color/design_default_color_primary" android:textSize="18sp" /> </LinearLayout>
Define the URL and the UI components at the top of the Main_activity.java file.
public course MainActivity extends AppCompatActivity { String myUrl = "https://api.mocki.io/v1/a44b26bb"; TextView resultsTextView; ProgressDialog progressDialog; Button displayData; //the balance of the code }
Next, employfindViewById()
to hook the components on theonCreate
method.
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); resultsTextView = (TextView) findViewById(R.id.results); displayData = (Button) findViewById(R.id.displayData); }
Defining an AsyncTask
Create theAsyncTask
method for downloading network data from the API, and implement the onPreExecute()
, doInBackground()
, and onPostExecute()
methods.
public class MyAsyncTasks extends AsyncTask<String, Cord, String> { @Override protected void onPreExecute() { super.onPreExecute(); // display a progress dialog to show the user what is happening @Override protected String doInBackground(Cord... params) { // Fetch information from the API in the background. } @Override protected void onPostExecute(String s) { // show results } }
On theonPreExecute()
method, brandish a progress dialog that lets the user know what is happening.
@Override protected void onPreExecute() { super.onPreExecute(); // display a progress dialog for adept user experiance progressDialog = new ProgressDialog(MainActivity.this); progressDialog.setMessage("processing results"); progressDialog.setCancelable(simulated); progressDialog.bear witness(); }
On thedoInBackground
method, create a URL connection and read the data from the API. Surround the operation with try-catch clauses to take hold of any exceptions that might occur when fetching data from the API.
@Override protected String doInBackground(String... params) { // Fetch information from the API in the groundwork. String result = ""; try { URL url; HttpURLConnection urlConnection = nada; endeavor { url = new URL(myUrl); //open a URL coonnection urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = urlConnection.getInputStream(); InputStreamReader isw = new InputStreamReader(in); int data = isw.read(); while (information != -i) { issue += (char) information; information = isw.read(); } // return the data to onPostExecute method return upshot; } grab (Exception e) { e.printStackTrace(); } finally { if (urlConnection != nada) { urlConnection.disconnect(); } } } catch (Exception due east) { e.printStackTrace(); return "Exception: " + eastward.getMessage(); } return upshot; }
On theonPostExecute()
method, dismiss the progress dialog and display the results to the user with a text view.
@Override protected void onPostExecute(String s) { // dismiss the progress dialog after receiving data from API progressDialog.dismiss(); endeavour { JSONObject jsonObject = new JSONObject(due south); JSONArray jsonArray1 = jsonObject.getJSONArray("users"); JSONObject jsonObject1 =jsonArray1.getJSONObject(index_no); String id = jsonObject1.getString("id"); String name = jsonObject1.getString("name"); String my_users = "User ID: "+id+"\n"+"Name: "+proper name; //Show the Textview subsequently fetching data resultsTextView.setVisibility(View.VISIBLE); //Brandish data with the Textview resultsTextView.setText(my_users); } grab (JSONException e) { e.printStackTrace(); } }
Finally, prepare anonClickLIstener
on the button and executeMyAsyncTasks
when a user clicks the button.
// implement setOnClickListener event on displayData button displayData.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View five) { // create object of MyAsyncTasks class and execute it MyAsyncTasks myAsyncTasks = new MyAsyncTasks(); myAsyncTasks.execute(); } });
Last Consequence
Conclusion
There are thousands of REST APIs available for you to freely use in your Android apps. Past using them, you can brand your app more informative, interesting, and feature-rich. In this tutorial, you learned how to use theHttpURLConnection
class to consume such Residuum APIs and create an HTTP response enshroud that keeps your app's bandwidth usage low. You lot also learned how to fetch and display information from an API.
If yous think usingHttpURLConnection
is hard, yous should give third-party libraries such as Volley a effort. Libraries like this utilise theHttpURLConnection
grade internally, but provide lots of user-friendly methods that let yous to brand your lawmaking more concise and readable.
To learn more than about networking on the Android platform, you lot can refer to Android's Network Operations guide.
Does Using Slideshow Background Slow Computer,
Source: https://code.tutsplus.com/tutorials/android-from-scratch-using-rest-apis--cms-27117
Posted by: leeyoutive.blogspot.com
0 Response to "Does Using Slideshow Background Slow Computer"
Post a Comment