diff --git a/android/assets/urllist.xml b/android/assets/urllist.xml
new file mode 100644
index 0000000..d5f3de3
--- /dev/null
+++ b/android/assets/urllist.xml
@@ -0,0 +1,61 @@
+
+
+
+ http://www.shulgan-tash.ru/about/
+ http://www.shulgan-tash.ru
+ shulgantash.html
+ ST_DIV_CLASS
+ post-content
+ Шульганташ
+ http://www.shulgan-tash.ru/wp-content/uploads/2013/07/MG_0164-FullHD.jpg
+
+
+ http://www.bashnl.ru/o-biblioteke/
+ http://www.bashnl.ru
+ bashnl.html
+ ST_ARTICLE
+ article
+ Библиотека имени Заки Валиди
+ http://upload.wikimedia.org/wikipedia/commons/f/f6/Library_Zaki-Validi.jpg
+
+
+ http://tv-rb.ru/o-kompanii/
+ http://tv-rb.ru
+ tv-rb.html
+ ST_DIV_CLASS
+ page-main-content
+ БСТ - О компании
+ http://tv-rb.ru/upload/medialibrary/4b6/4b6e96a91e32ed74ca239b0fca90d4a5.jpg
+
+
+
+ http://skikandry.ru/index/recreation
+ http://skikandry.ru
+ skikandry.html
+ ST_DIV_ID
+ article
+ Кандрыкуль
+ http://skikandry.ru/assets/images/photo/kandry-kul.jpg
+
+
+ http://www.iremel.net/
+ http://www.iremel.net
+ iremel.net.html
+ ST_DIV_CLASS
+ content-all
+ Гора Иремель
+ http://www.iremel.net/uploads/iremel/p1000694.jpg
+
+
+ http://invest.bashkortostan.ru/pages/11
+ http://invest.bashkortostan.ru
+ invest.bashkortostan.html
+ ST_DIV_CLASS
+ page-content
+ Преимущества Башкортостана
+ http://invest.bashkortostan.ru/uploads/picture/picture/50/normal_republic.png
+
+
+
+
+
diff --git a/android/libs/jsoup-1.8.1.jar b/android/libs/jsoup-1.8.1.jar
new file mode 100644
index 0000000..ae717d4
Binary files /dev/null and b/android/libs/jsoup-1.8.1.jar differ
diff --git a/android/libs/osmdroid-android-4.2.jar b/android/libs/osmdroid-android-4.3.jar
similarity index 56%
rename from android/libs/osmdroid-android-4.2.jar
rename to android/libs/osmdroid-android-4.3.jar
index 48612e3..aad6ea7 100644
Binary files a/android/libs/osmdroid-android-4.2.jar and b/android/libs/osmdroid-android-4.3.jar differ
diff --git a/android/project.properties b/android/project.properties
index dbb66c3..a80681a 100644
--- a/android/project.properties
+++ b/android/project.properties
@@ -13,4 +13,5 @@
# Project target.
target=android-21
android.library.reference.1=..\\HorizontalListViewLibrary
-android.library.reference.2=../google-play-services_lib
+android.library.reference.2=..\\google-play-services_lib
+android.library.reference.3=../networkutils
diff --git a/android/res/drawable/bashgid_logo_main.png b/android/res/drawable/bashgid_logo_main.png
new file mode 100644
index 0000000..212a935
Binary files /dev/null and b/android/res/drawable/bashgid_logo_main.png differ
diff --git a/android/res/drawable/marker_default.png b/android/res/drawable/marker_default.png
new file mode 100644
index 0000000..e161c69
Binary files /dev/null and b/android/res/drawable/marker_default.png differ
diff --git a/android/res/layout/button_hview_list_element.xml b/android/res/layout/button_hview_list_element.xml
index 6996e4e..ca1de54 100644
--- a/android/res/layout/button_hview_list_element.xml
+++ b/android/res/layout/button_hview_list_element.xml
@@ -13,7 +13,11 @@
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
- android:contentDescription="@string/related_image" />
+ android:adjustViewBounds="true"
+ android:contentDescription="@string/related_image"
+ android:maxHeight="180dp"
+ android:minHeight="180dp"
+ android:scaleType="fitXY" />
+
+
+
+
diff --git a/android/res/layout/fragment_link_content_page.xml b/android/res/layout/fragment_link_content_page.xml
index 88a2eb2..5024376 100644
--- a/android/res/layout/fragment_link_content_page.xml
+++ b/android/res/layout/fragment_link_content_page.xml
@@ -11,29 +11,10 @@
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="fishrungames.bashgid.LinkContentFragment" >
-
-
-
-
-
-
-
+
+
diff --git a/android/res/layout/fragment_photo_album_list_page.xml b/android/res/layout/fragment_photo_album_list_page.xml
new file mode 100644
index 0000000..6508282
--- /dev/null
+++ b/android/res/layout/fragment_photo_album_list_page.xml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
diff --git a/android/res/layout/fragment_photo_album_page.xml b/android/res/layout/fragment_photo_album_page.xml
new file mode 100644
index 0000000..6508282
--- /dev/null
+++ b/android/res/layout/fragment_photo_album_page.xml
@@ -0,0 +1,22 @@
+
+
+
+
+
+
+
diff --git a/android/res/layout/link_content_page_list_element.xml b/android/res/layout/link_content_page_list_element.xml
new file mode 100644
index 0000000..1b17f10
--- /dev/null
+++ b/android/res/layout/link_content_page_list_element.xml
@@ -0,0 +1,32 @@
+
+
+
+
+
+
+
+
+
+
diff --git a/android/res/layout/main_page_header.xml b/android/res/layout/main_page_header.xml
new file mode 100644
index 0000000..7aed26b
--- /dev/null
+++ b/android/res/layout/main_page_header.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
+
+
+
+
+
diff --git a/android/res/layout/main_page_list_header.xml b/android/res/layout/main_page_news.xml
similarity index 100%
rename from android/res/layout/main_page_list_header.xml
rename to android/res/layout/main_page_news.xml
diff --git a/android/res/layout/main_page_search.xml b/android/res/layout/main_page_search.xml
new file mode 100644
index 0000000..6abc0f3
--- /dev/null
+++ b/android/res/layout/main_page_search.xml
@@ -0,0 +1,46 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/android/res/layout/photo_album_element.xml b/android/res/layout/photo_album_element.xml
new file mode 100644
index 0000000..977bb62
--- /dev/null
+++ b/android/res/layout/photo_album_element.xml
@@ -0,0 +1,18 @@
+
+
+
+
+
+
diff --git a/android/res/layout/photo_album_list_element.xml b/android/res/layout/photo_album_list_element.xml
new file mode 100644
index 0000000..edc5990
--- /dev/null
+++ b/android/res/layout/photo_album_list_element.xml
@@ -0,0 +1,26 @@
+
+
+
+
+
+
+
+
diff --git a/android/res/layout/simple_hview_list_element.xml b/android/res/layout/simple_hview_list_element.xml
index df687e4..5f84423 100644
--- a/android/res/layout/simple_hview_list_element.xml
+++ b/android/res/layout/simple_hview_list_element.xml
@@ -10,9 +10,12 @@
+ android:adjustViewBounds="true"
+ android:maxHeight="180dp"
+ android:padding="2dp"
+ android:scaleType="centerCrop" />
newsRecordArr = NewsManager.GetInstance().getNews();
+ ArrayList newsRecordArr = NewsManager.getInstance().getNews();
if (newsRecordArr.size() > 0)
{
@@ -147,6 +163,9 @@ public class MainPageFragment extends Fragment implements NewsUpdatedCallbackInt
}
+
+ listAdapter.notifyDataSetChanged();
+
}
@@ -170,6 +189,7 @@ public class MainPageFragment extends Fragment implements NewsUpdatedCallbackInt
}
// create a new ImageView for each item referenced by the Adapter
+ @SuppressLint("InflateParams")
public View getView(int position, View convertView, ViewGroup parent) {
@@ -189,24 +209,8 @@ public class MainPageFragment extends Fragment implements NewsUpdatedCallbackInt
HListView hListView = (HListView) view.findViewById(R.id.hListView);
- if (position == 0)
- {
-
- hListView.setAdapter(new MainPageHListViewAdapters.SimpleElementAdapter(getActivity(), investorGroupContentIdArray));
- }
- else if (position == 1)
- {
- hListView.setAdapter(new MainPageHListViewAdapters.SimpleElementAdapter(getActivity(), cultureGroupContentIdArray));
- }
- else if (position == 2)
- {
- hListView.setAdapter(new MainPageHListViewAdapters.SimpleElementAdapter(getActivity(), touristGroupContentIdArray));
- }
- else
- {
- hListView.setAdapter(new MainPageHListViewAdapters.SimpleElementAdapter(getActivity(), educationGroupContentIdArray));
- }
-
+ hListView.setAdapter(new MainPageHListViewAdapters.SimpleElementAdapter(getActivity()));
+
textView.setText(teaserHeaderArray[position]);
button.setText(R.string.see_all);
@@ -215,10 +219,20 @@ public class MainPageFragment extends Fragment implements NewsUpdatedCallbackInt
}
}
+
+ @Override
+ public void OnFinished()
+ {
+
+ synchronized (removeCallbackSynchronizer)
+ {
+ removeCallback = null;
+ }
+ }
@Override
- public void OnNewsUpdated()
+ public void OnUpdated(Bundle result)
{
getActivity().runOnUiThread(new Runnable() {
diff --git a/android/src/fishrungames/bashgid/MainPageHListViewAdapters.java b/android/src/fishrungames/bashgid/MainPageHListViewAdapters.java
index de690a2..09232ce 100644
--- a/android/src/fishrungames/bashgid/MainPageHListViewAdapters.java
+++ b/android/src/fishrungames/bashgid/MainPageHListViewAdapters.java
@@ -1,6 +1,11 @@
package fishrungames.bashgid;
-import fishrungames.bashgid.core.LinkContentStorage;
+import java.util.ArrayList;
+
+import fishrungames.bashgid.core.HtmlDownloadManager;
+
+import fishrungames.bashgid.core.HtmlDownloadManager.TextFileRecord;
+import fishrungames.networkutils.ImageManager;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
@@ -16,19 +21,18 @@ public class MainPageHListViewAdapters {
public static class SimpleElementAdapter extends BaseAdapter {
-
- int [] contentIdArray;
-
+
private Context mContext;
+ ArrayList localHtmlList;
- public SimpleElementAdapter(Context c, int [] contentIdArray) {
- mContext = c;
- this.contentIdArray = contentIdArray;
-
+ public SimpleElementAdapter(Context c) {
+ mContext = c;
+
+ localHtmlList = HtmlDownloadManager.getInstance().getGlobalHtmlList();
}
public int getCount() {
- return contentIdArray.length;
+ return localHtmlList.size();
}
public Object getItem(int position) {
@@ -61,13 +65,13 @@ public class MainPageHListViewAdapters {
ImageButton imageButton = (ImageButton) view.findViewById(R.id.imageButton);
- textView.setText(LinkContentStorage.titleArray[contentIdArray[position]]);
+ textView.setText(localHtmlList.get(position).title);
- subTextView.setText(LinkContentStorage.subtitleArray[contentIdArray[position]]);
+ subTextView.setText("");
- imageButton.setBackgroundResource(LinkContentStorage.imgIdArray[contentIdArray[position]]);
+ ImageManager.getInstance().ApplyImageToImageView(imageButton, localHtmlList.get(position).topicImg);
- imageButton.setOnClickListener(new ContentButtonOnClickListener(contentIdArray[position]));
+ imageButton.setOnClickListener(new ContentButtonOnClickListener(localHtmlList.get(position)));
return view;
}
@@ -139,17 +143,18 @@ public static class DarkenElementAdapter extends BaseAdapter {
public static class ContentButtonOnClickListener implements OnClickListener
{
- Integer contentId;
+ TextFileRecord contentRecord;
- public ContentButtonOnClickListener(Integer contentId)
+ public ContentButtonOnClickListener(TextFileRecord contentRecord)
{
- this.contentId = contentId;
+ this.contentRecord = contentRecord;
}
@Override
public void onClick(View v)
{
- MainActivity.getInstance().OpenLinkContentScreen(contentId);
+ //MainActivity.getInstance().OpenHtmlViewerScreen(url);
+ MainActivity.getInstance().OpenLinkContentScreen(contentRecord);
}
}
diff --git a/android/src/fishrungames/bashgid/NewsListFragment.java b/android/src/fishrungames/bashgid/NewsListFragment.java
index e45b010..abf354a 100644
--- a/android/src/fishrungames/bashgid/NewsListFragment.java
+++ b/android/src/fishrungames/bashgid/NewsListFragment.java
@@ -3,11 +3,12 @@ package fishrungames.bashgid;
import java.util.ArrayList;
-import fishrungames.bashgid.core.ImageManager;
+import fishrungames.networkutils.ImageManager;
+import fishrungames.networkutils.UniversalActionWithCallback;
+import fishrungames.networkutils.interfaces.RemoveCallbackInterface;
+import fishrungames.networkutils.interfaces.UpdateAndFinishCallbackInterface;
import fishrungames.bashgid.core.NewsManager;
import fishrungames.bashgid.core.NewsManager.NewsRecord;
-import fishrungames.bashgid.core.NewsUpdatedCallbackInterface;
-import fishrungames.bashgid.core.RemoveCallbackInterface;
import fishrungames.bashgid.core.db.NewsDataSource;
import android.annotation.SuppressLint;
import android.content.Context;
@@ -24,7 +25,7 @@ import android.widget.ListView;
import android.widget.TextView;
-public class NewsListFragment extends Fragment implements NewsUpdatedCallbackInterface
+public class NewsListFragment extends Fragment implements UpdateAndFinishCallbackInterface
{
ListView listView;
@@ -33,15 +34,17 @@ public class NewsListFragment extends Fragment implements NewsUpdatedCallbackInt
ArrayList newsRecordArr;
- RemoveCallbackInterface downloadNewsCanceller = null;
+ RemoveCallbackInterface removeCallback = null;
+ Object removeCallbackSynchronizer = new Object();
@SuppressLint("InflateParams") @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_news_page, container, false);
- newsRecordArr = NewsManager.GetInstance().getNews();
+ newsRecordArr = NewsManager.getInstance().getNews();
+
+ removeCallback = UniversalActionWithCallback.PerformActionIfNotPerforming(NewsManager.getInstance(), null, this, "NewsManager");
- downloadNewsCanceller = NewsManager.GetInstance().DownloadNews(this);
listView = (ListView) rootView.findViewById(R.id.listView);
@@ -59,17 +62,20 @@ public class NewsListFragment extends Fragment implements NewsUpdatedCallbackInt
@Override
public void onDestroyView()
{
- if (downloadNewsCanceller != null)
+ synchronized (removeCallbackSynchronizer)
+ {
+ if (removeCallback != null)
{
- downloadNewsCanceller.RemoveCallback();
- downloadNewsCanceller = null;
+ removeCallback.RemoveCallback();
+ removeCallback = null;
}
+ }
super.onDestroyView();
}
public void RefreshNewsList()
{
- newsRecordArr = NewsManager.GetInstance().getNews();
+ newsRecordArr = NewsManager.getInstance().getNews();
listAdapter.notifyDataSetChanged();
}
@@ -130,7 +136,17 @@ public class NewsListFragment extends Fragment implements NewsUpdatedCallbackInt
@Override
- public void OnNewsUpdated()
+ public void OnFinished()
+ {
+ synchronized (removeCallbackSynchronizer)
+ {
+ removeCallback = null;
+ }
+
+ }
+
+ @Override
+ public void OnUpdated(Bundle result)
{
getActivity().runOnUiThread(new Runnable() {
diff --git a/android/src/fishrungames/bashgid/NewsRecordFragment.java b/android/src/fishrungames/bashgid/NewsRecordFragment.java
index 91a27f2..f643f15 100644
--- a/android/src/fishrungames/bashgid/NewsRecordFragment.java
+++ b/android/src/fishrungames/bashgid/NewsRecordFragment.java
@@ -1,7 +1,7 @@
package fishrungames.bashgid;
-import fishrungames.bashgid.core.ImageManager;
+import fishrungames.networkutils.ImageManager;
import fishrungames.bashgid.core.NewsManager.NewsRecord;
import android.os.Bundle;
import android.support.v4.app.Fragment;
diff --git a/android/src/fishrungames/bashgid/OsmMapHolderFragment.java b/android/src/fishrungames/bashgid/OsmMapHolderFragment.java
index 749d20b..afb6d41 100644
--- a/android/src/fishrungames/bashgid/OsmMapHolderFragment.java
+++ b/android/src/fishrungames/bashgid/OsmMapHolderFragment.java
@@ -2,6 +2,11 @@ package fishrungames.bashgid;
+import java.util.ArrayList;
+
+import android.app.AlertDialog;
+import android.graphics.Point;
+import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
@@ -10,17 +15,121 @@ import android.view.View;
import android.view.ViewGroup;
+import org.osmdroid.DefaultResourceProxyImpl;
+import org.osmdroid.ResourceProxy;
+import org.osmdroid.api.IMapController;
+import org.osmdroid.api.IMapView;
+import org.osmdroid.util.GeoPoint;
+
+import org.osmdroid.views.MapView;
+import org.osmdroid.views.overlay.ItemizedOverlay;
+
+import org.osmdroid.views.overlay.OverlayItem;
+import org.osmdroid.views.overlay.OverlayItem.HotspotPlace;
+
+import fishrungames.bashgid.core.LocationHolder;
+
+
public class OsmMapHolderFragment extends Fragment
{
+ private class CustomItemizedOverlay extends ItemizedOverlay{
+ private ArrayList mOverlayItems = new ArrayList();
+
+ public CustomItemizedOverlay(Drawable pDefaultMarker, ResourceProxy pResourceProxy) {
+ super(pDefaultMarker, pResourceProxy);
+ }
+
+ @Override
+ protected OverlayItem createItem(int pos) {
+ return mOverlayItems.get(pos);
+ }
+
+ @Override
+ public int size() {
+ if(mOverlayItems!=null) return mOverlayItems.size();
+ else return 0;
+ }
+
+ public void addOverlayItem(GeoPoint geoPoint){
+
+
+
+ /*if(Preferences.DEBUG) Log.d("MapActivity", "Latitude: "+latitude+" Longitude: "+longitude);
+ MarkerDrawable drawable = new MarkerDrawable(MapActivity.this, bitmap);
+ OverlayItem item = new OverlayItem("a", "a", new GeoPoint((int)(latitude*1e6), (int)(longitude*1e6)));
+ item.setMarker(drawable);
+ item.setMarkerHotspot(HotspotPlace.CENTER);
+ mOverlayItems.add(item);*/
+
+ OverlayItem item = new OverlayItem("Title", "Lol, snippet", geoPoint);
+ item.setMarker(getResources().getDrawable(R.drawable.marker_default));
+ item.setMarkerHotspot(HotspotPlace.CENTER);
+
+ mOverlayItems.add(item);
+
+ populateNow();
+ }
+
+ public void populateNow(){
+ populate();
+ }
+
+ @Override
+ public boolean onSnapToItem(int arg0, int arg1, Point arg2, IMapView arg3)
+ {
+ // TODO Auto-generated method stub
+ return false;
+ }
+
+ @Override
+ protected boolean onTap(int index) {
+ OverlayItem item = mOverlayItems.get(index);
+ AlertDialog.Builder dialog = new AlertDialog.Builder(OsmMapHolderFragment.this.getActivity());
+ dialog.setTitle(item.getTitle());
+ dialog.setMessage(item.getSnippet());
+ dialog.show();
+ return true;
+ }
+ }
+
+ CustomItemizedOverlay itemizedOverlay;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_osm_map_page, container, false);
-
+ MapView mapView = (MapView) rootView.findViewById(R.id.mapview);
+
+ mapView.setMaxZoomLevel(20);
+ mapView.setMinZoomLevel(4);
+
+ mapView.setBuiltInZoomControls(true);
+ mapView.setMultiTouchControls(true);
+
+
+ IMapController mapController = mapView.getController();
+
+
+ GeoPoint center = new GeoPoint(LocationHolder.CONST_UFA_LATITUDE, LocationHolder.CONST_UFA_LONGITUDE);
+
+ mapController.setZoom(10);
+ mapController.animateTo(center);
+
+
+ GeoPoint markerPoint = new GeoPoint( LocationHolder.CONST_UFA_LATITUDE, LocationHolder.CONST_UFA_LONGITUDE);
+
+
+ ResourceProxy resourceProxy = new DefaultResourceProxyImpl(getActivity());
+ itemizedOverlay = new CustomItemizedOverlay(getResources().getDrawable(R.drawable.russia_icon), resourceProxy);
+
+ itemizedOverlay.addOverlayItem(markerPoint);
+
+ mapView.getOverlays().add(itemizedOverlay);
+
return rootView;
}
+
}
diff --git a/android/src/fishrungames/bashgid/PhotoAlbumFragment.java b/android/src/fishrungames/bashgid/PhotoAlbumFragment.java
new file mode 100644
index 0000000..6ef7447
--- /dev/null
+++ b/android/src/fishrungames/bashgid/PhotoAlbumFragment.java
@@ -0,0 +1,91 @@
+package fishrungames.bashgid;
+
+
+import android.annotation.SuppressLint;
+import android.content.Context;
+import android.os.Bundle;
+import android.support.v4.app.Fragment;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+
+import android.widget.BaseAdapter;
+
+import android.widget.ImageView;
+import android.widget.ListView;
+
+import fishrungames.bashgid.core.AlbumManager;
+import fishrungames.networkutils.ImageManager;
+
+public class PhotoAlbumFragment extends Fragment
+{
+
+ AlbumManager.AlbumStruct album;
+
+ ListAdapter listAdapter;
+
+ public PhotoAlbumFragment(AlbumManager.AlbumStruct album)
+ {
+ this.album = album;
+ }
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+
+ View rootView = inflater.inflate(R.layout.fragment_photo_album_page, container, false);
+
+ listAdapter = new ListAdapter(getActivity());
+
+ ListView listView = (ListView) rootView.findViewById(R.id.listView);
+
+ listView.setAdapter(listAdapter);
+
+ return rootView;
+ }
+
+ public class ListAdapter extends BaseAdapter {
+ private Context mContext;
+
+ public ListAdapter(Context c) {
+ mContext = c;
+ }
+
+ public int getCount() {
+ return album.imageIds.size();
+ }
+
+ public Object getItem(int position) {
+ return null;
+ }
+
+ public long getItemId(int position) {
+ return 0;
+ }
+
+ // create a new ImageView for each item referenced by the Adapter
+ @SuppressLint("InflateParams")
+ public View getView(int position, View convertView, ViewGroup parent) {
+
+
+ View view;
+ if (convertView == null) { // if it's not recycled, initialize some attributes
+ LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ view = inflater.inflate(R.layout.photo_album_element, null);
+
+
+ } else {
+ view = convertView;
+ }
+
+
+ ImageView imageView = (ImageView) view.findViewById(R.id.imageView);
+
+ ImageManager.getInstance().ApplyImageToImageView(imageView, album.imageIds.get(position));
+
+ return view;
+ }
+
+ }
+
+
+}
\ No newline at end of file
diff --git a/android/src/fishrungames/bashgid/PhotoAlbumListFragment.java b/android/src/fishrungames/bashgid/PhotoAlbumListFragment.java
new file mode 100644
index 0000000..55db525
--- /dev/null
+++ b/android/src/fishrungames/bashgid/PhotoAlbumListFragment.java
@@ -0,0 +1,115 @@
+package fishrungames.bashgid;
+
+import java.util.ArrayList;
+
+import fishrungames.bashgid.core.AlbumManager;
+
+import fishrungames.networkutils.ImageManager;
+import android.annotation.SuppressLint;
+import android.content.Context;
+import android.os.Bundle;
+import android.support.v4.app.Fragment;
+import android.view.LayoutInflater;
+import android.view.View;
+import android.view.ViewGroup;
+import android.view.View.OnClickListener;
+import android.widget.BaseAdapter;
+
+import android.widget.ImageButton;
+import android.widget.ListView;
+import android.widget.TextView;
+
+
+public class PhotoAlbumListFragment extends Fragment
+{
+
+ ArrayList albumArr;
+
+ ListAdapter listAdapter;
+
+ @Override
+ public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
+
+ View rootView = inflater.inflate(R.layout.fragment_photo_album_list_page, container, false);
+
+ albumArr = AlbumManager.getInstance().getAlbums();
+
+ listAdapter = new ListAdapter(getActivity());
+
+ ListView listView = (ListView) rootView.findViewById(R.id.listView);
+
+ listView.setAdapter(listAdapter);
+
+ return rootView;
+ }
+
+ public class ListAdapter extends BaseAdapter {
+ private Context mContext;
+
+ public ListAdapter(Context c) {
+ mContext = c;
+ }
+
+ public int getCount() {
+ return albumArr.size();
+ }
+
+ public Object getItem(int position) {
+ return null;
+ }
+
+ public long getItemId(int position) {
+ return 0;
+ }
+
+ // create a new ImageView for each item referenced by the Adapter
+ @SuppressLint("InflateParams")
+ public View getView(int position, View convertView, ViewGroup parent) {
+
+
+ View view;
+ if (convertView == null) { // if it's not recycled, initialize some attributes
+ LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ view = inflater.inflate(R.layout.photo_album_list_element, null);
+
+
+ } else {
+ view = convertView;
+ }
+
+
+ ImageButton imageButton = (ImageButton) view.findViewById(R.id.imageButton);
+
+ ImageManager.getInstance().ApplyImageToImageView(imageButton, albumArr.get(position).imageIds.get(0));
+
+ imageButton.setOnClickListener(new ButtonOnClickListener(albumArr.get(position)));
+
+ TextView textView = (TextView)view.findViewById(R.id.textView);
+
+ textView.setText(albumArr.get(position).name);
+
+ return view;
+ }
+
+ }
+
+
+ public static class ButtonOnClickListener implements OnClickListener
+ {
+
+ AlbumManager.AlbumStruct album;
+
+ public ButtonOnClickListener(AlbumManager.AlbumStruct album)
+ {
+ this.album = album;
+ }
+
+ @Override
+ public void onClick(View v)
+ {
+ MainActivity.getInstance().OpenPhotoAlbumScreen(album);
+ }
+
+ }
+}
+
diff --git a/android/src/fishrungames/bashgid/SearchFragment.java b/android/src/fishrungames/bashgid/SearchFragment.java
index 7839497..c04ef5c 100644
--- a/android/src/fishrungames/bashgid/SearchFragment.java
+++ b/android/src/fishrungames/bashgid/SearchFragment.java
@@ -6,9 +6,11 @@ import java.util.ArrayList;
import fishrungames.bashgid.core.NewsManager;
import fishrungames.bashgid.core.NewsManager.NewsRecord;
import fishrungames.bashgid.core.db.NewsDataSource;
-import fishrungames.bashgid.core.ImageManager;
+import fishrungames.networkutils.ImageManager;
+import fishrungames.networkutils.UniversalActionWithCallback;
+import fishrungames.networkutils.interfaces.RemoveCallbackInterface;
+import fishrungames.networkutils.interfaces.UpdateAndFinishCallbackInterface;
import fishrungames.bashgid.core.NewsSearchRunnable;
-import fishrungames.bashgid.core.NewsUpdatedCallbackInterface;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
@@ -26,7 +28,7 @@ import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
-public class SearchFragment extends Fragment implements NewsUpdatedCallbackInterface
+public class SearchFragment extends Fragment implements UpdateAndFinishCallbackInterface
{
ListView listView;
@@ -39,10 +41,13 @@ public class SearchFragment extends Fragment implements NewsUpdatedCallbackInter
volatile boolean searchIsPerformingNow = false;
- NewsSearchRunnable nextSearchRunnable = null;
+ //NewsSearchRunnable nextSearchRunnable = null;
boolean restorePreviousSearch = false;
+ RemoveCallbackInterface removeCallback = null;
+ Object removeCallbackSynchronizer = new Object();
+
public SearchFragment()
{
}
@@ -69,8 +74,8 @@ public class SearchFragment extends Fragment implements NewsUpdatedCallbackInter
if (restorePreviousSearch)
{
- searchEditText.setText(NewsManager.GetInstance().getLastSearchQuery());
- searchResultArr = NewsManager.GetInstance().getSearchResultNews();
+ searchEditText.setText(NewsManager.getInstance().getLastSearchQuery());
+ searchResultArr = NewsManager.getInstance().getSearchResultNews();
}
@@ -95,6 +100,20 @@ public class SearchFragment extends Fragment implements NewsUpdatedCallbackInter
return rootView;
}
+ @Override
+ public void onDestroyView()
+ {
+ synchronized (removeCallbackSynchronizer)
+ {
+ if (removeCallback != null)
+ {
+ removeCallback.RemoveCallback();
+ removeCallback = null;
+ }
+ }
+ super.onDestroyView();
+ }
+
public class ListAdapter extends BaseAdapter {
private Context mContext;
@@ -150,55 +169,42 @@ public class SearchFragment extends Fragment implements NewsUpdatedCallbackInter
}
+ @Override
+ public void OnFinished()
+ {
+ synchronized (removeCallbackSynchronizer)
+ {
+ removeCallback = null;
+ }
+
+ }
@Override
- public void OnNewsUpdated()
+ public void OnUpdated(Bundle result)
{
getActivity().runOnUiThread(new RefreshSearchListRunnable());
}
public void CallUpdateNews(String text)
{
- if (!searchIsPerformingNow)
- {
- searchIsPerformingNow = true;
-
- NewsSearchRunnable runnable = new NewsSearchRunnable(this, text);
-
- ImmediateSearchNews(runnable);
- }
- else
- {
- nextSearchRunnable = new NewsSearchRunnable(this, text);
- }
- }
-
- private void ImmediateSearchNews(NewsSearchRunnable runnable)
- {
- Thread thread = new Thread(runnable);
+ Bundle query = new Bundle();
- thread.start();
+ query.putString("query", text);
+
+ removeCallback = UniversalActionWithCallback.PerformAction(new NewsSearchRunnable(), query, this, "NewsSearchRunnable");
+
}
-
-
+
private class RefreshSearchListRunnable implements Runnable
{
@Override
public void run()
{
- searchResultArr = NewsManager.GetInstance().getSearchResultNews();
+ searchResultArr = NewsManager.getInstance().getSearchResultNews();
listAdapter.notifyDataSetChanged();
- searchIsPerformingNow = false;
-
- if (nextSearchRunnable != null)
- {
- ImmediateSearchNews(nextSearchRunnable);
-
- nextSearchRunnable = null;
- }
}
}
diff --git a/android/src/fishrungames/bashgid/core/AlbumManager.java b/android/src/fishrungames/bashgid/core/AlbumManager.java
new file mode 100644
index 0000000..ac8b2a9
--- /dev/null
+++ b/android/src/fishrungames/bashgid/core/AlbumManager.java
@@ -0,0 +1,75 @@
+package fishrungames.bashgid.core;
+
+import java.util.ArrayList;
+
+public class AlbumManager
+{
+ public static class AlbumStruct
+ {
+ public String name;
+ public ArrayList imageIds = new ArrayList();
+
+ public AlbumStruct(String name)
+ {
+ this.name = name;
+ }
+ }
+
+ private ArrayList AlbumArr = new ArrayList();
+
+ public static AlbumManager instance = null;
+
+ public static AlbumManager getInstance()
+ {
+ if (instance == null)
+ {
+ instance = new AlbumManager();
+ }
+
+ return instance;
+ }
+
+ public void AddPhotoToAlbum(String albumName, String imageId)
+ {
+
+ synchronized (AlbumArr)
+ {
+ boolean albumExists = false;
+
+ for (AlbumStruct albumStruct : AlbumArr)
+ {
+ if (albumStruct.name.equals(albumName))
+ {
+ albumStruct.imageIds.add(imageId);
+ albumExists = true;
+ }
+ }
+
+ if (!albumExists)
+ {
+ AlbumStruct albumStruct = new AlbumStruct(albumName);
+
+ albumStruct.imageIds.add(imageId);
+
+ AlbumArr.add(albumStruct);
+ }
+
+ }
+ }
+
+ public ArrayList getAlbums()
+ {
+ ArrayList albums = new ArrayList();
+
+ synchronized(AlbumArr)
+ {
+ albums.addAll(AlbumArr);
+ }
+
+ return albums;
+ }
+
+
+
+
+}
diff --git a/android/src/fishrungames/bashgid/core/DownloadManager.java b/android/src/fishrungames/bashgid/core/DownloadManager.java
deleted file mode 100644
index 598d055..0000000
--- a/android/src/fishrungames/bashgid/core/DownloadManager.java
+++ /dev/null
@@ -1,74 +0,0 @@
-package fishrungames.bashgid.core;
-
-
-import java.io.BufferedReader;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.UnsupportedEncodingException;
-import java.net.URL;
-import java.net.URLConnection;
-
-import org.apache.http.client.ClientProtocolException;
-
-import android.util.Log;
-
-
-public class DownloadManager {
-
- public static String getXmlFromUrl(String urlString) {
- String xml = null;
-
- try {
- // defaultHttpClient
-
- URL url = new URL(urlString);
- URLConnection ucon = url.openConnection();
-
- BufferedReader in = new BufferedReader(new InputStreamReader(
- ucon.getInputStream()));
- String inputLine;
-
- StringBuilder stringBuilder = new StringBuilder();
-
- while ((inputLine = in.readLine()) != null)
- {
- stringBuilder.append(inputLine);
- }
-
-
- xml = stringBuilder.toString();
-
-
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- // return XML
- return xml;
- }
-
-
- public static boolean MimeTypeIsImage(String mimeType)
- {
- return mimeType.equals("image/bmp") || mimeType.equals("image/gif") || mimeType.equals("image/jpeg") || mimeType.equals("image/png");
- }
-
- public static String GetUrlFolder(String url)
- {
- int pos = url.lastIndexOf("/");
-
- if (pos == -1)
- {
- Log.e("Error", "GetUrlFolder got incorrect agrument");
-
- return "";
- }
-
- String substr = url.substring(0, pos);
-
- return substr;
- }
-}
diff --git a/android/src/fishrungames/bashgid/core/HtmlDownloadManager.java b/android/src/fishrungames/bashgid/core/HtmlDownloadManager.java
new file mode 100644
index 0000000..4f66059
--- /dev/null
+++ b/android/src/fishrungames/bashgid/core/HtmlDownloadManager.java
@@ -0,0 +1,365 @@
+package fishrungames.bashgid.core;
+
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+
+import org.jsoup.Jsoup;
+import org.jsoup.nodes.Document;
+import org.jsoup.nodes.Element;
+import org.jsoup.select.Elements;
+import org.xmlpull.v1.XmlPullParserException;
+
+import android.os.Bundle;
+
+import fishrungames.networkutils.ContextHolder;
+import fishrungames.networkutils.DownloadFunctions;
+import fishrungames.networkutils.FileFunctions;
+import fishrungames.networkutils.ImageManager;
+import fishrungames.networkutils.SimplePropertyTree;
+import fishrungames.networkutils.UniversalActionWithCallback;
+import fishrungames.networkutils.UpdateCallbackHolder;
+import fishrungames.networkutils.interfaces.NetworkActionInterface;
+import fishrungames.networkutils.interfaces.RemoveCallbackInterface;
+import fishrungames.networkutils.interfaces.UpdateAndFinishCallbackInterface;
+
+public class HtmlDownloadManager implements NetworkActionInterface
+{
+
+
+
+ public static class TextFileRecord
+ {
+ public String url;
+ public String baseUrl;
+ public String localUrl;
+
+
+ public static class DocPart
+ {
+ public enum DocPartType
+ {
+ DPT_TEXT,
+ DPT_IMAGE,
+ DPT_BUTTON
+ }
+
+ public DocPartType docPartType;
+ public String value;
+
+ public DocPart(DocPartType docPartType, String value)
+ {
+ this.docPartType = docPartType;
+ this.value = value;
+ }
+ }
+
+ public ArrayList contentArr = new ArrayList();
+
+ public enum SeparatorType
+ {
+ ST_DIV_ID,
+ ST_DIV_CLASS,
+ ST_ARTICLE
+ }
+
+ public SeparatorType separator;
+
+ public String separatorValue;
+
+ public String title;
+ public String topicImg;
+
+ public TextFileRecord(String url, String baseUrl, String localUrl, SeparatorType separator, String separatorValue, String title, String topicImg)
+ {
+ this.url = url;
+ this.baseUrl = baseUrl;
+ this.localUrl = localUrl;
+ this.separator = separator;
+ this.separatorValue = separatorValue;
+ this.title = title;
+ this.topicImg = topicImg;
+
+ }
+ }
+
+ private static HtmlDownloadManager instance = null;
+
+ public static HtmlDownloadManager getInstance()
+ {
+ if (instance == null)
+ {
+ instance = new HtmlDownloadManager();
+ }
+
+ return instance;
+ }
+
+ public static RemoveCallbackInterface DownloadHtmlFiles(UpdateAndFinishCallbackInterface callback)
+ {
+ return UniversalActionWithCallback.PerformActionIfNotPerforming(HtmlDownloadManager.getInstance(), null, callback, "TextFileDownloadManager");
+ }
+
+
+ private ArrayList GlobelHtmlUrlList = new ArrayList();
+
+ @Override
+ public void InThreadAction(Bundle query, UpdateCallbackHolder callbackHolder)
+ {
+
+ InputStream is = null;
+ SimplePropertyTree ptree = null;
+ try
+ {
+ is = ContextHolder.getContext().getAssets().open("urllist.xml");
+ ptree = SimplePropertyTree.parse(is);
+
+ } catch (IOException e)
+ {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (XmlPullParserException e)
+ {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } finally
+ {
+ if (is != null)
+ {
+ try
+ {
+ is.close();
+ } catch (IOException e)
+ {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ if (ptree != null)
+ {
+ ArrayList htmlUrlList = getListFromPropertyTree(ptree);
+
+ if (htmlUrlList.size() > 0)
+ {
+ for (int i = 0; i < htmlUrlList.size(); i++)
+ {
+ String fileContent = DownloadFunctions.getXmlFromUrl(htmlUrlList.get(i).url);
+
+ if (fileContent != null)
+ {
+
+ Document doc = Jsoup.parse(fileContent);
+
+ Elements linkElements = doc.getElementsByTag("link");
+
+ linkElements.remove();
+
+ Elements scriptElements = doc.getElementsByTag("script");
+
+ scriptElements.remove();
+
+ Elements hiddenElements = doc.getElementsByAttributeValue("style", "display: none;");
+
+ hiddenElements.remove();
+
+ Elements styleElements = doc.getElementsByTag("style");
+
+ styleElements.remove();
+
+ Elements aElements = doc.getElementsByTag("a");
+
+ for (Element a : aElements)
+ {
+ a.removeAttr("href");
+ a.attributes().put("href", "#");
+ }
+
+
+ Elements imgElements = doc.getElementsByTag("img");
+
+ for (Element img : imgElements)
+ {
+ String link = ImageTagToLink(htmlUrlList.get(i).baseUrl, img);
+
+
+ if (!link.equals(""))
+ {
+ ImageManager.getInstance().AddImageToLibrary(link);
+ }
+
+ }
+
+ Element body = doc.body();
+
+ Element mainDiv;
+
+ if (htmlUrlList.get(i).separator == TextFileRecord.SeparatorType.ST_DIV_ID)
+ {
+ mainDiv = body.getElementById(htmlUrlList.get(i).separatorValue).clone();
+ } else if (htmlUrlList.get(i).separator == TextFileRecord.SeparatorType.ST_DIV_CLASS)
+ {
+ mainDiv = body.getElementsByClass(htmlUrlList.get(i).separatorValue).first().clone();
+ } else
+ {
+ mainDiv = body.getElementsByTag(htmlUrlList.get(i).separatorValue).first().clone();
+ }
+
+ body.children().remove();
+
+ body.appendChild(mainDiv);
+
+ String newHtmlCode = doc.html();
+
+ Elements mainDivElements = mainDiv.children();
+
+ htmlUrlList.get(i).contentArr.add(new TextFileRecord.DocPart(TextFileRecord.DocPart.DocPartType.DPT_TEXT, htmlUrlList.get(i).title));
+
+ for (Element subDiv : mainDivElements)
+ {
+ String text = subDiv.text();
+ Elements subDivImgArr = subDiv.getElementsByTag("img");
+
+ for (Element subDivImg : subDivImgArr)
+ {
+ String imageLink = ImageTagToLink(htmlUrlList.get(i).baseUrl, subDivImg);
+
+ if (!imageLink.equals(""))
+ {
+ AlbumManager.getInstance().AddPhotoToAlbum(htmlUrlList.get(i).title, imageLink);
+ htmlUrlList.get(i).contentArr.add(new TextFileRecord.DocPart(TextFileRecord.DocPart.DocPartType.DPT_IMAGE, imageLink));
+ }
+ }
+
+ if (!text.equals(""))
+ {
+ htmlUrlList.get(i).contentArr.add(new TextFileRecord.DocPart(TextFileRecord.DocPart.DocPartType.DPT_TEXT, text));
+ }
+
+ }
+
+ htmlUrlList.get(i).contentArr.add(new TextFileRecord.DocPart(TextFileRecord.DocPart.DocPartType.DPT_BUTTON, htmlUrlList.get(i).localUrl));
+
+ FileFunctions.WriteTextToFile(htmlUrlList.get(i).localUrl, newHtmlCode);
+
+ }
+
+ }
+ }
+
+
+ synchronized(GlobelHtmlUrlList)
+ {
+ GlobelHtmlUrlList.clear();
+ GlobelHtmlUrlList.addAll(htmlUrlList);
+ }
+ }
+
+
+ callbackHolder.OnUpdated(null);
+ }
+
+
+ private static String ImageTagToLink(String baseUrl, Element imageTag)
+ {
+ String link = imageTag.attributes().get("src");
+
+ if (link.endsWith(".png") || link.endsWith(".jpg") || link.endsWith(".jpeg") || link.endsWith(".bmp")
+ || link.endsWith(".PNG") || link.endsWith(".JPG") || link.endsWith(".JPEG")
+ || link.endsWith(".BMP"))
+ {
+ if (link.startsWith("//"))
+ {
+ link = "http:" + link;
+ }
+ if (!link.startsWith("http://"))
+ {
+ link = baseUrl + link;
+ }
+
+ return link;
+
+ } else
+ {
+ return "";
+ }
+ }
+
+ public static void RecursiveRemoveScript(Element e)
+ {
+ for (Iterator iterator = e.children().iterator(); iterator.hasNext();)
+ {
+
+ Element c = iterator.next();
+
+ RecursiveRemoveScript(c);
+
+ if ("script".equals(c.tagName()))
+ {
+ iterator.remove();
+ }
+ }
+ }
+
+
+ public ArrayList getGlobalHtmlList()
+ {
+
+ ArrayList result = new ArrayList();
+
+
+ synchronized(GlobelHtmlUrlList)
+ {
+ result.addAll(GlobelHtmlUrlList);
+ }
+
+ return result;
+
+ }
+
+ public static ArrayList getListFromPropertyTree(SimplePropertyTree ptree)
+ {
+ ArrayList htmlUrlList = new ArrayList();
+
+ SimplePropertyTree listNode = ptree.GetNode("list");
+
+ if (listNode != null)
+ {
+ for (int i = 0; i < listNode.SubNodes.size(); i++)
+ {
+
+ String url = listNode.SubNodes.get(i).Get("url");
+ String baseUrl = listNode.SubNodes.get(i).Get("baseUrl");
+ String localUrl = listNode.SubNodes.get(i).Get("localUrl");
+
+ TextFileRecord.SeparatorType separator;
+
+ if (listNode.SubNodes.get(i).Get("separator").equals("ST_DIV_ID"))
+ {
+ separator = TextFileRecord.SeparatorType.ST_DIV_ID;
+ } else if (listNode.SubNodes.get(i).Get("separator").equals("ST_DIV_CLASS"))
+ {
+ separator = TextFileRecord.SeparatorType.ST_DIV_CLASS;
+ } else
+ {
+ separator = TextFileRecord.SeparatorType.ST_ARTICLE;
+ }
+
+ String separatorValue = listNode.SubNodes.get(i).Get("separatorValue");
+ String title = listNode.SubNodes.get(i).Get("title");
+ String topicImg = listNode.SubNodes.get(i).Get("topicImg");
+
+
+ htmlUrlList.add(new TextFileRecord(url, baseUrl, localUrl, separator, separatorValue, title, topicImg));
+
+ ImageManager.getInstance().AddImageToLibrary(topicImg);
+ }
+ }
+
+ return htmlUrlList;
+ }
+
+}
diff --git a/android/src/fishrungames/bashgid/core/ImageManager.java b/android/src/fishrungames/bashgid/core/ImageManager.java
deleted file mode 100644
index a00c619..0000000
--- a/android/src/fishrungames/bashgid/core/ImageManager.java
+++ /dev/null
@@ -1,213 +0,0 @@
-package fishrungames.bashgid.core;
-
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.concurrent.Semaphore;
-
-import fishrungames.bashgid.MainActivity;
-import fishrungames.bashgid.R;
-
-import android.content.Context;
-import android.graphics.Bitmap;
-import android.graphics.BitmapFactory;
-import android.util.Base64;
-import android.util.Log;
-import android.widget.ImageView;
-
-public class ImageManager {
-
- static ImageManager instance = null;
-
- private volatile Semaphore downloadingFileNameSetMutex = new Semaphore(1, true);
- private volatile HashSet downloadingFileNameSet = new HashSet();
-
-
- public static ImageManager getInstance()
- {
- if (instance == null)
- {
- instance = new ImageManager();
- }
-
- return instance;
- }
-
-
- HashMap PredefinedImageId = new HashMap();
-
- public ImageManager()
- {
- PredefinedImageId.put("R.drawable.transparent", R.drawable.transparent);
- }
-
-
-
-
- public void ApplyImageToImageView(ImageView imageView, String imageId)
- {
- //Xperimental -- Should be called only in main thread
-
- if (imageId.startsWith("R.drawable."))
- {
- Integer resourceId = PredefinedImageId.get(imageId);
-
- if (resourceId == null)
- {
- Log.e("Error: ", "Image not added to PredefinedImageId: " + imageId);
-
- resourceId = R.drawable.transparent;
- }
-
- imageView.setImageResource(resourceId);
- }
- else
- {
- String fileName = ImageUrlToFileName(imageId);
-
- File f = MainActivity.getInstance().getFileStreamPath(fileName);
-
- if (f.exists())
- {
-
- boolean fileIsBusy = false;
-
-
- try
- {
- downloadingFileNameSetMutex.acquire();
- try
- {
- fileIsBusy = downloadingFileNameSet.contains(fileName);
- } finally
- {
- downloadingFileNameSetMutex.release();
- }
- } catch (InterruptedException ie)
- {
- Log.e("Error in ApplyImageToImageView", "Error in ApplyImageToImageView");
- }
-
-
- if (!fileIsBusy)
- {
-
- Bitmap bitmap = BitmapFactory.decodeFile( MainActivity.getInstance().getFileStreamPath(fileName).getAbsolutePath());
-
- imageView.setImageBitmap(bitmap);
-
- }
-
-
-
- }
- else
- {
- imageView.setImageResource(R.drawable.transparent);
- }
- }
- }
-
-
- public static String ImageUrlToFileName(String imageUrl)
- {
- String beforeExtension = imageUrl.substring(0, imageUrl.lastIndexOf("."));
- String extension = imageUrl.substring(imageUrl.lastIndexOf("."));
-
- return Base64.encodeToString(beforeExtension.getBytes(), Base64.DEFAULT).replace("\n", "") + extension;
- }
-
- public void DownloadImageIfNeeded(String imageUrl)
- {
- String fileName = ImageUrlToFileName(imageUrl);
-
- File f = MainActivity.getInstance().getFileStreamPath(fileName);
-
- if (f.exists())
- {
- return;
- }
-
- boolean fileIsBusy = false;
-
-
- try
- {
- downloadingFileNameSetMutex.acquire();
- try
- {
- if (downloadingFileNameSet.contains(fileIsBusy))
- {
- fileIsBusy = true;
- }
- else
- {
- downloadingFileNameSet.add(fileName);
- }
- } finally
- {
- downloadingFileNameSetMutex.release();
- }
- } catch (InterruptedException ie)
- {
- Log.e("Error in DownloadImageIfNeeded", "Error in DownloadImageIfNeeded");
- }
-
- if (!fileIsBusy)
- {
-
- try {
- InputStream is = (InputStream) new URL(imageUrl).getContent();
-
- FileOutputStream out = null;
-
- out = MainActivity.getInstance().openFileOutput(fileName, Context.MODE_PRIVATE);
-
- byte [] buf = new byte[1024];
-
- int numRead;
-
- while ( (numRead = is.read(buf) ) >= 0) {
- out.write(buf, 0, numRead);
- }
-
- out.close();
-
-
- } catch (Exception e) {
- e.printStackTrace();
- }
-
-
- try
- {
- downloadingFileNameSetMutex.acquire();
- try
- {
-
- downloadingFileNameSet.remove(fileName);
-
- } finally
- {
- downloadingFileNameSetMutex.release();
- }
- } catch (InterruptedException ie)
- {
- Log.e("Error in DownloadImageIfNeeded", "Error in DownloadImageIfNeeded");
- }
-
-
- }
- }
-
- public String GetImageLocalUrl(String imageUrl)
- {
- return "file://" + MainActivity.getInstance().getFilesDir().getAbsolutePath() + "/" + ImageUrlToFileName(imageUrl);
- }
-
-
-
-}
diff --git a/android/src/fishrungames/bashgid/core/LinkContentStorage.java b/android/src/fishrungames/bashgid/core/LinkContentStorage.java
deleted file mode 100644
index 26b113e..0000000
--- a/android/src/fishrungames/bashgid/core/LinkContentStorage.java
+++ /dev/null
@@ -1,54 +0,0 @@
-package fishrungames.bashgid.core;
-
-import fishrungames.bashgid.R;
-
-public class LinkContentStorage
-{
-
- public static String [] titleArray = { "", "Предприятия Башкортостана", "Статистика", "Помощь инвестору", "Транспорт",
- "Земфира", "Башкирский театр", "Национальная библиотека",
- "Панорамы Уфы", "Шульган-Таш", "Фотографии старой Уфы", "Ночная жизнь в Уфе",
- "Министерство Образования", "УГАТУ", "БГПУ"
- };
-
- public static String [] textArray = {
- "",
- "Развитие промышленного производства республики характеризуется стабильностью позитивных процессов и поступательным ростом объемов производства. Структура промышленного производства Республики Башкортостан включает добычу полезных ископаемых, обрабатывающие производства, производство и распределение электроэнергии, газа и воды.",
- "Территориальный орган Федеральной службы государственной статистики по Республике Башкортостан (далее Башкортостанстат) является главным учетно-статистическим центром Республики Башкортостан и относится к федеральным органам исполнительной власти, осуществляющим руководство статистикой на территории Республики Башкортостан, исходя из отнесения в соответствии со статьей 71 Конституции Российской Федерации официального статистического учета к ведению Российской Федерации.",
- "ГАУ РБ «Агентство по привлечению инвестиций» создано создано в соответствии с распоряжением Правительства Республики Башкортостан от 20 августа 2013 года № 1036-р. Миссия Агентства – повышение инвестиционной привлекательности Республики Башкортостан, создание максимально комфортной бизнес-среды для привлечения инвестиций.",
- "Позитивным фактором географического положения является близость Республики Башкортостан к развитым регионам Урала и Поволжья, прежде всего к Свердловской области и Республике Татарстан. Кроме того, для Башкирии определенную роль играет фактор транзитного положения. Через Республику проходит Транссибирская магистраль, связывающая Центральную часть России с Сибирью и Дальним Востоком, а также со странами Средней Азии, в первую очередь с Казахстаном.",
- "Земфира — российская певица, музыкант, композитор и автор песен. Одна из самых коммерчески успешных исполнительниц в истории российской музыки. Земфира стала олицетворением нового движения в русском роке, которое журналисты окрестили «женский рок».",
- "Башкирский государственный академический театр драмы имени Мажита Гафури, насчитывающий свою историю с 1919 года, имеет статус первого театра республики, хранителя и продолжателя башкирского национального искусства. Почти целый век Башкирский академический театр служит идеалам мира, добра и любви, утверждая на своей сцене высокие нравственные ценности, хранит народную культуру, родной язык, традиции, менталитет, тем самым объединяет народ, укрепляет и сохраняет национальный дух.",
- "Национальная библиотека Республики Башкортостан является государственной, центральной, универсальной, научной, общедоступной библиотекой Республики Башкортостан, культурным центром республиканского значения, национальным хранилищем документов, республиканским центром научно-исследовательской работы в области библиотековедения, библиографоведения и книговедения. ",
- "Виртуальный тур по Уфе (панорама города) - это новый проект официального городского портала, который позволит вам ознакомиться с видом нашего замечательного города с высоты птичьего полета. Уверены, для многих из вас Уфа предстанет в новом свете, не часто удается подняться в небо, чтобы полюбоваться неувядающей красотой города - миллионника, его современными архитектурными решениями новых кварталов, гармонично сочетающимися с исторической частью столицы, городскими пейзажами и живописными окрестностями.",
- "Государственный природный заповедник «Шульга́н-Таш» расположен в западных предгорьях горно-лесной области Южного Урала, в Бурзя́нском районе Республики Башкортостан. Заповедник «Шульга́н-Таш» является природоохранным, научно-исследовательским, эколого-просветительским учреждением федерального значения и частью ядра созданного в 2012 году комплексного биосферного резервата ЮНЕСКО «Башки́рский Ура́л».",
- "Уникальные фотографии Уфы, сделанные в начале XX века",
- "Каждый день с 12.00 до 16.00 Harat`s Pub приглашает на ирландский завтрак – глазунья с тостами, горячими колбасками, беконом, помидорами черри и красной фасолью за 170 руб.",
- "Министерство образования Республики Башкортостан занимается обеспечением и развитием на территории Республики Башкортостан единого российского образовательного пространства с ориентацией на международные стандарты образования, реализацией республиканских и федеральных программ развития образования в целях обеспечения взаимодействия образовательной системы с органами государственной власти.",
- "Уфимский государственный авиационный технический университет - ведущий и крупнейший технический вуз города Уфы и Республики Башкортостан, центр отечественной науки и культуры, один из старейших университетов региона, победитель конкурса инновационных образовательных программ вузов",
- "Башкирский государственный педагогический университет имени М. Акмуллы́ (БГПУ имени М. Акмуллы) — является государственным образовательным учреждением высшего профессионального образования федерального подчинения."
- };
-
- public static String [] subtitleArray = { "", "Инвестиционная карта", "Все об экономике Башкортостана", "Программа помощи инвесторам", "Обзор транспортной инфраструктуры",
- "Персона дня", "Культурные традиции", "Литература",
- "Уфа с высоты птичьего полета", "Природный заповедник", "Фотогалерея", "Обзор",
- "Учреждение", "Университет", "Университет"
- };
-
-
- public static String [] webLinkArray = { "", "http://map.bashkortostan.ru/", "http://bashstat.gks.ru/wps/wcm/connect/rosstat_ts/bashstat/ru/", "http://invest.bashkortostan.ru/pages/15", "http://invest.bashkortostan.ru/pages/11",
- "http://www.zemfira.ru/", "http://bashdram.ru/", "http://www.bashnl.ru/",
- "http://www.ufacity.info/panorama/", "http://www.shulgan-tash.ru/", "http://srr.on.ufanet.ru/ufa.htm", "http://www.poufe.ru/poufe.php?type=clubs",
- "http://education.bashkortostan.ru", "http://ugatu.su/", "http://bspu.ru/"
- };
-
-
- public static int[] imgIdArray = { 0, R.drawable.img_for_investor1_button, R.drawable.img_for_investor2_button, R.drawable.img_for_investor3_button, R.drawable.img_for_investor4_button,
- R.drawable.img_culture1_button, R.drawable.img_culture2_button, R.drawable.img_culture3_button,
- R.drawable.img_tourist1_button, R.drawable.img_tourist2_button, R.drawable.img_tourist3_button, R.drawable.img_tourist4_button,
- R.drawable.img_education1_button, R.drawable.img_education2_button, R.drawable.img_education3_button
-
- };
-
-
-}
diff --git a/android/src/fishrungames/bashgid/core/MainPageUpdater.java b/android/src/fishrungames/bashgid/core/MainPageUpdater.java
new file mode 100644
index 0000000..e2440f0
--- /dev/null
+++ b/android/src/fishrungames/bashgid/core/MainPageUpdater.java
@@ -0,0 +1,20 @@
+package fishrungames.bashgid.core;
+
+import android.os.Bundle;
+import fishrungames.networkutils.UpdateCallbackHolder;
+import fishrungames.networkutils.interfaces.NetworkActionInterface;
+
+public class MainPageUpdater implements NetworkActionInterface
+{
+
+ @Override
+ public void InThreadAction(Bundle query, UpdateCallbackHolder callbackHolder)
+ {
+
+ NewsManager.getInstance().InThreadAction(query, callbackHolder);
+ HtmlDownloadManager.getInstance().InThreadAction(query, callbackHolder);
+
+ callbackHolder.OnUpdated(null);
+ }
+
+}
diff --git a/android/src/fishrungames/bashgid/core/NewsManager.java b/android/src/fishrungames/bashgid/core/NewsManager.java
index 5f59716..028a39d 100644
--- a/android/src/fishrungames/bashgid/core/NewsManager.java
+++ b/android/src/fishrungames/bashgid/core/NewsManager.java
@@ -1,18 +1,25 @@
package fishrungames.bashgid.core;
+import fishrungames.networkutils.ImageManager;
+import fishrungames.networkutils.UpdateCallbackHolder;
+
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.concurrent.Semaphore;
+import fishrungames.networkutils.DownloadFunctions;
+import fishrungames.networkutils.interfaces.NetworkActionInterface;
+
+import android.os.Bundle;
import android.util.Log;
import fishrungames.bashgid.MainActivity;
-public class NewsManager {
+public class NewsManager implements NetworkActionInterface {
private static final String [] urlArr = {
"https://www.bashkortostan.ru/presscenter/news/rss/",
@@ -26,7 +33,7 @@ public class NewsManager {
private static volatile boolean SynchronizationInProcess = false; //Not strict, so don't need mutex
- private volatile Semaphore newsRecordMutex = new Semaphore(1, true);
+ //private volatile Semaphore newsRecordMutex = new Semaphore(1, true);
private ArrayList newsRecord = new ArrayList();
@@ -42,7 +49,7 @@ public class NewsManager {
- public static NewsManager GetInstance()
+ public static NewsManager getInstance()
{
if (instance == null)
{
@@ -73,7 +80,7 @@ public class NewsManager {
this.title = rss2Item.title;
this.description = rss2Item.description;
- if ((rss2Item.rss2Enclosure != null) && (DownloadManager.MimeTypeIsImage(rss2Item.rss2Enclosure.mimeType)))
+ if ((rss2Item.rss2Enclosure != null) && (DownloadFunctions.MimeTypeIsImage(rss2Item.rss2Enclosure.mimeType)))
{
this.imageId = rss2Item.rss2Enclosure.url;
}
@@ -86,185 +93,58 @@ public class NewsManager {
}
}
-
- public RemoveCallbackInterface DownloadNews(NewsUpdatedCallbackInterface callback)
+
+ @Override
+ public void InThreadAction(Bundle query, UpdateCallbackHolder callbackHolder)
{
- DownloadNewsRunnable downloadNewsRunnable = null;
- if (CanCallSynchronization())
+ ArrayList localNewsRecord = MainActivity.getInstance().newsDataSource.getNews();
+
+ ArrayList imageToDownloadList = new ArrayList();
+
+ for (int i = 0; i < urlArr.length; i++)
{
- downloadNewsRunnable = new DownloadNewsRunnable(callback);
- Thread thread = new Thread(downloadNewsRunnable);
+ LoadNewsAndImagesFromRss2(urlArr[i], localNewsRecord, imageToDownloadList);
- thread.start();
}
- return downloadNewsRunnable;
+ Collections.sort(localNewsRecord, new NewsSortComparator());
+
+ synchronized(newsRecord)
+ {
+ newsRecord.clear();
+ newsRecord.addAll(localNewsRecord);
+ MainActivity.getInstance().newsDataSource.replaceNews(newsRecord);
+ }
+
+ Bundle innerQuery = new Bundle();
+
+ innerQuery.putStringArray("imageUrlArr", imageToDownloadList.toArray(new String[imageToDownloadList.size()]));
+
+ ImageManager.getInstance().InThreadAction(innerQuery, callbackHolder);
+
+ callbackHolder.OnUpdated(null);
}
- class DownloadNewsRunnable implements Runnable, RemoveCallbackInterface
- {
-
- private volatile Semaphore callbackMutex = new Semaphore(1, true);
- NewsUpdatedCallbackInterface callback = null;
-
- public DownloadNewsRunnable(NewsUpdatedCallbackInterface callback)
- {
- try
- {
- callbackMutex.acquire();
- try
- {
-
- this.callback = callback;
-
- } finally
- {
- callbackMutex.release();
- }
- } catch (InterruptedException ie)
- {
- Log.e("Error in DownloadNewsRunnable", "Error in DownloadNewsRunnable");
- }
-
- }
-
- @Override
- public void RemoveCallback()
- {
-
- try
- {
- callbackMutex.acquire();
- try
- {
-
- callback = null;
-
- } finally
- {
- callbackMutex.release();
- }
- } catch (InterruptedException ie)
- {
- Log.e("Error in DownloadNewsRunnable", "Error in DownloadNewsRunnable");
- }
- }
-
- @Override
- public void run()
- {
-
-
- SynchronizationInProcess = true;
-
-
- ArrayList localNewsRecord = MainActivity.getInstance().newsDataSource.getNews();
-
- ArrayList imageToDownloadList = new ArrayList();
-
- for (int i = 0; i < urlArr.length; i++)
- {
-
- LoadNewsAndImagesFromRss2(urlArr[i], localNewsRecord, imageToDownloadList);
-
- }
-
- Collections.sort(localNewsRecord, new NewsSortComparator());
-
-
- try
- {
- newsRecordMutex.acquire();
- try
- {
-
- newsRecord = localNewsRecord;
-
- MainActivity.getInstance().newsDataSource.replaceNews(newsRecord);
-
- } finally
- {
- newsRecordMutex.release();
- }
- } catch (InterruptedException ie)
- {
- Log.e("Error in DownloadNewsRunnable", "Error in DownloadNewsRunnable");
- }
-
-
- try
- {
- callbackMutex.acquire();
- try
- {
-
- if (callback != null)
- {
- callback.OnNewsUpdated();
- }
-
- } finally
- {
- callbackMutex.release();
- }
- } catch (InterruptedException ie)
- {
- Log.e("Error in DownloadNewsRunnable", "Error in DownloadNewsRunnable");
- }
-
-
- for (String imageToDownload : imageToDownloadList)
- {
- ImageManager.getInstance().DownloadImageIfNeeded(imageToDownload);
- }
-
-
- SynchronizationInProcess = false;
-
- }
- }
public NewsManager()
{
- try
+ synchronized(newsRecord)
{
- newsRecordMutex.acquire();
- try
- {
- newsRecord = MainActivity.getInstance().newsDataSource.getNews();
-
- } finally
- {
- newsRecordMutex.release();
- }
- } catch (InterruptedException ie)
- {
- Log.e("Error in NewsManager constructor", "Error in NewsManager constructor");
- }
-
+ newsRecord = MainActivity.getInstance().newsDataSource.getNews();
+ }
}
public ArrayList getNews()
{
ArrayList result = new ArrayList();
+
- try
+ synchronized(newsRecord)
{
- newsRecordMutex.acquire();
- try
- {
- result.addAll(newsRecord);
-
- } finally
- {
- newsRecordMutex.release();
- }
- } catch (InterruptedException ie)
- {
- Log.e("Error in NewsManager constructor", "Error in NewsManager constructor");
- }
+ result.addAll(newsRecord);
+ }
return result;
}
@@ -335,7 +215,7 @@ public class NewsManager {
//Enclosure
if (rss2Item.rss2Enclosure != null)
{
- if (DownloadManager.MimeTypeIsImage(rss2Item.rss2Enclosure.mimeType))
+ if (DownloadFunctions.MimeTypeIsImage(rss2Item.rss2Enclosure.mimeType))
{
imageToDownloadList.add(rss2Item.rss2Enclosure.url);
}
@@ -384,7 +264,7 @@ public class NewsManager {
{
if (!relativeImageUrl.startsWith("http://"))
{
- String homeFolder = DownloadManager.GetUrlFolder(url);
+ String homeFolder = DownloadFunctions.GetUrlFolder(url);
relativeImageUrl = homeFolder + relativeImageUrl;
}
@@ -403,7 +283,7 @@ public class NewsManager {
{
for (int i = 0; i < relativeImageUrlList.size(); i++)
{
- String fileName = ImageManager.getInstance().GetImageLocalUrl(absoluteImageUrlList.get(i));
+ String fileName = ImageManager.GetImageLocalUrl(absoluteImageUrlList.get(i));
rss2Item.description = rss2Item.description.replace("\"" +relativeImageUrlList.get(i) + "\"" , "\"" +fileName + "\"");
}
@@ -413,7 +293,7 @@ public class NewsManager {
static void LoadNewsAndImagesFromRss2(String url, ArrayList newsRecordArr, ArrayList imageUrlArr)
{
//Xperimental -- need to optimize this code. slow block BEGINS
- String xmlCode = DownloadManager.getXmlFromUrl(url);
+ String xmlCode = DownloadFunctions.getXmlFromUrl(url);
if (xmlCode == null)
{
diff --git a/android/src/fishrungames/bashgid/core/NewsSearchResultInterface.java b/android/src/fishrungames/bashgid/core/NewsSearchResultInterface.java
deleted file mode 100644
index f7d69f3..0000000
--- a/android/src/fishrungames/bashgid/core/NewsSearchResultInterface.java
+++ /dev/null
@@ -1,12 +0,0 @@
-package fishrungames.bashgid.core;
-
-import java.util.ArrayList;
-
-import fishrungames.bashgid.core.NewsManager.NewsRecord;
-
-public interface NewsSearchResultInterface
-{
-
- public void OnNewsUpdated(ArrayList newsRecordArr);
-
-}
diff --git a/android/src/fishrungames/bashgid/core/NewsSearchRunnable.java b/android/src/fishrungames/bashgid/core/NewsSearchRunnable.java
index 9b0dbfa..ff98320 100644
--- a/android/src/fishrungames/bashgid/core/NewsSearchRunnable.java
+++ b/android/src/fishrungames/bashgid/core/NewsSearchRunnable.java
@@ -1,92 +1,19 @@
package fishrungames.bashgid.core;
-import java.util.concurrent.Semaphore;
+import fishrungames.networkutils.UpdateCallbackHolder;
+import fishrungames.networkutils.interfaces.NetworkActionInterface;
-import android.util.Log;
+import android.os.Bundle;
-public class NewsSearchRunnable implements Runnable, RemoveCallbackInterface
+public class NewsSearchRunnable implements NetworkActionInterface
{
-
- private volatile Semaphore callbackMutex = new Semaphore(1, true);
-
- private NewsUpdatedCallbackInterface callback = null;
-
- private String query;
-
- public NewsSearchRunnable(NewsUpdatedCallbackInterface callback, String query)
- {
- this.query = query;
-
- try
- {
- callbackMutex.acquire();
- try
- {
-
- this.callback = callback;
-
-
- } finally
- {
- callbackMutex.release();
- }
- } catch (InterruptedException ie)
- {
- Log.e("Error in NewsSearchRunnable", "Error in NewsSearchRunnable");
- }
- }
@Override
- public void run()
+ public void InThreadAction(Bundle query, UpdateCallbackHolder callbackHolder)
{
-
- NewsManager.GetInstance().searchNews(query);
-
- //After all
-
- try
- {
- callbackMutex.acquire();
- try
- {
-
- if (callback != null)
- {
- callback.OnNewsUpdated();
-
- callback = null;
- }
-
- } finally
- {
- callbackMutex.release();
- }
- } catch (InterruptedException ie)
- {
- Log.e("Error in DownloadNewsRunnable", "Error in DownloadNewsRunnable");
- }
- }
-
- @Override
- public void RemoveCallback()
- {
- try
- {
- callbackMutex.acquire();
- try
- {
-
- callback = null;
-
- } finally
- {
- callbackMutex.release();
- }
- } catch (InterruptedException ie)
- {
- Log.e("Error in NewsSearchRunnable", "Error in NewsSearchRunnable");
- }
+ NewsManager.getInstance().searchNews(query.getString("query"));
+ callbackHolder.OnUpdated(null);
}
}
diff --git a/android/src/fishrungames/bashgid/core/NewsUpdatedCallbackInterface.java b/android/src/fishrungames/bashgid/core/NewsUpdatedCallbackInterface.java
deleted file mode 100644
index 2b1a19b..0000000
--- a/android/src/fishrungames/bashgid/core/NewsUpdatedCallbackInterface.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package fishrungames.bashgid.core;
-
-public interface NewsUpdatedCallbackInterface
-{
- //Xperimental -- maybe allow it to return value? Array of news
- public void OnNewsUpdated();
-}
-
diff --git a/android/src/fishrungames/bashgid/core/RemoveCallbackInterface.java b/android/src/fishrungames/bashgid/core/RemoveCallbackInterface.java
deleted file mode 100644
index 7638843..0000000
--- a/android/src/fishrungames/bashgid/core/RemoveCallbackInterface.java
+++ /dev/null
@@ -1,8 +0,0 @@
-package fishrungames.bashgid.core;
-
-
-public interface RemoveCallbackInterface
-{
- public void RemoveCallback();
-}
-
\ No newline at end of file