Skip to content

Instantly share code, notes, and snippets.

@MohammadSamandari
Last active April 3, 2020 17:12
Show Gist options
  • Save MohammadSamandari/063d839855e73df0a6636d1182d70f11 to your computer and use it in GitHub Desktop.
Save MohammadSamandari/063d839855e73df0a6636d1182d70f11 to your computer and use it in GitHub Desktop.
Android - Hide keyboard Programatically - Get data from internet class - checking network status

Asynctask

getting data from the internet using

see the NetworkUtils class to see how to get data from internet.

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

        //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);
            }
        }
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.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;
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);
}
}
}
}
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