Skip to content

Instantly share code, notes, and snippets.

@MohammadSamandari
Created April 3, 2020 19:01
Show Gist options
  • Save MohammadSamandari/84aa3465f9dc1d7c743cfce47e175adb to your computer and use it in GitHub Desktop.
Save MohammadSamandari/84aa3465f9dc1d7c743cfce47e175adb to your computer and use it in GitHub Desktop.
Internet connection - hide keyboard - Parsing JSON data

Internet Connection

getting data from the internet using

see the NetworkUtils class to see how to get data from internet. also we can use the volley library to fetch data.

Hiding the keyboard Programatically

        //Hiding the keyboard after the button pressed.
        InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputManager != null) {
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }

checking the network status

To check the network connection, use the following classes:

  • ConnectivityManager answers queries about the state of network connectivity. It also notifies apps when network connectivity changes.
  • NetworkInfo describes the status of a network interface of a given type (currently either mobile or Wi-Fi).

The following code snippet tests whether Wi-Fi and mobile are connected. In the code:

private static final String DEBUG_TAG = "NetworkStatusExample";
ConnectivityManager connMgr = (ConnectivityManager)
           getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = 
           connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
boolean isWifiConn = networkInfo.isConnected();
networkInfo = 
           connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
boolean isMobileConn = networkInfo.isConnected();
Log.d(DEBUG_TAG, "Wifi connected: " + isWifiConn);
Log.d(DEBUG_TAG, "Mobile connected: " + isMobileConn);

More infromation here: https://developer.android.com/training/basics/network-ops/connecting.html

parsing JSON result.

this is a JSON file example:

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}

To find the value of an item in the response, use methods from the JSONObject and JSONArray classes. For example, here's how to find the "onclick" value of the third item in the "menuitem" array:

JSONObject data = new JSONObject(responseString);
JSONArray menuItemArray = data.getJSONArray("menuitem");
JSONObject thirdItem = menuItemArray.getJSONObject(2);
String onClick = thirdItem.getString("onclick");
package mohammad.samandari.whowroteit;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.ref.WeakReference;
public class FetchBook extends AsyncTask<String, Void, String> {
private static final String TAG = "Lord";
// Base URL for Books API.
private static final String BOOK_BASE_URL = "https://www.googleapis.com/books/v1/volumes?";
// Parameter for the search string.
private static final String QUERY_PARAM = "q";
// Parameter that limits search results.
private static final String MAX_RESULTS = "maxResults";
// Parameter to filter by print type.
private static final String PRINT_TYPE = "printType";
WeakReference<TextView> mTitleTextview, mAuthorTextview;
FetchBook (TextView titleTextview, TextView authorTextview) {
mTitleTextview = new WeakReference<>(titleTextview);
mAuthorTextview = new WeakReference<>(authorTextview);
}
@Override
protected String doInBackground (String... strings) {
try {
Uri buildUri = Uri.parse(BOOK_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, strings[0])
.appendQueryParameter(MAX_RESULTS, "10")
.appendQueryParameter(PRINT_TYPE, "books")
.build();
return NetworkUtils.GetData(buildUri);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute (String s) {
super.onPostExecute(s);
try {
JSONObject jsonObject = new JSONObject(s);
JSONArray jsonArray = jsonObject.getJSONArray("items");
int i = 0;
String TITLE = null;
String AUTHOR = null;
while (i < jsonArray.length() &&
(AUTHOR == null && TITLE == null)) {
// Get the current item information.
JSONObject book = jsonArray.getJSONObject(i);
JSONObject volumeInfo = book.getJSONObject("volumeInfo");
// Try to get the author and title from the current item,
// catch if either field is empty and move on.
try {
TITLE = volumeInfo.getString("title");
AUTHOR = volumeInfo.getString("authors");
} catch (Exception e) {
e.printStackTrace();
}
// Move to the next item.
i++;
}
if (TITLE != null && AUTHOR != null) {
mTitleTextview.get().setText(TITLE);
mAuthorTextview.get().setText(AUTHOR);
} else {
mTitleTextview.get().setText(R.string.no_result);
mAuthorTextview.get().setText("");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "onPostExecute: ", e);
// If onPostExecute does not receive a proper JSON string,
// update the UI to show failed results.
mTitleTextview.get().setText(R.string.no_result);
mAuthorTextview.get().setText("");
}
}
}
package mohammad.samandari.whowroteit;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.hardware.input.InputManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "Lord";
EditText searchEditText;
TextView titleTextview, authorTetview;
@Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
searchEditText = findViewById(R.id.searchEditText);
titleTextview = findViewById(R.id.titleTextview);
authorTetview = findViewById(R.id.authorTextview);
}
public void searchBook (View view) {
// Get the search string from the input field.
String SEARCH_QUERY = searchEditText.getText().toString();
//Hiding the keyboard after the button pressed.
InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputManager != null) {
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
//Getting the network info and connectivity state:
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = null;
if (connectivityManager != null) {
networkInfo = connectivityManager.getActiveNetworkInfo();
}
if (networkInfo != null && networkInfo.isConnected() && SEARCH_QUERY.length() != 0) {
//Updating the text iews so that the user know what is going on.
titleTextview.setText(R.string.loading);
authorTetview.setText(R.string.please_wait);
//Ask for the data over internet
new FetchBook(titleTextview, authorTetview).execute(SEARCH_QUERY);
} else {
if (SEARCH_QUERY.length() == 0) {
authorTetview.setText("");
titleTextview.setText(R.string.no_search_term);
} else {
authorTetview.setText("");
titleTextview.setText(R.string.no_connection);
}
}
}
public void searchVolley (View view) {
titleTextview.setText("Volley In Progress");
// Base URL for Books API.
String BOOK_BASE_URL = "https://www.googleapis.com/books/v1/volumes?";
// Parameter for the search string.
String QUERY_PARAM = "q";
// Parameter that limits search results.
String MAX_RESULTS = "maxResults";
// Parameter to filter by print type.
String PRINT_TYPE = "printType";
// Get the search string from the input field.
String SEARCH_QUERY = searchEditText.getText().toString();
Uri buildUri = Uri.parse(BOOK_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, SEARCH_QUERY)
.appendQueryParameter(MAX_RESULTS, "10")
.appendQueryParameter(PRINT_TYPE, "books")
.build();
// Instantiate the RequestQueue.
RequestQueue requestQueue = Volley.newRequestQueue(this);
String url = buildUri.toString();
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(StringRequest.Method.GET, url, new Response.Listener<String>() {
@Override
public void onResponse (String response) {
//Parse the result
parseResult(response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse (VolleyError error) {
//Error if there volley error
titleTextview.setText(error.toString());
}
});
requestQueue.add(stringRequest);
}
private void parseResult (String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray jsonArray = jsonObject.getJSONArray("items");
int i = 0;
String TITLE = null;
String AUTHOR = null;
while (i < jsonArray.length() &&
(AUTHOR == null && TITLE == null)) {
// Get the current item information.
JSONObject book = jsonArray.getJSONObject(i);
JSONObject volumeInfo = book.getJSONObject("volumeInfo");
// Try to get the author and title from the current item,
// catch if either field is empty and move on.
try {
TITLE = volumeInfo.getString("title");
AUTHOR = volumeInfo.getString("authors");
} catch (Exception e) {
e.printStackTrace();
}
// Move to the next item.
i++;
}
if (TITLE != null && AUTHOR != null) {
titleTextview.setText(TITLE);
authorTetview.setText(AUTHOR);
} else {
titleTextview.setText(R.string.no_result);
authorTetview.setText("");
}
} catch (JSONException e) {
e.printStackTrace();
Log.e(TAG, "onPostExecute: ", e);
// If onPostExecute does not receive a proper JSON string,
// update the UI to show failed results.
titleTextview.setText(R.string.no_result);
authorTetview.setText("");
}
}
}
package mohammad.samandari.whowroteit;
import android.net.Uri;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
public class NetworkUtils {
private static final String TAG = "Lord";
static String GetData (Uri uri) {
HttpURLConnection httpURLConnection = null;
BufferedReader reader = null;
String RESULT = null;
try {
URL requestUrl = new URL(uri.toString());
httpURLConnection = (HttpURLConnection) requestUrl.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.connect();
// Get the InputStream.
InputStream inputStream = httpURLConnection.getInputStream();
// Create a buffered reader from that input stream.
reader = new BufferedReader(new InputStreamReader(inputStream));
// Use a StringBuilder to hold the incoming response.
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
// Since it's JSON, adding a newline isn't necessary (it won't
// affect parsing) but it does make debugging a *lot* easier
// if you print out the completed buffer for debugging.
builder.append("\n");
}
if (builder.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
RESULT = builder.toString();
} catch (IOException e) {
e.printStackTrace();
Log.e(TAG, "getData: ", e);
} finally {
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Log.d(TAG, RESULT);
return RESULT;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment