Initial commit

This commit is contained in:
2017-06-05 20:17:52 +01:00
commit b974df9b89
43 changed files with 1123 additions and 0 deletions

1
app/.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
/build

29
app/build.gradle Normal file
View File

@@ -0,0 +1,29 @@
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion "24.0.3"
defaultConfig {
applicationId "com.example.h_mal.newsapp"
minSdkVersion 15
targetSdkVersion 25
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.0'
testCompile 'junit:junit:4.12'
}

17
app/proguard-rules.pro vendored Normal file
View File

@@ -0,0 +1,17 @@
# Add project specific ProGuard rules here.
# By default, the flags in this file are appended to flags specified
# in C:\Users\h_mal\AppData\Local\Android\Sdk/tools/proguard/proguard-android.txt
# You can edit the include path and order by changing the proguardFiles
# directive in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# Add any project specific keep options here:
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}

View File

@@ -0,0 +1,26 @@
package com.example.h_mal.newsapp;
import android.content.Context;
import android.support.test.InstrumentationRegistry;
import android.support.test.runner.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;
import static org.junit.Assert.*;
/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getTargetContext();
assertEquals("com.example.h_mal.newsapp", appContext.getPackageName());
}
}

View File

@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.h_mal.newsapp">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".SettingsActivity"
android:label="Settings">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.h_mal.newsapp.MainActivity"/>
</activity>
</application>
</manifest>

View File

@@ -0,0 +1,145 @@
package com.example.h_mal.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;
/**
* Created by h_mal on 16/03/2017.
*/
public class DataSink {
private static final String LOG_TAG = DataSink.class.getSimpleName();
private DataSink(){}
public static List<News> fetchNewsData(String requestUrl) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
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<News> news = extractFeatureFromJson(jsonResponse);
return news;
}
private static URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Error with creating URL ", e);
}
return url;
}
private static String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
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 earthquake 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 List<News> extractFeatureFromJson(String newsJSON) {
if (TextUtils.isEmpty(newsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
JSONObject baseJsonResponse = new JSONObject(newsJSON);
JSONObject currentNews = baseJsonResponse.getJSONObject("response");
JSONArray newsArray = currentNews.getJSONArray("results");
for (int i = 0; i < newsArray.length(); i++) {
JSONObject properties = newsArray.getJSONObject(i);
String title = properties.getString("webTitle");
String section = properties.getString("sectionName");
String url = properties.getString("webUrl");
News newsArticles = new News(title, section, url);
news.add(newsArticles);
}
} catch (JSONException e) {
Log.e("DataSink", "Problem parsing the earthquake JSON results", e);
}
return news;
}
}

View File

@@ -0,0 +1,147 @@
package com.example.h_mal.newsapp;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<News>> {
private TextView mEmptyStateTextView;
private static final int NEWS_LOADER_ID = 1;
private String GUARDIAN_REQUEST_URL = "https://content.guardianapis.com/search?page-size=30";
private NewsAdapter mAdapter;
// private String topic = "debate";
@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 NewsAdapter(this, new ArrayList<News>());
newsListView.setAdapter(mAdapter);
newsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
News currentNews = mAdapter.getItem(position);
Uri newsUri = Uri.parse(currentNews.getURLaddress());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, newsUri);
startActivity(websiteIntent);
}
});
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected()) {
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(NEWS_LOADER_ID, null, this);
} else {
mEmptyStateTextView.setText("no internet connection");
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setVisibility(View.GONE);
}
NewsAsyncTask task = new NewsAsyncTask();
task.execute(GUARDIAN_REQUEST_URL);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
Intent settingsIntent = new Intent(this, SettingsActivity.class);
startActivity(settingsIntent);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this);
String topic = sharedPrefs.getString(
"defaultNews",
"debate"
);
Uri baseUri = Uri.parse(GUARDIAN_REQUEST_URL);
Uri.Builder uriBuilder = baseUri.buildUpon();
uriBuilder.appendQueryParameter("tag", "politics/politics");
uriBuilder.appendQueryParameter("from-date", "2014-01-01");
uriBuilder.appendQueryParameter("q", topic);
uriBuilder.appendQueryParameter("api-key", "test");
return new NewsLoader(this, uriBuilder.toString());
}
@Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
mEmptyStateTextView.setText("no articles found");
mAdapter.clear();
ProgressBar progressBar = (ProgressBar) findViewById(R.id.progress_bar);
progressBar.setVisibility(View.GONE);
if (news != null && !news.isEmpty()) {
mAdapter.addAll(news);
}
}
@Override
public void onLoaderReset(Loader<List<News>> loader) {
mAdapter.clear();
}
private class NewsAsyncTask extends AsyncTask<String, Void, List<News>> {
@Override
protected List<News> doInBackground(String... urls) {
if (urls.length < 1 || urls[0] == null) {
return null;
}
List<News> result = DataSink.fetchNewsData(urls[0]);
return result;
}
}
}

View File

@@ -0,0 +1,31 @@
package com.example.h_mal.newsapp;
/**
* Created by h_mal on 16/03/2017.
*/
public class News {
private String mTitle;
private String mSection;
private String mURLaddress;
public News (String title, String section, String URLaddress){
mTitle = title;
mSection = section;
mURLaddress = URLaddress;
}
public String getTitle() {
return mTitle;
}
public String getSection() {
return mSection; }
public String getURLaddress() {
return mURLaddress;}
}

View File

@@ -0,0 +1,45 @@
package com.example.h_mal.newsapp;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by h_mal on 16/03/2017.
*/
public class NewsAdapter extends ArrayAdapter<News>{
public NewsAdapter(Activity context, ArrayList<News> news) {
super(context, 0, news);
}
public View getView(int position, View convertView, ViewGroup parent){
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
News currentNews = getItem(position);
String title = currentNews.getTitle();
String section = currentNews.getSection();
TextView titleView = (TextView) listItemView.findViewById(R.id.title);
titleView.setText(title);
TextView sectionView = (TextView) listItemView.findViewById(R.id.section);
sectionView.setText(section);
return listItemView;
}
}

View File

@@ -0,0 +1,37 @@
package com.example.h_mal.newsapp;
import android.content.AsyncTaskLoader;
import android.content.Context;
import java.util.List;
/**
* Created by h_mal on 18/03/2017.
*/
public class NewsLoader extends AsyncTaskLoader<List<News>> {
public static final String LOG_TAG = NewsLoader.class.getName();
private String mUrl;
public NewsLoader(Context context, String url) {
super(context);
mUrl = url;
}
@Override
protected void onStartLoading() {
forceLoad();
}
@Override
public List<News> loadInBackground() {
if (mUrl == null) {
return null;
}
List<News> result = DataSink.fetchNewsData(mUrl);
return result;
}
}

View File

@@ -0,0 +1,56 @@
package com.example.h_mal.newsapp;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
/**
* Created by h_mal on 19/03/2017.
*/
public class SettingsActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.settings_activity);
}
public static class NewsPreferenceFragment extends PreferenceFragment implements Preference.OnPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings_main);
Preference topic = findPreference("defaultNews");
bindPreferenceSummaryToValue(topic);
}
private void bindPreferenceSummaryToValue(Preference preference) {
preference.setOnPreferenceChangeListener(this);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(preference.getContext());
String preferenceString = preferences.getString(preference.getKey(), "");
onPreferenceChange(preference, preferenceString);
}
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
String stringValue = value.toString();
if (preference instanceof ListPreference) {
ListPreference listPreference = (ListPreference) preference;
int prefIndex = listPreference.findIndexOfValue(stringValue);
if (prefIndex >= 0) {
CharSequence[] labels = listPreference.getEntries();
preference.setSummary(labels[prefIndex]);
}
} else {
preference.setSummary(stringValue);
}
return true;
}
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 321 B

View File

@@ -0,0 +1,26 @@
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@+id/list"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@null"
android:dividerHeight="0dp" />
<TextView
android:id="@+id/empty_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAppearance="?android:textAppearanceMedium" />
<ProgressBar
android:id="@+id/progress_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textAppearance="?android:textAppearanceMedium"/>
</RelativeLayout>

View File

@@ -0,0 +1,31 @@
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:orientation="vertical"
android:paddingEnd="6dp"
android:paddingLeft="6dp"
android:paddingRight="6dp"
android:paddingStart="6dp">
<TextView
android:id="@+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="8dp"
android:textSize="16sp"
android:textColor="@android:color/black"
android:gravity="top"
android:maxLines="2"
android:text="breaking news: something normal happens somewhere"/>
<TextView
android:id="@+id/section"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="italic"
android:textSize="12sp"
android:text="Section"
android:layout_marginRight="8dp"/>
</LinearLayout>

View File

@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<fragment
android:name="com.example.h_mal.newsapp.SettingsActivity$NewsPreferenceFragment"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.h_mal.newsapp.SettingsActivity">
</fragment>

View File

@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.example.h_mal.newsapp.MainActivity">
<item
android:id="@+id/action_settings"
android:title="Settings"
android:icon="@drawable/ic_filter"
android:orderInCategory="1"
app:showAsAction="ifRoom" />
</menu>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 10 KiB

View File

@@ -0,0 +1,6 @@
<resources>
<!-- Example customization of dimensions originally defined in res/values/dimens.xml
(such as screen margins) for screens with more than 820dp of available width. This
would include 7" and 10" devices in landscape (~960dp and ~1280dp respectively). -->
<dimen name="activity_horizontal_margin">64dp</dimen>
</resources>

View File

@@ -0,0 +1,15 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="settings_order_by_labels">
<item>Debate</item>
<item>Economy</item>
<item>Immigration</item>
<item>Education</item>
</string-array>
<string-array name="settings_order_by_values">
<item>debate</item>
<item>economy</item>
<item>immigration</item>
<item>education</item>
</string-array>
</resources>

View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<color name="colorPrimary">#3F51B5</color>
<color name="colorPrimaryDark">#303F9F</color>
<color name="colorAccent">#FF4081</color>
</resources>

View File

@@ -0,0 +1,5 @@
<resources>
<!-- Default screen margins, per the Android Design guidelines. -->
<dimen name="activity_horizontal_margin">16dp</dimen>
<dimen name="activity_vertical_margin">16dp</dimen>
</resources>

View File

@@ -0,0 +1,3 @@
<resources>
<string name="app_name">News app</string>
</resources>

View File

@@ -0,0 +1,11 @@
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
</resources>

View File

@@ -0,0 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:title="Settings">
<EditTextPreference
android:defaultValue="debate"
android:inputType="text"
android:key="defaultNews"
android:selectAllOnFocus="true"
android:title="Search Term" />
</PreferenceScreen>

View File

@@ -0,0 +1,17 @@
package com.example.h_mal.newsapp;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Example local unit test, which will execute on the development machine (host).
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
}