Skip to content

Instantly share code, notes, and snippets.

@asafstr2
Created June 12, 2018 15:10
Show Gist options
  • Save asafstr2/0d86f9f59a3027470f8b891041e385a6 to your computer and use it in GitHub Desktop.
Save asafstr2/0d86f9f59a3027470f8b891041e385a6 to your computer and use it in GitHub Desktop.
newsApp by A.S presenting thev news from guardian has swipe for refresh and parsing photo from url using picaso
package androidcodesnippets.me.cfsuman.com.newsapp;
import android.graphics.Bitmap;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import com.squareup.picasso.Transformation;
public class CircleTransform implements Transformation {
private final int radius;
private final int margin; // dp
// radius is corner radii in dp
// margin is the board in dp
public CircleTransform(final int radius, final int margin) {
this.radius = radius;
this.margin = margin;
}
@Override
public Bitmap transform(final Bitmap source) {
final Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setShader(new BitmapShader(source, Shader.TileMode.CLAMP,
Shader.TileMode.CLAMP));
Bitmap output = Bitmap.createBitmap(source.getWidth(),
source.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
canvas.drawRoundRect(new RectF(margin, margin, source.getWidth()
- margin, source.getHeight() - margin), radius, radius, paint);
if (source != output) {
source.recycle();
}
return output;
}
@Override
public String key() {
return "rounded";
}
}
package androidcodesnippets.me.cfsuman.com.newsapp;
import android.content.Context;
import android.content.Intent;;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.Loader;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderCallbacks<List<NewsApp>> {
private static final int NEWSAPP_LOADER_ID = 1;
private static final String LOG_TAG = MainActivity.class.getSimpleName();
private static final String USGS_REQUEST_URL =
"https://content.guardianapis.com/search?show-tags=contributor&show-fields=thumbnail&api-key=test";
private NewsAppAdapter mAdapter;
private TextView mEmptyStateTextView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView newsListView = (ListView) findViewById(R.id.list);
mEmptyStateTextView = (TextView) findViewById(R.id.empty_view);
newsListView.setEmptyView(mEmptyStateTextView);
mAdapter = new NewsAppAdapter(this, new ArrayList<NewsApp>());
newsListView.setAdapter(mAdapter);
newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
NewsApp currentNews = mAdapter.getItem(position);
Uri newsUri = Uri.parse(currentNews.getUrl());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, newsUri);
startActivity(websiteIntent);
}
});
final ConnectivityManager connMgr = (ConnectivityManager)
getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
SwipeRefreshLayout swipe = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
swipe.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
SwipeRefreshLayout swipe = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(NEWSAPP_LOADER_ID, null, MainActivity.this);
Toast.makeText(getApplicationContext(), R.string.refreshed_successfully, Toast.LENGTH_LONG).show();
} else {
ProgressBar loader2 = findViewById(R.id.loading_spinner);
ListView earthquakeListView = (ListView) findViewById(R.id.list);
loader2.setVisibility(View.GONE);
earthquakeListView.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_internet_connection);
mEmptyStateTextView.setVisibility(View.VISIBLE);
swipe.setRefreshing(false);
}
}
}
);
if (networkInfo != null && networkInfo.isConnected())
{
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(NEWSAPP_LOADER_ID, null, this);
} else
{
View loadingIndicator = findViewById(R.id.loading_spinner);
loadingIndicator.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_internet_connection);
}
}
@Override
public Loader<List<NewsApp>> onCreateLoader(int i, Bundle bundle) {
return new NewsAppLoader(this, USGS_REQUEST_URL);
}
@Override
public void onLoadFinished(Loader<List<NewsApp>> loader, List<NewsApp> news) {
SwipeRefreshLayout swipe = (SwipeRefreshLayout) findViewById(R.id.swiperefresh);
View loadingIndicator = findViewById(R.id.loading_spinner);
loadingIndicator.setVisibility(View.GONE);
mEmptyStateTextView.setText(R.string.no_news_found);
mAdapter.clear();
if (news != null && !news.isEmpty()) {
mAdapter.addAll(news);
}
swipe.setRefreshing(false);
}
@Override
public void onLoaderReset(Loader<List<NewsApp>> loader) {
mAdapter.clear();
}
}
package androidcodesnippets.me.cfsuman.com.newsapp;
public class NewsApp {
private String mTitle;
private String mDate;
private String mUrl;
private String mAuthor;
private String mThumbNail;
NewsApp(String title, String author, String webPublicationDate, String url,String thumbNail) {
mTitle = title;
mAuthor = author;
mDate = webPublicationDate;
mUrl = url;
mThumbNail=thumbNail;
}
String getTitle() {return mTitle; }
String getAuthor() {return mAuthor;}
String getDate() {return mDate; }
String getUrl() {return mUrl;}
String getThumbNail() { return mThumbNail;}
}
package androidcodesnippets.me.cfsuman.com.newsapp;
import android.content.Context;
import android.content.res.Resources;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import com.squareup.picasso.Picasso;
public class NewsAppAdapter extends ArrayAdapter<NewsApp> {
private static final String LOCATION_SEPARATOR = "T";
private Resources mResources;
NewsAppAdapter(Context context, ArrayList<NewsApp> EarthQuakes) {
super(context, 0, EarthQuakes);
mResources = getContext().getResources();
}
@NonNull
@Override
public View getView(int position, View convertView, @NonNull ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
}
NewsApp currentPlace = getItem(position);
TextView authorTextView = listItemView.findViewById(R.id.author);
String output = currentPlace.getAuthor();
authorTextView.setText(output);
TextView dateTextView = listItemView.findViewById(R.id.date);
String date = currentPlace.getDate();
String dateonly="";
String[] parts = date.split(LOCATION_SEPARATOR);
dateonly = parts[0] ;
dateTextView.setText(dateonly);
TextView titleTextView = listItemView.findViewById(R.id.mainTitle);
titleTextView.setText(currentPlace.getTitle());
ImageView thumbnail_image = listItemView.findViewById(R.id.thumbnail_image);
if (currentPlace != null&&currentPlace.getThumbNail()!="") {
Picasso.with(this.getContext())
.load(currentPlace.getThumbNail())
.centerCrop()
.transform(new CircleTransform(20,6))
.fit()
.into(thumbnail_image);
}
return listItemView;
}
}
package androidcodesnippets.me.cfsuman.com.newsapp;
import android.content.Context;
import android.content.AsyncTaskLoader;
import java.util.List;
public class NewsAppLoader extends AsyncTaskLoader<List<NewsApp>> {
private static final String LOG_TAG = NewsAppLoader.class.getName();
private String mUrl;
public NewsAppLoader(Context context, String url) {
super(context);
mUrl = url;
}
@Override
protected void onStartLoading() {
forceLoad();
}
@Override
public List<NewsApp> loadInBackground() {
if (mUrl == null) {
return null;
}
List<NewsApp> newsList = QueryUtils.fetchNewsAppData(mUrl);
return newsList;
}
}
package androidcodesnippets.me.cfsuman.com.newsapp;
import android.text.TextUtils;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public final class QueryUtils {
private static final String LOG_TAG = QueryUtils.class.getSimpleName();
private QueryUtils() {
}
public static List<NewsApp> fetchNewsAppData(String requestUrl) {
URL url = createUrl(requestUrl);
String jsonResponse = null;
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Problem making the HTTP request.", e);
}
List<NewsApp> newsList = extractFeatureFromJson(jsonResponse);
return newsList;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Problem building the URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000);
urlConnection.setConnectTimeout(15000);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
private static ArrayList<NewsApp> extractFeatureFromJson(String newsAppJSON) {
if (TextUtils.isEmpty(newsAppJSON)) {
return null;
}
ArrayList<NewsApp> newsAppList = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(newsAppJSON);
JSONObject response = baseJsonResponse.getJSONObject("response");
JSONArray results = response.getJSONArray("results");
String author = "System editor";
JSONObject fields;
String thumbNail="";
for (int i = 0; i < results.length(); i++) {
JSONObject news = results.getJSONObject(i);
String webTitle = news.optString("webTitle");
String webPublicationDate = news.optString("webPublicationDate");
String webUrl = news.optString("webUrl");
try {
JSONArray tags = news.getJSONArray("tags");
JSONObject contributor = (JSONObject) tags.get(0);
//using getString and try catch block instead of optString because i want to get System Editor and not blank string.
author = contributor.getString("webTitle");
fields = news.getJSONObject("fields");
thumbNail = fields.optString("thumbnail");
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing author field", e);
}
NewsApp newsApp = new NewsApp(webTitle, author, webPublicationDate, webUrl,thumbNail);
newsAppList.add(newsApp);
}
} catch (JSONException e) {
Log.e("QueryUtils", "Problem parsing JSON file", e);
}
return newsAppList;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment