diff --git a/.settings/org.eclipse.jdt.core.prefs b/.settings/org.eclipse.jdt.core.prefs new file mode 100644 index 00000000..b080d2dd --- /dev/null +++ b/.settings/org.eclipse.jdt.core.prefs @@ -0,0 +1,4 @@ +eclipse.preferences.version=1 +org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 +org.eclipse.jdt.core.compiler.compliance=1.6 +org.eclipse.jdt.core.compiler.source=1.6 diff --git a/libs/gson-2.2.4-javadoc.jar b/libs/gson-2.2.4-javadoc.jar new file mode 100644 index 00000000..ce8fa7db Binary files /dev/null and b/libs/gson-2.2.4-javadoc.jar differ diff --git a/libs/gson-2.2.4-sources.jar b/libs/gson-2.2.4-sources.jar new file mode 100644 index 00000000..30b13f65 Binary files /dev/null and b/libs/gson-2.2.4-sources.jar differ diff --git a/libs/gson-2.2.4.jar b/libs/gson-2.2.4.jar new file mode 100644 index 00000000..9478253e Binary files /dev/null and b/libs/gson-2.2.4.jar differ diff --git a/src/de/luhmer/owncloudnewsreader/NewsDetailActivity.java b/src/de/luhmer/owncloudnewsreader/NewsDetailActivity.java index 28947ac9..2cc68ddb 100644 --- a/src/de/luhmer/owncloudnewsreader/NewsDetailActivity.java +++ b/src/de/luhmer/owncloudnewsreader/NewsDetailActivity.java @@ -1,459 +1,487 @@ -package de.luhmer.owncloudnewsreader; - -import java.util.ArrayList; -import java.util.List; - -import android.content.Intent; -import android.content.SharedPreferences; -import android.database.Cursor; -import android.net.Uri; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.support.v4.app.Fragment; -import android.support.v4.app.FragmentManager; -import android.support.v4.app.FragmentPagerAdapter; -import android.support.v4.view.ViewPager; -import android.support.v4.view.ViewPager.OnPageChangeListener; -import android.util.Log; -import android.view.KeyEvent; -import android.widget.Toast; - -import com.actionbarsherlock.app.SherlockFragmentActivity; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuItem; - -import de.luhmer.owncloudnewsreader.database.DatabaseConnection; -import de.luhmer.owncloudnewsreader.helper.ThemeChooser; -import de.luhmer.owncloudnewsreader.reader.IReader; -import de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloud_Reader; - -public class NewsDetailActivity extends SherlockFragmentActivity { - - /** - * The {@link android.support.v4.view.PagerAdapter} that will provide - * fragments for each of the sections. We use a - * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which - * will keep every loaded fragment in memory. If this becomes too memory - * intensive, it may be best to switch to a - * {@link android.support.v4.app.FragmentStatePagerAdapter}. - */ - SectionsPagerAdapter mSectionsPagerAdapter; - - /** - * The {@link ViewPager} that will host the section contents. - */ - public ViewPager mViewPager; - private int currentPosition; - MenuItem menuItem_Starred; - IReader _Reader; - ArrayList databaseItemIds; - DatabaseConnection dbConn; - //public List rssFiles; - - public static final String DATABASE_IDS_OF_ITEMS = "DATABASE_IDS_OF_ITEMS"; - - @Override - protected void onCreate(Bundle savedInstanceState) { - - ThemeChooser.chooseTheme(this); - - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_news_detail); - - _Reader = new OwnCloud_Reader(); - dbConn = new DatabaseConnection(this); - Intent intent = getIntent(); - - //long subsciption_id = -1; - //long folder_id = -1; - int item_id = 0; - - //if(intent.hasExtra(NewsReaderDetailActivity.SUBSCRIPTION_ID)) - // subsciption_id = intent.getExtras().getLong(NewsReaderDetailActivity.SUBSCRIPTION_ID); - //if(intent.hasExtra(NewsReaderDetailActivity.FOLDER_ID)) - // folder_id = intent.getExtras().getLong(NewsReaderDetailActivity.FOLDER_ID); - if(intent.hasExtra(NewsReaderDetailActivity.ITEM_ID)) - item_id = intent.getExtras().getInt(NewsReaderDetailActivity.ITEM_ID); - if(intent.hasExtra(NewsReaderDetailActivity.TITEL)) - getSupportActionBar().setTitle(intent.getExtras().getString(NewsReaderDetailActivity.TITEL)); - //getActionBar().setTitle(intent.getExtras().getString(NewsReaderDetailActivity.TITEL)); - - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - - if(intent.hasExtra(DATABASE_IDS_OF_ITEMS)) - databaseItemIds = intent.getIntegerArrayListExtra(DATABASE_IDS_OF_ITEMS); - - - // Create the adapter that will return a fragment for each of the three - // primary sections of the app. - mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); - - // Set up the ViewPager with the sections adapter. - mViewPager = (ViewPager) findViewById(R.id.pager); - mViewPager.setAdapter(mSectionsPagerAdapter); - - - //rssFiles = new ArrayList(); - try - { - mViewPager.setCurrentItem(item_id, true); - PageChanged(item_id); - } - catch(Exception ex) - { - ex.printStackTrace(); - } - - mViewPager.setOnPageChangeListener(new OnPageChangeListener() { - - @Override - public void onPageSelected(int pos) { - PageChanged(pos); - } - - @Override - public void onPageScrolled(int arg0, float arg1, int arg2) { - } - - @Override - public void onPageScrollStateChanged(int arg0) { - } - }); - } - - @Override - protected void onDestroy() { - if(dbConn != null) - dbConn.closeDatabase(); - super.onDestroy(); - } - - - @Override - public boolean onKeyDown(int keyCode, KeyEvent event) { - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this); - if(mPrefs.getBoolean(SettingsActivity.CB_NAVIGATE_WITH_VOLUME_BUTTONS_STRING, false)) - { - if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) - { - if(currentPosition < databaseItemIds.size() -1) - { - mViewPager.setCurrentItem(currentPosition + 1, true); - return true; - } - } - - else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)) - { - if(currentPosition > 0) - { - mViewPager.setCurrentItem(currentPosition - 1, true); - return true; - } - } - } - if(keyCode == KeyEvent.KEYCODE_BACK) - { - NewsDetailFragment ndf = (NewsDetailFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + currentPosition); - if(ndf.webview != null) - { - if(ndf.webview.canGoBack()) - { - ndf.webview.goBack(); - if(!ndf.webview.canGoBack())//RssItem - ndf.LoadRssItemInWebView(); - - return true; - } - } - - /* - View vGroup = mViewPager.getChildAt(currentPosition); - - if(vGroup != null) - { - WebView webView = (WebView) vGroup.findViewById(R.id.webview); - if(webView != null) - { - if(webView.canGoBack()) - { - webView.goBack(); - if(!webView.canGoBack())//RssItem - { - NewsDetailFragment ndf = (NewsDetailFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + currentPosition); - ndf.LoadRssItemInWebView(this); - } - - return true; - } - } - }*/ - } - - return super.onKeyDown(keyCode, event); - } - - private void PageChanged(int position) - { - StopVideoOnCurrentPage(); - currentPosition = position; - ResumeVideoPlayersOnCurrentPage(); - - UpdateActionBarIcons(); - - //String idFeed = String.valueOf(rssFiles.get(position).getDB_Id()); - String idFeed = String.valueOf(databaseItemIds.get(currentPosition)); - - if(!dbConn.isFeedUnreadStarred(idFeed, true)) - { - dbConn.updateIsReadOfFeed(idFeed, true); - - //Cursor cur = dbConn.getArticleByID(idFeed); - //cur.moveToFirst(); - //GoogleReaderMethods.MarkItemAsRead(true, cur, dbConn, getApplicationContext(), asyncTaskCompletedPerformTagRead); - - - /* - List idItems = new ArrayList(); - idItems.add(cur.getString(cur.getColumnIndex(DatabaseConnection.RSS_ITEM_RSSITEM_ID))); - _Reader.Start_AsyncTask_PerformTagActionForSingleItem(5, - this, - asyncTaskCompletedPerformTagRead, - idItems, - FeedItemTags.TAGS.MARK_ITEM_AS_READ); - - - cur.close(); - */ - //dbConn.closeDatabase(); - Log.d("PAGE CHANGED", "PAGE: " + position + " - IDFEED: " + idFeed); - } - } - - private void ResumeVideoPlayersOnCurrentPage() - { - NewsDetailFragment fragment = (NewsDetailFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + currentPosition); - if(fragment != null) // could be null if not instantiated yet - fragment.ResumeVideoPlayers(); - - } - - private void StopVideoOnCurrentPage() - { - NewsDetailFragment fragment = (NewsDetailFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + currentPosition); - if(fragment != null) // could be null if not instantiated yet - fragment.StopVideoPlayers(); - } - - public void UpdateActionBarIcons() - { - boolean isStarred = dbConn.isFeedUnreadStarred(String.valueOf(databaseItemIds.get(currentPosition)) , false); - - //if(rssFiles.get(currentPosition).getStarred() && menuItem_Starred != null) - if(isStarred && menuItem_Starred != null) - menuItem_Starred.setIcon(android.R.drawable.star_on); - //menuItem_Starred.setIcon(R.drawable.btn_rating_star_on_normal_holo_light); - else if(menuItem_Starred != null) - menuItem_Starred.setIcon(android.R.drawable.star_off); - //menuItem_Starred.setIcon(R.drawable.btn_rating_star_off_normal_holo_light); - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - // Inflate the menu; this adds items to the action bar if it is present. - //getMenuInflater().inflate(R.menu.news_detail, menu); - getSupportMenuInflater().inflate(R.menu.news_detail, menu); - - menuItem_Starred = menu.findItem(R.id.action_starred); - UpdateActionBarIcons(); - - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - Cursor cursor = dbConn.getArticleByID(String.valueOf(databaseItemIds.get(currentPosition))); - - switch (item.getItemId()) { - case android.R.id.home: - super.onBackPressed(); - break; - - case R.id.action_starred: - //String idItem_Db = String.valueOf(rssFiles.get(currentPosition).getDB_Id()); - String idItem_Db = String.valueOf(databaseItemIds.get(currentPosition)); - //String idItem = String.valueOf(rssFiles.get(currentPosition).getItem_Id()); - Boolean curState = dbConn.isFeedUnreadStarred(idItem_Db, false); - - //rssFiles.get(currentPosition).setStarred(!curState); - - dbConn.updateIsStarredOfFeed(idItem_Db, !curState); - - UpdateActionBarIcons(); - - List idItems = new ArrayList(); - cursor.moveToFirst(); - idItems.add(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_RSSITEM_ID))); - cursor.close(); - - /* - if(!curState) - _Reader.Start_AsyncTask_PerformTagActionForSingleItem(0, this, asyncTaskCompletedPerformTagRead, idItems, FeedItemTags.TAGS.MARK_ITEM_AS_STARRED); - else - _Reader.Start_AsyncTask_PerformTagActionForSingleItem(0, this, asyncTaskCompletedPerformTagRead, idItems, FeedItemTags.TAGS.MARK_ITEM_AS_UNSTARRED); - - */ - /* - Cursor cur = dbConn.getFeedByID(idFeed); - cur.moveToFirst(); - GoogleReaderMethods.MarkItemAsStarred(!curState, cur, dbConn, getApplicationContext(), asyncTaskCompletedPerformTagStarred); - cur.close();*/ - break; - - case R.id.action_openInBrowser: - //String link = rssFiles.get(currentPosition).getLink(); - String link = ""; - - if(cursor != null) - { - cursor.moveToFirst(); - link = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_LINK)); - cursor.close(); - } - - //if(!link.isEmpty()) - if(link.trim().length() > 0) - { - Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link)); - startActivity(browserIntent); - } - break; - - case R.id.action_sendSourceCode: - String description = ""; - if(cursor != null) - { - cursor.moveToFirst(); - description = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_BODY)); - cursor.close(); - } - - - Intent i = new Intent(Intent.ACTION_SEND); - i.setType("message/rfc822"); - i.putExtra(Intent.EXTRA_EMAIL , new String[]{"david-dev@live.de"}); - i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_sourceCode)); - //i.putExtra(Intent.EXTRA_TEXT , rssFiles.get(currentPosition).getDescription()); - i.putExtra(Intent.EXTRA_TEXT , description); - try { - startActivity(Intent.createChooser(i, getString(R.string.email_sendMail))); - } catch (android.content.ActivityNotFoundException ex) { - Toast.makeText(NewsDetailActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show(); - } - break; - - case R.id.action_ShareItem: - - String title = ""; - String linkToItem = ""; - if(cursor != null) - { - cursor.moveToFirst(); - title = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_TITLE)); - linkToItem = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_LINK)); - cursor.close(); - } - - Intent share = new Intent(Intent.ACTION_SEND); - share.setType("text/plain"); - //share.putExtra(Intent.EXTRA_SUBJECT, rssFiles.get(currentPosition).getTitle()); - //share.putExtra(Intent.EXTRA_TEXT, rssFiles.get(currentPosition).getLink()); - share.putExtra(Intent.EXTRA_SUBJECT, title); - share.putExtra(Intent.EXTRA_TEXT, linkToItem); - - startActivity(Intent.createChooser(share, "Share Item")); - break; - } - return super.onOptionsItemSelected(item); - } - - - /* - OnAsyncTaskCompletedListener asyncTaskCompletedPerformTagRead = new OnAsyncTaskCompletedListener() { - - @Override - public void onAsyncTaskCompleted(int task_id, Object task_result) { - boolean success = (Boolean) task_result; - if(!success) - Toast.makeText(NewsDetailActivity.this, "Error while changing the read tag..", Toast.LENGTH_LONG).show(); - - Log.d("FINISHED PERFORM TAG READ ", "" + task_result); - } - }; - - OnAsyncTaskCompletedListener asyncTaskCompletedPerformTagStarred = new OnAsyncTaskCompletedListener() { - - @Override - public void onAsyncTaskCompleted(int task_id, Object task_result) { - Log.d("FINISHED PERFORM TAG STARRED ", "" + task_result); - } - }; - */ - - @Override - public void finish() { - Intent intent = new Intent(); - intent.putExtra("POS", mViewPager.getCurrentItem()); - setResult(RESULT_OK, intent); - super.finish(); - } - - /** - * A {@link FragmentPagerAdapter} that returns a fragment corresponding to - * one of the sections/tabs/pages. - */ - public class SectionsPagerAdapter extends FragmentPagerAdapter { - //public class SectionsPagerAdapter extends FragmentStatePagerAdapter { - - - public SectionsPagerAdapter(FragmentManager fm) { - super(fm); - } - - @Override - public Fragment getItem(int position) { - // getItem is called to instantiate the fragment for the given page. - // Return a DummySectionFragment (defined as a static inner class - // below) with the page number as its lone argument. - Fragment fragment = new NewsDetailFragment(); - Bundle args = new Bundle(); - args.putInt(NewsDetailFragment.ARG_SECTION_NUMBER, position + 1); - fragment.setArguments(args); - return fragment; - } - - - @Override - public int getCount() { - //return 2; - return databaseItemIds.size(); - //return rssFiles.size(); - } - - @Override - public CharSequence getPageTitle(int position) { - /* - Locale l = Locale.getDefault(); - switch (position) { - case 0: - return getString(R.string.title_section1).toUpperCase(l); - case 1: - return getString(R.string.title_section2).toUpperCase(l); - case 2: - return getString(R.string.title_section3).toUpperCase(l); - } - */ - return null; - } - } -} +package de.luhmer.owncloudnewsreader; + +import java.util.ArrayList; +import java.util.List; + +import android.content.Intent; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.net.Uri; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.support.v4.app.Fragment; +import android.support.v4.app.FragmentManager; +import android.support.v4.app.FragmentPagerAdapter; +import android.support.v4.view.ViewPager; +import android.support.v4.view.ViewPager.OnPageChangeListener; +import android.util.Log; +import android.view.KeyEvent; +import android.widget.Toast; + +import com.actionbarsherlock.app.SherlockFragmentActivity; +import com.actionbarsherlock.view.Menu; +import com.actionbarsherlock.view.MenuItem; + +import de.luhmer.owncloudnewsreader.database.DatabaseConnection; +import de.luhmer.owncloudnewsreader.helper.ThemeChooser; +import de.luhmer.owncloudnewsreader.reader.IReader; +import de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloud_Reader; + +public class NewsDetailActivity extends SherlockFragmentActivity { + + /** + * The {@link android.support.v4.view.PagerAdapter} that will provide + * fragments for each of the sections. We use a + * {@link android.support.v4.app.FragmentPagerAdapter} derivative, which + * will keep every loaded fragment in memory. If this becomes too memory + * intensive, it may be best to switch to a + * {@link android.support.v4.app.FragmentStatePagerAdapter}. + */ + SectionsPagerAdapter mSectionsPagerAdapter; + + /** + * The {@link ViewPager} that will host the section contents. + */ + public ViewPager mViewPager; + private int currentPosition; + + MenuItem menuItem_Starred; + MenuItem menuItem_Read; + + IReader _Reader; + ArrayList databaseItemIds; + DatabaseConnection dbConn; + //public List rssFiles; + + public static final String DATABASE_IDS_OF_ITEMS = "DATABASE_IDS_OF_ITEMS"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + + ThemeChooser.chooseTheme(this); + + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_news_detail); + + _Reader = new OwnCloud_Reader(); + dbConn = new DatabaseConnection(this); + Intent intent = getIntent(); + + //long subsciption_id = -1; + //long folder_id = -1; + int item_id = 0; + + //if(intent.hasExtra(NewsReaderDetailActivity.SUBSCRIPTION_ID)) + // subsciption_id = intent.getExtras().getLong(NewsReaderDetailActivity.SUBSCRIPTION_ID); + //if(intent.hasExtra(NewsReaderDetailActivity.FOLDER_ID)) + // folder_id = intent.getExtras().getLong(NewsReaderDetailActivity.FOLDER_ID); + if(intent.hasExtra(NewsReaderDetailActivity.ITEM_ID)) + item_id = intent.getExtras().getInt(NewsReaderDetailActivity.ITEM_ID); + if(intent.hasExtra(NewsReaderDetailActivity.TITEL)) + getSupportActionBar().setTitle(intent.getExtras().getString(NewsReaderDetailActivity.TITEL)); + //getActionBar().setTitle(intent.getExtras().getString(NewsReaderDetailActivity.TITEL)); + + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + if(intent.hasExtra(DATABASE_IDS_OF_ITEMS)) + databaseItemIds = intent.getIntegerArrayListExtra(DATABASE_IDS_OF_ITEMS); + + + // Create the adapter that will return a fragment for each of the three + // primary sections of the app. + mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager()); + + // Set up the ViewPager with the sections adapter. + mViewPager = (ViewPager) findViewById(R.id.pager); + mViewPager.setAdapter(mSectionsPagerAdapter); + + + //rssFiles = new ArrayList(); + try + { + mViewPager.setCurrentItem(item_id, true); + PageChanged(item_id); + } + catch(Exception ex) + { + ex.printStackTrace(); + } + + mViewPager.setOnPageChangeListener(new OnPageChangeListener() { + + @Override + public void onPageSelected(int pos) { + PageChanged(pos); + } + + @Override + public void onPageScrolled(int arg0, float arg1, int arg2) { + } + + @Override + public void onPageScrollStateChanged(int arg0) { + } + }); + } + + @Override + protected void onDestroy() { + if(dbConn != null) + dbConn.closeDatabase(); + super.onDestroy(); + } + + + @Override + public boolean onKeyDown(int keyCode, KeyEvent event) { + SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this); + if(mPrefs.getBoolean(SettingsActivity.CB_NAVIGATE_WITH_VOLUME_BUTTONS_STRING, false)) + { + if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) + { + if(currentPosition < databaseItemIds.size() -1) + { + mViewPager.setCurrentItem(currentPosition + 1, true); + return true; + } + } + + else if ((keyCode == KeyEvent.KEYCODE_VOLUME_UP)) + { + if(currentPosition > 0) + { + mViewPager.setCurrentItem(currentPosition - 1, true); + return true; + } + } + } + if(keyCode == KeyEvent.KEYCODE_BACK) + { + NewsDetailFragment ndf = (NewsDetailFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + currentPosition); + if(ndf.webview != null) + { + if(ndf.webview.canGoBack()) + { + ndf.webview.goBack(); + if(!ndf.webview.canGoBack())//RssItem + ndf.LoadRssItemInWebView(); + + return true; + } + } + + /* + View vGroup = mViewPager.getChildAt(currentPosition); + + if(vGroup != null) + { + WebView webView = (WebView) vGroup.findViewById(R.id.webview); + if(webView != null) + { + if(webView.canGoBack()) + { + webView.goBack(); + if(!webView.canGoBack())//RssItem + { + NewsDetailFragment ndf = (NewsDetailFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + currentPosition); + ndf.LoadRssItemInWebView(this); + } + + return true; + } + } + }*/ + } + + return super.onKeyDown(keyCode, event); + } + + private void PageChanged(int position) + { + StopVideoOnCurrentPage(); + currentPosition = position; + ResumeVideoPlayersOnCurrentPage(); + + //String idFeed = String.valueOf(rssFiles.get(position).getDB_Id()); + String idFeed = String.valueOf(databaseItemIds.get(currentPosition)); + + if(!dbConn.isFeedUnreadStarred(idFeed, true)) + { + markItemAsReadUnread(idFeed, true); + + //Cursor cur = dbConn.getArticleByID(idFeed); + //cur.moveToFirst(); + //GoogleReaderMethods.MarkItemAsRead(true, cur, dbConn, getApplicationContext(), asyncTaskCompletedPerformTagRead); + + + /* + List idItems = new ArrayList(); + idItems.add(cur.getString(cur.getColumnIndex(DatabaseConnection.RSS_ITEM_RSSITEM_ID))); + _Reader.Start_AsyncTask_PerformTagActionForSingleItem(5, + this, + asyncTaskCompletedPerformTagRead, + idItems, + FeedItemTags.TAGS.MARK_ITEM_AS_READ); + + + cur.close(); + */ + //dbConn.closeDatabase(); + Log.d("PAGE CHANGED", "PAGE: " + position + " - IDFEED: " + idFeed); + } + else //Only in else because the function markItemAsReas updates the ActionBar items as well + UpdateActionBarIcons(); + } + + private void ResumeVideoPlayersOnCurrentPage() + { + NewsDetailFragment fragment = (NewsDetailFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + currentPosition); + if(fragment != null) // could be null if not instantiated yet + fragment.ResumeVideoPlayers(); + + } + + private void StopVideoOnCurrentPage() + { + NewsDetailFragment fragment = (NewsDetailFragment) getSupportFragmentManager().findFragmentByTag("android:switcher:" + R.id.pager + ":" + currentPosition); + if(fragment != null) // could be null if not instantiated yet + fragment.StopVideoPlayers(); + } + + public void UpdateActionBarIcons() + { + boolean isStarred = dbConn.isFeedUnreadStarred(String.valueOf(databaseItemIds.get(currentPosition)), false); + boolean isRead = dbConn.isFeedUnreadStarred(String.valueOf(databaseItemIds.get(currentPosition)), true); + + //if(rssFiles.get(currentPosition).getStarred() && menuItem_Starred != null) + if(isStarred && menuItem_Starred != null) + menuItem_Starred.setIcon(android.R.drawable.star_on); + //menuItem_Starred.setIcon(R.drawable.btn_rating_star_on_normal_holo_light); + else if(menuItem_Starred != null) + menuItem_Starred.setIcon(android.R.drawable.star_off); + //menuItem_Starred.setIcon(R.drawable.btn_rating_star_off_normal_holo_light); + + if(isRead && menuItem_Read != null) + menuItem_Read.setChecked(true); + else if(menuItem_Read != null) + menuItem_Read.setChecked(false); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + //getMenuInflater().inflate(R.menu.news_detail, menu); + getSupportMenuInflater().inflate(R.menu.news_detail, menu); + + menuItem_Starred = menu.findItem(R.id.action_starred); + menuItem_Read = menu.findItem(R.id.action_read); + UpdateActionBarIcons(); + + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + Cursor cursor = dbConn.getArticleByID(String.valueOf(databaseItemIds.get(currentPosition))); + + switch (item.getItemId()) { + case android.R.id.home: + super.onBackPressed(); + break; + + case R.id.action_starred: + //String idItem_Db = String.valueOf(rssFiles.get(currentPosition).getDB_Id()); + String idItem_Db = String.valueOf(databaseItemIds.get(currentPosition)); + //String idItem = String.valueOf(rssFiles.get(currentPosition).getItem_Id()); + Boolean curState = dbConn.isFeedUnreadStarred(idItem_Db, false); + + //rssFiles.get(currentPosition).setStarred(!curState); + + dbConn.updateIsStarredOfFeed(idItem_Db, !curState); + + UpdateActionBarIcons(); + + List idItems = new ArrayList(); + cursor.moveToFirst(); + idItems.add(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_RSSITEM_ID))); + cursor.close(); + + /* + if(!curState) + _Reader.Start_AsyncTask_PerformTagActionForSingleItem(0, this, asyncTaskCompletedPerformTagRead, idItems, FeedItemTags.TAGS.MARK_ITEM_AS_STARRED); + else + _Reader.Start_AsyncTask_PerformTagActionForSingleItem(0, this, asyncTaskCompletedPerformTagRead, idItems, FeedItemTags.TAGS.MARK_ITEM_AS_UNSTARRED); + + */ + /* + Cursor cur = dbConn.getFeedByID(idFeed); + cur.moveToFirst(); + GoogleReaderMethods.MarkItemAsStarred(!curState, cur, dbConn, getApplicationContext(), asyncTaskCompletedPerformTagStarred); + cur.close();*/ + break; + + case R.id.action_openInBrowser: + //String link = rssFiles.get(currentPosition).getLink(); + String link = ""; + + if(cursor != null) + { + cursor.moveToFirst(); + link = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_LINK)); + cursor.close(); + } + + //if(!link.isEmpty()) + if(link.trim().length() > 0) + { + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(link)); + startActivity(browserIntent); + } + break; + + case R.id.action_sendSourceCode: + String description = ""; + if(cursor != null) + { + cursor.moveToFirst(); + description = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_BODY)); + cursor.close(); + } + + + Intent i = new Intent(Intent.ACTION_SEND); + i.setType("message/rfc822"); + i.putExtra(Intent.EXTRA_EMAIL , new String[]{"david-dev@live.de"}); + i.putExtra(Intent.EXTRA_SUBJECT, getString(R.string.email_sourceCode)); + //i.putExtra(Intent.EXTRA_TEXT , rssFiles.get(currentPosition).getDescription()); + i.putExtra(Intent.EXTRA_TEXT , description); + try { + startActivity(Intent.createChooser(i, getString(R.string.email_sendMail))); + } catch (android.content.ActivityNotFoundException ex) { + Toast.makeText(NewsDetailActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show(); + } + break; + + case R.id.action_ShareItem: + + String title = ""; + String linkToItem = ""; + if(cursor != null) + { + cursor.moveToFirst(); + title = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_TITLE)); + linkToItem = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_LINK)); + cursor.close(); + } + + Intent share = new Intent(Intent.ACTION_SEND); + share.setType("text/plain"); + //share.putExtra(Intent.EXTRA_SUBJECT, rssFiles.get(currentPosition).getTitle()); + //share.putExtra(Intent.EXTRA_TEXT, rssFiles.get(currentPosition).getLink()); + share.putExtra(Intent.EXTRA_SUBJECT, title); + share.putExtra(Intent.EXTRA_TEXT, linkToItem); + + startActivity(Intent.createChooser(share, "Share Item")); + break; + + case R.id.action_read: + + if(cursor != null) + { + cursor.moveToFirst(); + String id = cursor.getString(0); + markItemAsReadUnread(id, !menuItem_Read.isChecked()); + cursor.close(); + } + + break; + } + return super.onOptionsItemSelected(item); + } + + + private void markItemAsReadUnread(String item_id, boolean read) { + dbConn.updateIsReadOfFeed(item_id, read); + UpdateActionBarIcons(); + } + + + /* + OnAsyncTaskCompletedListener asyncTaskCompletedPerformTagRead = new OnAsyncTaskCompletedListener() { + + @Override + public void onAsyncTaskCompleted(int task_id, Object task_result) { + boolean success = (Boolean) task_result; + if(!success) + Toast.makeText(NewsDetailActivity.this, "Error while changing the read tag..", Toast.LENGTH_LONG).show(); + + Log.d("FINISHED PERFORM TAG READ ", "" + task_result); + } + }; + + OnAsyncTaskCompletedListener asyncTaskCompletedPerformTagStarred = new OnAsyncTaskCompletedListener() { + + @Override + public void onAsyncTaskCompleted(int task_id, Object task_result) { + Log.d("FINISHED PERFORM TAG STARRED ", "" + task_result); + } + }; + */ + + @Override + public void finish() { + Intent intent = new Intent(); + intent.putExtra("POS", mViewPager.getCurrentItem()); + setResult(RESULT_OK, intent); + super.finish(); + } + + /** + * A {@link FragmentPagerAdapter} that returns a fragment corresponding to + * one of the sections/tabs/pages. + */ + public class SectionsPagerAdapter extends FragmentPagerAdapter { + //public class SectionsPagerAdapter extends FragmentStatePagerAdapter { + + + public SectionsPagerAdapter(FragmentManager fm) { + super(fm); + } + + @Override + public Fragment getItem(int position) { + // getItem is called to instantiate the fragment for the given page. + // Return a DummySectionFragment (defined as a static inner class + // below) with the page number as its lone argument. + Fragment fragment = new NewsDetailFragment(); + Bundle args = new Bundle(); + args.putInt(NewsDetailFragment.ARG_SECTION_NUMBER, position + 1); + fragment.setArguments(args); + return fragment; + } + + + @Override + public int getCount() { + //return 2; + return databaseItemIds.size(); + //return rssFiles.size(); + } + + @Override + public CharSequence getPageTitle(int position) { + /* + Locale l = Locale.getDefault(); + switch (position) { + case 0: + return getString(R.string.title_section1).toUpperCase(l); + case 1: + return getString(R.string.title_section2).toUpperCase(l); + case 2: + return getString(R.string.title_section3).toUpperCase(l); + } + */ + return null; + } + } +} diff --git a/src/de/luhmer/owncloudnewsreader/NewsReaderDetailActivity.java b/src/de/luhmer/owncloudnewsreader/NewsReaderDetailActivity.java index 4beb594e..c3429eb6 100644 --- a/src/de/luhmer/owncloudnewsreader/NewsReaderDetailActivity.java +++ b/src/de/luhmer/owncloudnewsreader/NewsReaderDetailActivity.java @@ -1,154 +1,154 @@ -package de.luhmer.owncloudnewsreader; - -import android.annotation.TargetApi; -import android.content.Intent; -import android.os.Build; -import android.os.Bundle; -import android.support.v4.app.FragmentActivity; -import android.support.v4.app.NavUtils; - -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuItem; - -import de.luhmer.owncloudnewsreader.helper.MenuUtilsSherlockFragmentActivity; -import de.luhmer.owncloudnewsreader.helper.ThemeChooser; - -/** - * An activity representing a single NewsReader detail screen. This activity is - * only used on handset devices. On tablet-size devices, item details are - * presented side-by-side with a list of items in a - * {@link NewsReaderListActivity}. - *

- * This activity is mostly just a 'shell' activity containing nothing more than - * a {@link NewsReaderDetailFragment}. - */ -public class NewsReaderDetailActivity extends MenuUtilsSherlockFragmentActivity { - - public static final String FOLDER_ID = "FOLDER_ID"; - public static final String SUBSCRIPTION_ID = "SUBSCRIPTION_ID"; - public static final String ITEM_ID = "ITEM_ID"; - public static final String TITEL = "TITEL"; - protected static final String TAG = "NewsReaderDetailActivity"; - - - String titel; - - - @Override - protected void onCreate(Bundle savedInstanceState) { - - ThemeChooser.chooseTheme(this); - - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_newsreader_detail); - - // Show the Up button in the action bar. - //getActionBar().setDisplayHomeAsUpEnabled(true); - getSupportActionBar().setDisplayHomeAsUpEnabled(true); - - // savedInstanceState is non-null when there is fragment state - // saved from previous configurations of this activity - // (e.g. when rotating the screen from portrait to landscape). - // In this case, the fragment will automatically be re-added - // to its container so we don't need to manually add it. - // For more information, see the Fragments API guide at: - // - // http://developer.android.com/guide/components/fragments.html - // - if (savedInstanceState == null) { - - Intent intent = getIntent(); - titel = "Name Missing"; - - String idFeed = null; - String idFolder = null; - - if(intent.hasExtra(SUBSCRIPTION_ID)) - idFeed = intent.getExtras().getString(SUBSCRIPTION_ID); - if(intent.hasExtra(FOLDER_ID)) - idFolder = intent.getExtras().getString(FOLDER_ID); - if(intent.hasExtra(TITEL)) - titel = intent.getExtras().getString(TITEL); - - //getSupportActionBar().setTitle(titel); - - - - // Create the detail fragment and add it to the activity - // using a fragment transaction. - Bundle arguments = new Bundle(); - arguments.putString( - NewsReaderDetailFragment.ARG_ITEM_ID, - getIntent().getStringExtra( - NewsReaderDetailFragment.ARG_ITEM_ID)); - - if(idFeed != null) - arguments.putString(SUBSCRIPTION_ID, idFeed); - if(idFolder != null) - arguments.putString(FOLDER_ID, idFolder); - - arguments.putString(TITEL, titel); - NewsReaderDetailFragment fragment = new NewsReaderDetailFragment(); - fragment.setArguments(arguments); - getSupportFragmentManager().beginTransaction() - .add(R.id.newsreader_detail_container, fragment).commit(); - } - } - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - // Inflate the menu; this adds items to the action bar if it is present. - //getSupportMenuInflater().inflate(R.menu.subscription, menu); - - super.onCreateOptionsMenu(menu, getSupportMenuInflater(), true, this); - - return true; - } - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - //if (requestCode == 1) { - if(resultCode == RESULT_OK){ - int pos = data.getIntExtra("POS", 0); - UpdateListViewAndScrollToPos(this, pos); - } - if (resultCode == RESULT_CANCELED) { - //Write your code on no result return - } - //} - } - - - @TargetApi(Build.VERSION_CODES.FROYO) - public static void UpdateListViewAndScrollToPos(FragmentActivity act, int pos) - { - ((NewsReaderDetailFragment) act.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)).lvAdapter.notifyDataSetChanged(); - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) - ((NewsReaderDetailFragment) act.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)).getListView().smoothScrollToPosition(pos); - else - ((NewsReaderDetailFragment) act.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)).getListView().setSelection(pos); - - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - boolean handled = super.onOptionsItemSelected(item, this); - if(!handled) - { - switch (item.getItemId()) { - case android.R.id.home: - // This ID represents the Home or Up button. In the case of this - // activity, the Up button is shown. Use NavUtils to allow users - // to navigate up one level in the application structure. For - // more details, see the Navigation pattern on Android Design: - // - // http://developer.android.com/design/patterns/navigation.html#up-vs-back - // - NavUtils.navigateUpTo(this, new Intent(this, - NewsReaderListActivity.class)); - return true; - } - } - return super.onOptionsItemSelected(item); - } -} +package de.luhmer.owncloudnewsreader; + +import android.annotation.TargetApi; +import android.content.Intent; +import android.os.Build; +import android.os.Bundle; +import android.support.v4.app.FragmentActivity; +import android.support.v4.app.NavUtils; + +import com.actionbarsherlock.view.Menu; +import com.actionbarsherlock.view.MenuItem; + +import de.luhmer.owncloudnewsreader.helper.MenuUtilsSherlockFragmentActivity; +import de.luhmer.owncloudnewsreader.helper.ThemeChooser; + +/** + * An activity representing a single NewsReader detail screen. This activity is + * only used on handset devices. On tablet-size devices, item details are + * presented side-by-side with a list of items in a + * {@link NewsReaderListActivity}. + *

+ * This activity is mostly just a 'shell' activity containing nothing more than + * a {@link NewsReaderDetailFragment}. + */ +public class NewsReaderDetailActivity extends MenuUtilsSherlockFragmentActivity { + + public static final String FOLDER_ID = "FOLDER_ID"; + public static final String SUBSCRIPTION_ID = "SUBSCRIPTION_ID"; + public static final String ITEM_ID = "ITEM_ID"; + public static final String TITEL = "TITEL"; + protected static final String TAG = "NewsReaderDetailActivity"; + + + String titel; + + + @Override + protected void onCreate(Bundle savedInstanceState) { + + ThemeChooser.chooseTheme(this); + + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_newsreader_detail); + + // Show the Up button in the action bar. + //getActionBar().setDisplayHomeAsUpEnabled(true); + getSupportActionBar().setDisplayHomeAsUpEnabled(true); + + // savedInstanceState is non-null when there is fragment state + // saved from previous configurations of this activity + // (e.g. when rotating the screen from portrait to landscape). + // In this case, the fragment will automatically be re-added + // to its container so we don't need to manually add it. + // For more information, see the Fragments API guide at: + // + // http://developer.android.com/guide/components/fragments.html + // + if (savedInstanceState == null) { + + Intent intent = getIntent(); + titel = "Name Missing"; + + String idFeed = null; + String idFolder = null; + + if(intent.hasExtra(SUBSCRIPTION_ID)) + idFeed = intent.getExtras().getString(SUBSCRIPTION_ID); + if(intent.hasExtra(FOLDER_ID)) + idFolder = intent.getExtras().getString(FOLDER_ID); + if(intent.hasExtra(TITEL)) + titel = intent.getExtras().getString(TITEL); + + //getSupportActionBar().setTitle(titel); + + + + // Create the detail fragment and add it to the activity + // using a fragment transaction. + Bundle arguments = new Bundle(); + arguments.putString( + NewsReaderDetailFragment.ARG_ITEM_ID, + getIntent().getStringExtra( + NewsReaderDetailFragment.ARG_ITEM_ID)); + + if(idFeed != null) + arguments.putString(SUBSCRIPTION_ID, idFeed); + if(idFolder != null) + arguments.putString(FOLDER_ID, idFolder); + + arguments.putString(TITEL, titel); + NewsReaderDetailFragment fragment = new NewsReaderDetailFragment(); + fragment.setArguments(arguments); + getSupportFragmentManager().beginTransaction() + .add(R.id.newsreader_detail_container, fragment).commit(); + } + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + //getSupportMenuInflater().inflate(R.menu.subscription, menu); + + super.onCreateOptionsMenu(menu, getSupportMenuInflater(), true, this); + + return true; + } + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + //if (requestCode == 1) { + if(resultCode == RESULT_OK){ + int pos = data.getIntExtra("POS", 0); + UpdateListViewAndScrollToPos(this, pos); + } + if (resultCode == RESULT_CANCELED) { + //Write your code on no result return + } + //} + } + + + @TargetApi(Build.VERSION_CODES.FROYO) + public static void UpdateListViewAndScrollToPos(FragmentActivity act, int pos) + { + ((NewsReaderDetailFragment) act.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)).getLvAdapter().notifyDataSetChanged(); + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) + ((NewsReaderDetailFragment) act.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)).getListView().smoothScrollToPosition(pos); + else + ((NewsReaderDetailFragment) act.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)).getListView().setSelection(pos); + + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + boolean handled = super.onOptionsItemSelected(item, this); + if(!handled) + { + switch (item.getItemId()) { + case android.R.id.home: + // This ID represents the Home or Up button. In the case of this + // activity, the Up button is shown. Use NavUtils to allow users + // to navigate up one level in the application structure. For + // more details, see the Navigation pattern on Android Design: + // + // http://developer.android.com/design/patterns/navigation.html#up-vs-back + // + NavUtils.navigateUpTo(this, new Intent(this, + NewsReaderListActivity.class)); + return true; + } + } + return super.onOptionsItemSelected(item); + } +} diff --git a/src/de/luhmer/owncloudnewsreader/NewsReaderDetailFragment.java b/src/de/luhmer/owncloudnewsreader/NewsReaderDetailFragment.java index 150e467e..dd8cd2a8 100644 --- a/src/de/luhmer/owncloudnewsreader/NewsReaderDetailFragment.java +++ b/src/de/luhmer/owncloudnewsreader/NewsReaderDetailFragment.java @@ -1,303 +1,346 @@ -package de.luhmer.owncloudnewsreader; - -import java.util.ArrayList; - -import android.app.Activity; -import android.content.Intent; -import android.content.SharedPreferences; -import android.database.Cursor; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.widget.AbsListView; -import android.widget.CheckBox; -import android.widget.ListView; - -import com.actionbarsherlock.app.SherlockFragmentActivity; -import com.actionbarsherlock.app.SherlockListFragment; - -import de.luhmer.owncloudnewsreader.ListView.SubscriptionExpandableListAdapter; -import de.luhmer.owncloudnewsreader.cursor.NewsListCursorAdapter; -import de.luhmer.owncloudnewsreader.database.DatabaseConnection; -import de.luhmer.owncloudnewsreader.helper.MenuUtilsSherlockFragmentActivity; - -/** - * A fragment representing a single NewsReader detail screen. This fragment is - * either contained in a {@link NewsReaderListActivity} in two-pane mode (on - * tablets) or a {@link NewsReaderDetailActivity} on handsets. - */ -public class NewsReaderDetailFragment extends SherlockListFragment { - /** - * The fragment argument representing the item ID that this fragment - * represents. - */ - public static final String ARG_ITEM_ID = "item_id"; - - protected static final String TAG = "NewsReaderDetailFragment"; - - DatabaseConnection dbConn; - NewsListCursorAdapter lvAdapter; - String idFeed; - /** - * @return the idFeed - */ - public String getIdFeed() { - return idFeed; - } - - String idFolder; - /** - * @return the idFolder - */ - public String getIdFolder() { - return idFolder; - } - - String titel; - int lastItemPosition; - - ArrayList databaseIdsOfItems; - - /** - * Mandatory empty constructor for the fragment manager to instantiate the - * fragment (e.g. upon screen orientation changes). - */ - public NewsReaderDetailFragment() { - databaseIdsOfItems = new ArrayList(); - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - /* - if (getArguments().containsKey(ARG_ITEM_ID)) { - // Load the dummy content specified by the fragment - // arguments. In a real-world scenario, use a Loader - // to load content from a content provider. - - mItem = DummyContent.ITEM_MAP.get(getArguments().getString( - ARG_ITEM_ID)); - - }*/ - - if (getArguments().containsKey(NewsReaderDetailActivity.SUBSCRIPTION_ID)) { - idFeed = getArguments().getString(NewsReaderDetailActivity.SUBSCRIPTION_ID); - } - if (getArguments().containsKey(NewsReaderDetailActivity.TITEL)) { - titel = getArguments().getString(NewsReaderDetailActivity.TITEL); - } - if (getArguments().containsKey(NewsReaderDetailActivity.FOLDER_ID)) { - idFolder = getArguments().getString(NewsReaderDetailActivity.FOLDER_ID); - } - - dbConn = new DatabaseConnection(getActivity()); - - ((SherlockFragmentActivity) getActivity()).getSupportActionBar().setTitle(titel); - - UpdateMenuItemsState();//Is called on Tablets and Smartphones but on Smartphones the menuItemDownloadMoreItems is null. So it will be ignored - - //getListView().setLayerType(View.LAYER_TYPE_SOFTWARE, null); - - //lvAdapter = new Subscription_ListViewAdapter(this); - UpdateCursor(); - } - - @SuppressWarnings("static-access") - public void UpdateMenuItemsState() - { - MenuUtilsSherlockFragmentActivity mActivity = ((MenuUtilsSherlockFragmentActivity) getActivity()); - - if(mActivity.getMenuItemDownloadMoreItems() != null) - { - if(idFolder.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS)) - mActivity.getMenuItemDownloadMoreItems().setEnabled(false); - else - mActivity.getMenuItemDownloadMoreItems().setEnabled(true); - } - } - - - /* (non-Javadoc) - * @see android.support.v4.app.ListFragment#onViewCreated(android.view.View, android.os.Bundle) - */ - @Override - public void onViewCreated(View view, Bundle savedInstanceState) { - - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); - if(mPrefs.getBoolean(SettingsActivity.CB_MARK_AS_READ_WHILE_SCROLLING_STRING, false)) - { - getListView().setOnScrollListener(new AbsListView.OnScrollListener() { - - public void onScrollStateChanged(AbsListView view, int scrollState) { - /* - Log.d(TAG, "LOL" + scrollState); - if(AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL == scrollState) - { - - }*/ - } - - - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - CheckBox cb = getCheckBoxAtPosition(0, view); - ChangeCheckBoxState(cb, true); - - if((firstVisibleItem + visibleItemCount) == totalItemCount) { - for (int i = firstVisibleItem + 1; i < firstVisibleItem + visibleItemCount; i++) { - cb = getCheckBoxAtPosition(i - firstVisibleItem, view); - ChangeCheckBoxState(cb, true); - } - } - } - - /* - public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { - for (int i = firstVisibleItem; i < firstVisibleItem + visibleItemCount; i++) { - - if(lastItemPosition < firstVisibleItem) - { - lastItemPosition = firstVisibleItem; - - CheckBox cb = (CheckBox) view.findViewById(R.id.cb_lv_item_read); - if(!cb.isChecked()) - cb.setChecked(true); - - //dbConn. - } - - //Cursor cursor = (Cursor)view.getItemAtPosition(i); - //long id = cursor.getLong(cursor.getColumnIndex(AlertsContract._ID)); - //String type = cursor.getString(cursor.getColumnIndex(AlertsContract.TYPE)); - //Log.d("VIEWED", "This is viewed "+ type + " id: " + id); - //Log.d("VIEWED", "This is viewed "+ firstVisibleItem + " id: "); - - // here I can get the id and mark the item read - } - }*/ - - - }); - } - - super.onViewCreated(view, savedInstanceState); - } - - private void ChangeCheckBoxState(CheckBox cb, boolean state) - { - if(cb != null) - if(cb.isChecked() != state) - cb.setChecked(state); - } - - private CheckBox getCheckBoxAtPosition(int pos, AbsListView viewLV) - { - ListView lv = (ListView) viewLV; - View view = (View) lv.getChildAt(pos); - if(view != null) - return (CheckBox) view.findViewById(R.id.cb_lv_item_read); - else - return null; - } - - - /* (non-Javadoc) - * @see android.support.v4.app.Fragment#onResume() - */ - @Override - public void onResume() { - lastItemPosition = -1; - super.onResume(); - } - - @Override - public void onDestroy() { - if(lvAdapter != null) - lvAdapter.CloseDatabaseConnection(); - if(dbConn != null) - dbConn.closeDatabase(); - super.onDestroy(); - } - - public void UpdateCursor() - { - try - { - Cursor cursor = getRightCusor(idFolder); - - databaseIdsOfItems.clear(); - if(cursor != null) - while(cursor.moveToNext()) - databaseIdsOfItems.add(cursor.getInt(0)); - - - if(lvAdapter == null) - { - lvAdapter = new NewsListCursorAdapter(getActivity(), cursor); - setListAdapter(lvAdapter); - } - else - lvAdapter.changeCursor(cursor); - - } - catch(Exception ex) - { - ex.printStackTrace(); - } - } - - public Cursor getRightCusor(String ID_FOLDER) - { - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); - boolean onlyUnreadItems = mPrefs.getBoolean(SettingsActivity.CB_SHOWONLYUNREAD_STRING, false); - boolean onlyStarredItems = false; - if(ID_FOLDER != null) - if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS)) - onlyStarredItems = true; - - if(idFeed != null) - return dbConn.getAllItemsForFeed(idFeed, onlyUnreadItems, onlyStarredItems); - else if(idFolder != null) - { - if(idFolder.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS)) - onlyUnreadItems = false; - return dbConn.getAllItemsForFolder(idFolder, onlyUnreadItems); - } - return null; - } - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View rootView = inflater.inflate(R.layout.fragment_newsreader_detail, container, false); - return rootView; - } - - @Override - public void onListItemClick(ListView l, View v, int position, long id) { - - Intent intentNewsDetailAct = new Intent(getActivity(), NewsDetailActivity.class); - //if(idSubscription != null) - // intentNewsDetailAct.putExtra(NewsReaderDetailActivity.SUBSCRIPTION_ID, Long.valueOf(idSubscription)); - //else if(idFolder != null) - // intentNewsDetailAct.putExtra(NewsReaderDetailActivity.FOLDER_ID, Long.valueOf(idFolder)); - - //intentNewsDetailAct.putIntegerArrayListExtra(NewsDetailActivity.DATABASE_IDS_OF_ITEMS, databaseIdsOfItems); - //Integer[] databaseIdsOfItemsArray = databaseIdsOfItems.toArray(new Integer[databaseIdsOfItems.size()]); - intentNewsDetailAct.putIntegerArrayListExtra(NewsDetailActivity.DATABASE_IDS_OF_ITEMS, databaseIdsOfItems); - - intentNewsDetailAct.putExtra(NewsReaderDetailActivity.ITEM_ID, position); - intentNewsDetailAct.putExtra(NewsReaderDetailActivity.TITEL, titel); - startActivityForResult(intentNewsDetailAct, Activity.RESULT_CANCELED); - - super.onListItemClick(l, v, position, id); - } - - public ArrayList getDatabaseIdsOfItems() { - return databaseIdsOfItems; - } - -} +package de.luhmer.owncloudnewsreader; + +import java.util.ArrayList; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.AbsListView; +import android.widget.CheckBox; +import android.widget.ListView; + +import com.actionbarsherlock.app.SherlockFragmentActivity; +import com.actionbarsherlock.app.SherlockListFragment; + +import de.luhmer.owncloudnewsreader.ListView.SubscriptionExpandableListAdapter; +import de.luhmer.owncloudnewsreader.cursor.NewsListCursorAdapter; +import de.luhmer.owncloudnewsreader.database.DatabaseConnection; +import de.luhmer.owncloudnewsreader.helper.MenuUtilsSherlockFragmentActivity; + +/** + * A fragment representing a single NewsReader detail screen. This fragment is + * either contained in a {@link NewsReaderListActivity} in two-pane mode (on + * tablets) or a {@link NewsReaderDetailActivity} on handsets. + */ +public class NewsReaderDetailFragment extends SherlockListFragment { + /** + * The fragment argument representing the item ID that this fragment + * represents. + */ + public static final String ARG_ITEM_ID = "item_id"; + + protected static final String TAG = "NewsReaderDetailFragment"; + + private DatabaseConnection dbConn; + + private boolean DialogShowedToMarkLastItemsAsRead = false; + + private NewsListCursorAdapter lvAdapter; + /** + * @return the lvAdapter + */ + public NewsListCursorAdapter getLvAdapter() { + return lvAdapter; + } + + String idFeed; + /** + * @return the idFeed + */ + public String getIdFeed() { + return idFeed; + } + + String idFolder; + /** + * @return the idFolder + */ + public String getIdFolder() { + return idFolder; + } + + String titel; + int lastItemPosition; + + ArrayList databaseIdsOfItems; + + /** + * Mandatory empty constructor for the fragment manager to instantiate the + * fragment (e.g. upon screen orientation changes). + */ + public NewsReaderDetailFragment() { + databaseIdsOfItems = new ArrayList(); + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + /* + if (getArguments().containsKey(ARG_ITEM_ID)) { + // Load the dummy content specified by the fragment + // arguments. In a real-world scenario, use a Loader + // to load content from a content provider. + + mItem = DummyContent.ITEM_MAP.get(getArguments().getString( + ARG_ITEM_ID)); + + }*/ + + if (getArguments().containsKey(NewsReaderDetailActivity.SUBSCRIPTION_ID)) { + idFeed = getArguments().getString(NewsReaderDetailActivity.SUBSCRIPTION_ID); + } + if (getArguments().containsKey(NewsReaderDetailActivity.TITEL)) { + titel = getArguments().getString(NewsReaderDetailActivity.TITEL); + } + if (getArguments().containsKey(NewsReaderDetailActivity.FOLDER_ID)) { + idFolder = getArguments().getString(NewsReaderDetailActivity.FOLDER_ID); + } + + dbConn = new DatabaseConnection(getActivity()); + + ((SherlockFragmentActivity) getActivity()).getSupportActionBar().setTitle(titel); + + UpdateMenuItemsState();//Is called on Tablets and Smartphones but on Smartphones the menuItemDownloadMoreItems is null. So it will be ignored + + //getListView().setLayerType(View.LAYER_TYPE_SOFTWARE, null); + + //lvAdapter = new Subscription_ListViewAdapter(this); + UpdateCursor(); + } + + @SuppressWarnings("static-access") + public void UpdateMenuItemsState() + { + MenuUtilsSherlockFragmentActivity mActivity = ((MenuUtilsSherlockFragmentActivity) getActivity()); + + if(mActivity.getMenuItemDownloadMoreItems() != null) + { + if(idFolder.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS)) + mActivity.getMenuItemDownloadMoreItems().setEnabled(false); + else + mActivity.getMenuItemDownloadMoreItems().setEnabled(true); + } + } + + + /* (non-Javadoc) + * @see android.support.v4.app.ListFragment#onViewCreated(android.view.View, android.os.Bundle) + */ + @Override + public void onViewCreated(View view, Bundle savedInstanceState) { + + SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); + if(mPrefs.getBoolean(SettingsActivity.CB_MARK_AS_READ_WHILE_SCROLLING_STRING, false)) + { + getListView().setOnScrollListener(new AbsListView.OnScrollListener() { + + public void onScrollStateChanged(AbsListView view, int scrollState) { + + //Log.d(TAG, "Scroll: " + scrollState); + /* + if(AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL == scrollState) + { + + }*/ + } + + + public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount, int totalItemCount) { + CheckBox cb = getCheckBoxAtPosition(0, view); + NewsListCursorAdapter.ChangeCheckBoxState(cb, true, getActivity()); + + if(((firstVisibleItem + visibleItemCount) == totalItemCount) && !DialogShowedToMarkLastItemsAsRead ){ + + DialogShowedToMarkLastItemsAsRead = true; + + boolean needQuestion = false; + for (int i = firstVisibleItem + 1; i < firstVisibleItem + visibleItemCount; i++) { + cb = getCheckBoxAtPosition(i - firstVisibleItem, view); + if(!cb.isChecked()) + { + needQuestion = true; + break; + } + } + + if(needQuestion) + new AlertDialog.Builder(getActivity()) + .setTitle("Alle als gelesen markieren ?") + .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { + + @Override + public void onClick(DialogInterface dialog, int which) { + for (int i = firstVisibleItem + 1; i < firstVisibleItem + visibleItemCount; i++) { + CheckBox cb = getCheckBoxAtPosition(i - firstVisibleItem, view); + NewsListCursorAdapter.ChangeCheckBoxState(cb, true, getActivity()); + } + } + }) + .setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int id) { + // if this button is clicked, just close + // the dialog box and do nothing + dialog.cancel(); + } + }) + .create() + .show(); + + + + } + } + + /* + public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { + for (int i = firstVisibleItem; i < firstVisibleItem + visibleItemCount; i++) { + + if(lastItemPosition < firstVisibleItem) + { + lastItemPosition = firstVisibleItem; + + CheckBox cb = (CheckBox) view.findViewById(R.id.cb_lv_item_read); + if(!cb.isChecked()) + cb.setChecked(true); + + //dbConn. + } + + //Cursor cursor = (Cursor)view.getItemAtPosition(i); + //long id = cursor.getLong(cursor.getColumnIndex(AlertsContract._ID)); + //String type = cursor.getString(cursor.getColumnIndex(AlertsContract.TYPE)); + //Log.d("VIEWED", "This is viewed "+ type + " id: " + id); + //Log.d("VIEWED", "This is viewed "+ firstVisibleItem + " id: "); + + // here I can get the id and mark the item read + } + }*/ + + + }); + } + + super.onViewCreated(view, savedInstanceState); + } + + + + private CheckBox getCheckBoxAtPosition(int pos, AbsListView viewLV) + { + ListView lv = (ListView) viewLV; + View view = (View) lv.getChildAt(pos); + if(view != null) + return (CheckBox) view.findViewById(R.id.cb_lv_item_read); + else + return null; + } + + + /* (non-Javadoc) + * @see android.support.v4.app.Fragment#onResume() + */ + @Override + public void onResume() { + lastItemPosition = -1; + super.onResume(); + } + + @Override + public void onDestroy() { + if(lvAdapter != null) + lvAdapter.CloseDatabaseConnection(); + if(dbConn != null) + dbConn.closeDatabase(); + super.onDestroy(); + } + + public void UpdateCursor() + { + try + { + Cursor cursor = getRightCusor(idFolder); + + databaseIdsOfItems.clear(); + if(cursor != null) + while(cursor.moveToNext()) + databaseIdsOfItems.add(cursor.getInt(0)); + + + if(lvAdapter == null) + { + lvAdapter = new NewsListCursorAdapter(getActivity(), cursor); + setListAdapter(lvAdapter); + } + else + lvAdapter.changeCursor(cursor); + + } + catch(Exception ex) + { + ex.printStackTrace(); + } + } + + public Cursor getRightCusor(String ID_FOLDER) + { + SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); + boolean onlyUnreadItems = mPrefs.getBoolean(SettingsActivity.CB_SHOWONLYUNREAD_STRING, false); + boolean onlyStarredItems = false; + if(ID_FOLDER != null) + if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS)) + onlyStarredItems = true; + + if(idFeed != null) + return dbConn.getAllItemsForFeed(idFeed, onlyUnreadItems, onlyStarredItems); + else if(idFolder != null) + { + if(idFolder.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS)) + onlyUnreadItems = false; + return dbConn.getAllItemsForFolder(idFolder, onlyUnreadItems); + } + return null; + } + + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View rootView = inflater.inflate(R.layout.fragment_newsreader_detail, container, false); + return rootView; + } + + @Override + public void onListItemClick(ListView l, View v, int position, long id) { + + Intent intentNewsDetailAct = new Intent(getActivity(), NewsDetailActivity.class); + //if(idSubscription != null) + // intentNewsDetailAct.putExtra(NewsReaderDetailActivity.SUBSCRIPTION_ID, Long.valueOf(idSubscription)); + //else if(idFolder != null) + // intentNewsDetailAct.putExtra(NewsReaderDetailActivity.FOLDER_ID, Long.valueOf(idFolder)); + + //intentNewsDetailAct.putIntegerArrayListExtra(NewsDetailActivity.DATABASE_IDS_OF_ITEMS, databaseIdsOfItems); + //Integer[] databaseIdsOfItemsArray = databaseIdsOfItems.toArray(new Integer[databaseIdsOfItems.size()]); + intentNewsDetailAct.putIntegerArrayListExtra(NewsDetailActivity.DATABASE_IDS_OF_ITEMS, databaseIdsOfItems); + + intentNewsDetailAct.putExtra(NewsReaderDetailActivity.ITEM_ID, position); + intentNewsDetailAct.putExtra(NewsReaderDetailActivity.TITEL, titel); + startActivityForResult(intentNewsDetailAct, Activity.RESULT_CANCELED); + + super.onListItemClick(l, v, position, id); + } + + public ArrayList getDatabaseIdsOfItems() { + return databaseIdsOfItems; + } + +} diff --git a/src/de/luhmer/owncloudnewsreader/NewsReaderListActivity.java b/src/de/luhmer/owncloudnewsreader/NewsReaderListActivity.java index 28852bf6..7dbcbfa1 100644 --- a/src/de/luhmer/owncloudnewsreader/NewsReaderListActivity.java +++ b/src/de/luhmer/owncloudnewsreader/NewsReaderListActivity.java @@ -1,332 +1,334 @@ -package de.luhmer.owncloudnewsreader; - -import android.content.Intent; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; - -import com.actionbarsherlock.app.SherlockDialogFragment; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuItem; -import com.handmark.pulltorefresh.library.PullToRefreshExpandableListView; - -import de.luhmer.owncloudnewsreader.database.DatabaseConnection; -import de.luhmer.owncloudnewsreader.helper.MenuUtilsSherlockFragmentActivity; -import de.luhmer.owncloudnewsreader.helper.ThemeChooser; -import de.luhmer.owncloudnewsreader.reader.IReader; -import de.luhmer.owncloudnewsreader.services.DownloadImagesService; - -/** - * An activity representing a list of NewsReader. This activity has different - * presentations for handset and tablet-size devices. On handsets, the activity - * presents a list of items, which when touched, lead to a - * {@link NewsReaderDetailActivity} representing item details. On tablets, the - * activity presents the list of items and item details side-by-side using two - * vertical panes. - *

- * The activity makes heavy use of fragments. The list of items is a - * {@link NewsReaderListFragment} and the item details (if present) is a - * {@link NewsReaderDetailFragment}. - *

- * This activity also implements the required - * {@link NewsReaderListFragment.Callbacks} interface to listen for item - * selections. - */ -public class NewsReaderListActivity extends MenuUtilsSherlockFragmentActivity implements - NewsReaderListFragment.Callbacks { - - /** - * Whether or not the activity is in two-pane mode, i.e. running on a tablet - * device. - */ - private boolean mTwoPane; - //IabHelper mHelper; - static final String TAG = "NewsReaderListActivity"; - - @Override - protected void onCreate(Bundle savedInstanceState) { - - ThemeChooser.chooseTheme(this); - - //setTheme(R.style.Theme_Sherlock); - - super.onCreate(savedInstanceState); - setContentView(R.layout.activity_newsreader_list); - - - if (findViewById(R.id.newsreader_detail_container) != null) { - // The detail container view will be present only in the - // large-screen layouts (res/values-large and - // res/values-sw600dp). If this view is present, then the - // activity should be in two-pane mode. - mTwoPane = true; - - // In two-pane mode, list items should be given the - // 'activated' state when touched. - - ((NewsReaderListFragment) getSupportFragmentManager() - .findFragmentById(R.id.newsreader_list)) - .setActivateOnItemClick(true); - } - - - //DatabaseUtils.CopyDatabaseToSdCard(this); - - /* - ((NewsReaderListFragment) getSupportFragmentManager() - .findFragmentById(R.id.newsreader_list)).setUpdateFinishedListener(updateFinished); - */ - - /* - AppUpdater au = new AppUpdater(this, false); - au.UpdateApp(); - */ - - /* - // compute your public key and store it in base64EncodedPublicKey - mHelper = new IabHelper(this, Constants.getBase64EncodedPublicKey()); - mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { - public void onIabSetupFinished(IabResult result) { - if (!result.isSuccess()) { - // Oh noes, there was a problem. - Log.d(TAG, "Problem setting up In-app Billing: " + result); - } - } - }); - */ - - //Init config --> if nothing is configured start the login dialog. - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this); - if(mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, null) == null) - StartLoginFragment(); - - //if(mPrefs.getBoolean(SettingsActivity.CB_SYNCONSTARTUP_STRING, false)) - // startSync(); - - } - - - - @Override - protected void onResume() { - ThemeChooser.chooseTheme(this); - - NewsReaderListFragment nlf = ((NewsReaderListFragment) getSupportFragmentManager().findFragmentById(R.id.newsreader_list)); - if(nlf != null) - nlf.lvAdapter.notifyDataSetChanged(); - super.onResume(); - } - - @Override - public void onDestroy() { - //this.unregisterReceiver() - super.onDestroy(); - /* - try - { - if (mHelper != null) - mHelper.dispose(); - mHelper = null; - } - catch(Exception ex) - { - ex.printStackTrace(); - }*/ - } - - - /** - * Callback method from {@link NewsReaderListFragment.Callbacks} indicating - * that the item with the given ID was selected. - */ - @Override - public void onTopItemClicked(String idSubscription, boolean isFolder, String optional_folder_id) { - StartDetailFragment(idSubscription, isFolder, optional_folder_id); - } - - @Override - public void onChildItemClicked(String idSubscription, String optional_folder_id) { - StartDetailFragment(idSubscription, false, optional_folder_id); - } - - private void StartDetailFragment(String id, Boolean folder, String optional_folder_id) - { - if(super.getMenuItemMarkAllAsRead() != null) - super.getMenuItemMarkAllAsRead().setEnabled(true); - if(super.getMenuItemDownloadMoreItems() != null) - super.getMenuItemDownloadMoreItems().setEnabled(true); - - DatabaseConnection dbConn = new DatabaseConnection(getApplicationContext()); - - Intent detailIntent = new Intent(this, NewsReaderDetailActivity.class); - //detailIntent.putExtra(NewsReaderDetailFragment.ARG_ITEM_ID, id); - if(!folder) - { - detailIntent.putExtra(NewsReaderDetailActivity.SUBSCRIPTION_ID, id); - detailIntent.putExtra(NewsReaderDetailActivity.FOLDER_ID, optional_folder_id); - detailIntent.putExtra(NewsReaderDetailActivity.TITEL, dbConn.getTitleOfSubscriptionByRowID(id)); - } - else - { - detailIntent.putExtra(NewsReaderDetailActivity.FOLDER_ID, id); - int idFolder = Integer.valueOf(id); - if(idFolder >= 0) - detailIntent.putExtra(NewsReaderDetailActivity.TITEL, dbConn.getTitleOfFolderByID(id)); - else if(idFolder == -10) - detailIntent.putExtra(NewsReaderDetailActivity.TITEL, getString(R.string.allUnreadFeeds)); - else if(idFolder == -11) - detailIntent.putExtra(NewsReaderDetailActivity.TITEL, getString(R.string.starredFeeds)); - } - - - if (mTwoPane) { - // In two-pane mode, show the detail view in this activity by - // adding or replacing the detail fragment using a - // fragment transaction. - Bundle arguments = detailIntent.getExtras(); - - //arguments.putString(NewsReaderDetailFragment.ARG_ITEM_ID, id); - - //getApplicationContext().startActivity(detailIntent); - - NewsReaderDetailFragment fragment = new NewsReaderDetailFragment(); - fragment.setArguments(arguments); - getSupportFragmentManager().beginTransaction() - .replace(R.id.newsreader_detail_container, fragment) - .commit(); - - } else { - // In single-pane mode, simply start the detail activity - // for the selected item ID. - startActivity(detailIntent); - } - - dbConn.closeDatabase(); - } - - - public void UpdateItemList()//Only in use on Tablets - { - if(mTwoPane) - { - NewsReaderDetailFragment nrD = (NewsReaderDetailFragment) getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container); - if(nrD != null) - nrD.UpdateCursor(); - } - } - - - void startSync() - { - //menuItemUpdater.setActionView(R.layout.inderterminate_progress); - ((NewsReaderListFragment) getSupportFragmentManager().findFragmentById(R.id.newsreader_list)).StartSync(); - } - - @SuppressWarnings("static-access") - public void UpdateButtonSyncLayout() - { - if(super.getMenuItemUpdater() != null) - { - IReader _Reader = ((NewsReaderListFragment) getSupportFragmentManager().findFragmentById(R.id.newsreader_list))._Reader; - PullToRefreshExpandableListView pullToRefreshView = (PullToRefreshExpandableListView) findViewById(R.id.expandableListView); - if(_Reader.isSyncRunning()) - { - super.getMenuItemUpdater().setActionView(R.layout.inderterminate_progress); - if(pullToRefreshView != null) - pullToRefreshView.setRefreshing(true); - - } - else - { - super.getMenuItemUpdater().setActionView(null); - if(pullToRefreshView != null) - pullToRefreshView.onRefreshComplete(); - } - } - } - - - @Override - public boolean onCreateOptionsMenu(Menu menu) { - // Inflate the menu; this adds items to the action bar if it is present. - //getMenuInflater().inflate(R.menu.news_reader, menu); - //getSupportMenuInflater().inflate(R.menu.news_reader, menu); - - super.onCreateOptionsMenu(menu, getSupportMenuInflater(), mTwoPane, this); - - UpdateButtonSyncLayout(); - - return true; - } - - @Override - public boolean onOptionsItemSelected(MenuItem item) { - boolean handled = super.onOptionsItemSelected(item, this); - if(!handled) - { - switch (item.getItemId()) { - case R.id.action_settings: - Intent intent = new Intent(this, SettingsActivity.class); - //intent.putExtra(EXTRA_MESSAGE, message); - startActivityForResult(intent, RESULT_SETTINGS); - return true; - - case R.id.menu_update: - //menuItemUpdater = item.setActionView(R.layout.inderterminate_progress); - startSync(); - break; - - case R.id.action_login: - StartLoginFragment(); - break; - - case R.id.menu_StartImageCaching: - DatabaseConnection dbConn = new DatabaseConnection(this); - try { - long highestItemId = dbConn.getLowestItemIdUnread(); - Intent service = new Intent(this, DownloadImagesService.class); - service.putExtra(DownloadImagesService.LAST_ITEM_ID, highestItemId); - startService(service); - } finally { - dbConn.closeDatabase(); - } - break; - } - } - return super.onOptionsItemSelected(item); - } - - private static final int RESULT_SETTINGS = 15642; - - - @Override - protected void onActivityResult(int requestCode, int resultCode, Intent data) { - //if (requestCode == 1) { - if(resultCode == RESULT_OK){ - int pos = data.getIntExtra("POS", 0); - NewsReaderDetailActivity.UpdateListViewAndScrollToPos(this, pos); - - ((NewsReaderListFragment) getSupportFragmentManager().findFragmentById(R.id.newsreader_list)).lvAdapter.notifyDataSetChanged(); - } - else if(requestCode == RESULT_SETTINGS) - { - ((NewsReaderListFragment) getSupportFragmentManager().findFragmentById(R.id.newsreader_list)).lvAdapter.ReloadAdapter(); - } - } - - - public void StartLoginFragment() - { - SherlockDialogFragment dialog = new LoginDialogFragment(); - dialog.show(getSupportFragmentManager(), "NoticeDialogFragment"); - } - - /* - AsyncUpdateFinished updateFinished = new AsyncUpdateFinished() { - - @Override - public void FinishedUpdate() { - menuItemUpdater.setActionView(null); - } - };*/ -} +package de.luhmer.owncloudnewsreader; + +import android.content.Intent; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.PreferenceManager; + +import com.actionbarsherlock.app.SherlockDialogFragment; +import com.actionbarsherlock.view.Menu; +import com.actionbarsherlock.view.MenuItem; +import com.handmark.pulltorefresh.library.BlockingExpandableListView; +import com.handmark.pulltorefresh.library.PullToRefreshExpandableListView; + +import de.luhmer.owncloudnewsreader.database.DatabaseConnection; +import de.luhmer.owncloudnewsreader.helper.MenuUtilsSherlockFragmentActivity; +import de.luhmer.owncloudnewsreader.helper.ThemeChooser; +import de.luhmer.owncloudnewsreader.reader.IReader; +import de.luhmer.owncloudnewsreader.services.DownloadImagesService; + +/** + * An activity representing a list of NewsReader. This activity has different + * presentations for handset and tablet-size devices. On handsets, the activity + * presents a list of items, which when touched, lead to a + * {@link NewsReaderDetailActivity} representing item details. On tablets, the + * activity presents the list of items and item details side-by-side using two + * vertical panes. + *

+ * The activity makes heavy use of fragments. The list of items is a + * {@link NewsReaderListFragment} and the item details (if present) is a + * {@link NewsReaderDetailFragment}. + *

+ * This activity also implements the required + * {@link NewsReaderListFragment.Callbacks} interface to listen for item + * selections. + */ +public class NewsReaderListActivity extends MenuUtilsSherlockFragmentActivity implements + NewsReaderListFragment.Callbacks { + + /** + * Whether or not the activity is in two-pane mode, i.e. running on a tablet + * device. + */ + private boolean mTwoPane; + //IabHelper mHelper; + static final String TAG = "NewsReaderListActivity"; + + @Override + protected void onCreate(Bundle savedInstanceState) { + + ThemeChooser.chooseTheme(this); + + //setTheme(R.style.Theme_Sherlock); + + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_newsreader_list); + + + if (findViewById(R.id.newsreader_detail_container) != null) { + // The detail container view will be present only in the + // large-screen layouts (res/values-large and + // res/values-sw600dp). If this view is present, then the + // activity should be in two-pane mode. + mTwoPane = true; + + // In two-pane mode, list items should be given the + // 'activated' state when touched. + + ((NewsReaderListFragment) getSupportFragmentManager() + .findFragmentById(R.id.newsreader_list)) + .setActivateOnItemClick(true); + } + + + //DatabaseUtils.CopyDatabaseToSdCard(this); + + /* + ((NewsReaderListFragment) getSupportFragmentManager() + .findFragmentById(R.id.newsreader_list)).setUpdateFinishedListener(updateFinished); + */ + + /* + AppUpdater au = new AppUpdater(this, false); + au.UpdateApp(); + */ + + /* + // compute your public key and store it in base64EncodedPublicKey + mHelper = new IabHelper(this, Constants.getBase64EncodedPublicKey()); + mHelper.startSetup(new IabHelper.OnIabSetupFinishedListener() { + public void onIabSetupFinished(IabResult result) { + if (!result.isSuccess()) { + // Oh noes, there was a problem. + Log.d(TAG, "Problem setting up In-app Billing: " + result); + } + } + }); + */ + + //Init config --> if nothing is configured start the login dialog. + SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(this); + if(mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, null) == null) + StartLoginFragment(); + + //if(mPrefs.getBoolean(SettingsActivity.CB_SYNCONSTARTUP_STRING, false)) + // startSync(); + + } + + public void updateAdapter() { + NewsReaderListFragment nlf = ((NewsReaderListFragment) getSupportFragmentManager().findFragmentById(R.id.newsreader_list)); + if(nlf != null) + { + // Block children layout for now + PullToRefreshExpandableListView ptrel = ((PullToRefreshExpandableListView)nlf.eListView); + BlockingExpandableListView bView = ((BlockingExpandableListView) ptrel.getRefreshableView()); + bView.setBlockLayoutChildren(true); + nlf.lvAdapter.notifyDataSetChanged(); + bView.setBlockLayoutChildren(false); + } + } + + @Override + protected void onResume() { + ThemeChooser.chooseTheme(this); + + updateAdapter(); + + super.onResume(); + } + + @Override + public void onDestroy() { + //this.unregisterReceiver() + super.onDestroy(); + /* + try + { + if (mHelper != null) + mHelper.dispose(); + mHelper = null; + } + catch(Exception ex) + { + ex.printStackTrace(); + }*/ + } + + + /** + * Callback method from {@link NewsReaderListFragment.Callbacks} indicating + * that the item with the given ID was selected. + */ + @Override + public void onTopItemClicked(String idSubscription, boolean isFolder, String optional_folder_id) { + StartDetailFragment(idSubscription, isFolder, optional_folder_id); + } + + @Override + public void onChildItemClicked(String idSubscription, String optional_folder_id) { + StartDetailFragment(idSubscription, false, optional_folder_id); + } + + private void StartDetailFragment(String id, Boolean folder, String optional_folder_id) + { + if(super.getMenuItemMarkAllAsRead() != null) + super.getMenuItemMarkAllAsRead().setEnabled(true); + if(super.getMenuItemDownloadMoreItems() != null) + super.getMenuItemDownloadMoreItems().setEnabled(true); + + DatabaseConnection dbConn = new DatabaseConnection(getApplicationContext()); + + Intent detailIntent = new Intent(this, NewsReaderDetailActivity.class); + //detailIntent.putExtra(NewsReaderDetailFragment.ARG_ITEM_ID, id); + if(!folder) + { + detailIntent.putExtra(NewsReaderDetailActivity.SUBSCRIPTION_ID, id); + detailIntent.putExtra(NewsReaderDetailActivity.FOLDER_ID, optional_folder_id); + detailIntent.putExtra(NewsReaderDetailActivity.TITEL, dbConn.getTitleOfSubscriptionByRowID(id)); + } + else + { + detailIntent.putExtra(NewsReaderDetailActivity.FOLDER_ID, id); + int idFolder = Integer.valueOf(id); + if(idFolder >= 0) + detailIntent.putExtra(NewsReaderDetailActivity.TITEL, dbConn.getTitleOfFolderByID(id)); + else if(idFolder == -10) + detailIntent.putExtra(NewsReaderDetailActivity.TITEL, getString(R.string.allUnreadFeeds)); + else if(idFolder == -11) + detailIntent.putExtra(NewsReaderDetailActivity.TITEL, getString(R.string.starredFeeds)); + } + + + if (mTwoPane) { + // In two-pane mode, show the detail view in this activity by + // adding or replacing the detail fragment using a + // fragment transaction. + Bundle arguments = detailIntent.getExtras(); + + //arguments.putString(NewsReaderDetailFragment.ARG_ITEM_ID, id); + + //getApplicationContext().startActivity(detailIntent); + + NewsReaderDetailFragment fragment = new NewsReaderDetailFragment(); + fragment.setArguments(arguments); + getSupportFragmentManager().beginTransaction() + .replace(R.id.newsreader_detail_container, fragment) + .commit(); + + } else { + // In single-pane mode, simply start the detail activity + // for the selected item ID. + startActivity(detailIntent); + } + + dbConn.closeDatabase(); + } + + + public void UpdateItemList()//Only in use on Tablets + { + if(mTwoPane) + { + NewsReaderDetailFragment nrD = (NewsReaderDetailFragment) getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container); + if(nrD != null) + nrD.UpdateCursor(); + } + } + + + void startSync() + { + //menuItemUpdater.setActionView(R.layout.inderterminate_progress); + ((NewsReaderListFragment) getSupportFragmentManager().findFragmentById(R.id.newsreader_list)).StartSync(); + } + + @SuppressWarnings("static-access") + public void UpdateButtonSyncLayout() + { + if(super.getMenuItemUpdater() != null) + { + IReader _Reader = ((NewsReaderListFragment) getSupportFragmentManager().findFragmentById(R.id.newsreader_list))._Reader; + PullToRefreshExpandableListView pullToRefreshView = (PullToRefreshExpandableListView) findViewById(R.id.expandableListView); + if(_Reader.isSyncRunning()) + { + super.getMenuItemUpdater().setActionView(R.layout.inderterminate_progress); + if(pullToRefreshView != null) + pullToRefreshView.setRefreshing(true); + + } + else + { + super.getMenuItemUpdater().setActionView(null); + if(pullToRefreshView != null) + pullToRefreshView.onRefreshComplete(); + } + } + } + + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + //getMenuInflater().inflate(R.menu.news_reader, menu); + //getSupportMenuInflater().inflate(R.menu.news_reader, menu); + + super.onCreateOptionsMenu(menu, getSupportMenuInflater(), mTwoPane, this); + + UpdateButtonSyncLayout(); + + return true; + } + + @Override + public boolean onOptionsItemSelected(MenuItem item) { + boolean handled = super.onOptionsItemSelected(item, this); + if(!handled) + { + switch (item.getItemId()) { + case R.id.action_settings: + Intent intent = new Intent(this, SettingsActivity.class); + //intent.putExtra(EXTRA_MESSAGE, message); + startActivityForResult(intent, RESULT_SETTINGS); + return true; + + case R.id.menu_update: + //menuItemUpdater = item.setActionView(R.layout.inderterminate_progress); + startSync(); + break; + + case R.id.action_login: + StartLoginFragment(); + break; + + case R.id.menu_StartImageCaching: + DatabaseConnection dbConn = new DatabaseConnection(this); + try { + long highestItemId = dbConn.getLowestItemIdUnread(); + Intent service = new Intent(this, DownloadImagesService.class); + service.putExtra(DownloadImagesService.LAST_ITEM_ID, highestItemId); + startService(service); + } finally { + dbConn.closeDatabase(); + } + break; + } + } + return super.onOptionsItemSelected(item); + } + + private static final int RESULT_SETTINGS = 15642; + + + @Override + protected void onActivityResult(int requestCode, int resultCode, Intent data) { + //if (requestCode == 1) { + if(resultCode == RESULT_OK){ + int pos = data.getIntExtra("POS", 0); + NewsReaderDetailActivity.UpdateListViewAndScrollToPos(this, pos); + + ((NewsReaderListFragment) getSupportFragmentManager().findFragmentById(R.id.newsreader_list)).lvAdapter.notifyDataSetChanged(); + } + else if(requestCode == RESULT_SETTINGS) + { + ((NewsReaderListFragment) getSupportFragmentManager().findFragmentById(R.id.newsreader_list)).lvAdapter.ReloadAdapter(); + } + } + + + public void StartLoginFragment() + { + SherlockDialogFragment dialog = new LoginDialogFragment(); + dialog.show(getSupportFragmentManager(), "NoticeDialogFragment"); + } +} diff --git a/src/de/luhmer/owncloudnewsreader/NewsReaderListFragment.java b/src/de/luhmer/owncloudnewsreader/NewsReaderListFragment.java index 3b3e4f9c..5d4c007a 100644 --- a/src/de/luhmer/owncloudnewsreader/NewsReaderListFragment.java +++ b/src/de/luhmer/owncloudnewsreader/NewsReaderListFragment.java @@ -1,589 +1,590 @@ -package de.luhmer.owncloudnewsreader; - -import java.util.List; - -import org.apache.http.client.HttpResponseException; -import org.apache.http.conn.HttpHostConnectException; - -import android.app.Activity; -import android.content.Context; -import android.content.SharedPreferences; -import android.os.Bundle; -import android.preference.PreferenceManager; -import android.util.Log; -import android.view.LayoutInflater; -import android.view.View; -import android.view.View.OnCreateContextMenuListener; -import android.view.ViewGroup; -import android.view.ViewGroup.LayoutParams; -import android.widget.ExpandableListView; -import android.widget.ExpandableListView.OnChildClickListener; -import android.widget.ListView; -import android.widget.Toast; - -import com.actionbarsherlock.app.SherlockFragment; -import com.handmark.pulltorefresh.library.PullToRefreshBase; -import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; -import com.handmark.pulltorefresh.library.PullToRefreshExpandableListView; - -import de.luhmer.owncloudnewsreader.ListView.SubscriptionExpandableListAdapter; -import de.luhmer.owncloudnewsreader.data.FolderSubscribtionItem; -import de.luhmer.owncloudnewsreader.database.DatabaseConnection; -import de.luhmer.owncloudnewsreader.interfaces.ExpListTextClicked; -import de.luhmer.owncloudnewsreader.reader.FeedItemTags.TAGS; -import de.luhmer.owncloudnewsreader.reader.IReader; -import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; -import de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloud_Reader; - -/** - * A list fragment representing a list of NewsReader. This fragment also - * supports tablet devices by allowing list items to be given an 'activated' - * state upon selection. This helps indicate which item is currently being - * viewed in a {@link NewsReaderDetailFragment}. - *

- * Activities containing this fragment MUST implement the {@link Callbacks} - * interface. - */ -public class NewsReaderListFragment extends SherlockFragment implements OnCreateContextMenuListener /*, - ExpandableListView.OnChildClickListener, - ExpandableListView.OnGroupCollapseListener, - ExpandableListView.OnGroupExpandListener*/ { - - - - /** - * The serialization (saved instance state) Bundle key representing the - * activated item position. Only used on tablets. - */ - private static final String STATE_ACTIVATED_POSITION = "activated_position"; - - protected static final String TAG = "NewsReaderListFragment"; - - /** - * The fragment's current callback object, which is notified of list item - * clicks. - */ - private Callbacks mCallbacks = sExpListCallbacks; - - /** - * The current activated item position. Only used on tablets. - */ - private int mActivatedPosition = ListView.INVALID_POSITION; - - /** - * A callback interface that all activities containing this fragment must - * implement. This mechanism allows activities to be notified of item - * selections. - */ - public interface Callbacks { - /** - * Callback for when an item has been selected. - */ - public void onChildItemClicked(String idSubscription, String optional_folder_id); - public void onTopItemClicked(String idSubscription, boolean isFolder, String optional_folder_id); - } - - /** - * A dummy implementation of the {@link Callbacks} interface that does - * nothing. Used only when this fragment is not attached to an activity. - */ - private static Callbacks sExpListCallbacks = new Callbacks() { - @Override - public void onChildItemClicked(String idSubscription, String optional_folder_id) { - } - - @Override - public void onTopItemClicked(String idSubscription, boolean isFolder, String optional_folder_id) { - } - }; - - DatabaseConnection dbConn; - //SubscriptionExpandableListAdapter lvAdapter; - SubscriptionExpandableListAdapter lvAdapter; - //ExpandableListView eListView; - PullToRefreshExpandableListView eListView; - public static IReader _Reader = null; //AsyncTask_GetGReaderTags asyncTask_GetUnreadFeeds = null; - - public static String username; - public static String password; - //AsyncUpdateFinished asyncUpdateFinished; - - /** - * Mandatory empty constructor for the fragment manager to instantiate the - * fragment (e.g. upon screen orientation changes). - */ - public NewsReaderListFragment() { - } - - @Override - public void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - - setRetainInstance(true); - - try - { - dbConn = new DatabaseConnection(getActivity()); - - /* - //Update Database Stuff first - try { - PackageInfo pInfo = getActivity().getPackageManager().getPackageInfo(getActivity().getPackageName(), 0); - - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); - if(mPrefs.getInt("LAST_APP_VERSION", 0) < pInfo.versionCode) - { - dbConn.resetDatabase(); - SharedPreferences.Editor editor = mPrefs.edit(); - editor.putInt("LAST_APP_VERSION", pInfo.versionCode); - editor.commit(); - } - } catch (Exception e) { - e.printStackTrace(); - } - - */ - - - /* - String val = String.valueOf(dbConn.getLongValueBySQL("SELECT COUNT(*) FROM " + - DatabaseConnection.RSS_ITEM_TABLE + - " WHERE " + DatabaseConnection.RSS_ITEM_STARRED_TEMP + " != " + DatabaseConnection.RSS_ITEM_STARRED - )); - Toast.makeText(getActivity(), val, Toast.LENGTH_LONG).show(); - */ - - //dbConn.resetDatabase(); - - //dbConn.clearDatabaseOverSize(); - - username = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).getString("edt_username", ""); - password = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).getString("edt_password", ""); - - //dbConn.resetRssItemsDatabase(); - - lvAdapter = new SubscriptionExpandableListAdapter(getActivity(), dbConn); - lvAdapter.setHandlerListener(expListTextClickedListener); - - if(_Reader == null) - _Reader = new OwnCloud_Reader(); - - - //((NewsReaderListActivity) getActivity()).startSync(); - - //_Reader.Start_AsyncTask_GetFeeds(2, getActivity(), null); - - - /* - new AsyncTask_GetGReaderTags(1, getActivity(), onAsyncTask_GetTopReaderTags).execute(username, password); - new AsyncTask_GetSubReaderTags(1, getActivity(), onAsyncTask_GetSubReaderTags).execute(username, password);*/ - - - } - catch(Exception ex) - { - ex.printStackTrace(); - } - } - - - - public void StartSync() - { - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); - if(mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, null) == null) - { - NewsReaderListActivity nla = (NewsReaderListActivity) getActivity(); - nla.StartLoginFragment(); - - } else { - if (!_Reader.isSyncRunning()) - { - DatabaseConnection dbConn = new DatabaseConnection(getActivity()); - try { - //Mark as READ - List item_ids = dbConn.getAllNewReadItems(); - _Reader.Start_AsyncTask_PerformTagAction(-4, getActivity(), onAsyncTask_PerformTagExecute, item_ids, TAGS.MARK_ITEM_AS_READ); - - //Mark as UNREAD - item_ids = dbConn.getAllNewUnreadItems(); - _Reader.Start_AsyncTask_PerformTagAction(-3, getActivity(), onAsyncTask_PerformTagExecute, item_ids, TAGS.MARK_ITEM_AS_UNREAD); - - //Mark as STARRED - item_ids = dbConn.getAllNewStarredItems(); - _Reader.Start_AsyncTask_PerformTagAction(-2, getActivity(), onAsyncTask_PerformTagExecute, item_ids, TAGS.MARK_ITEM_AS_STARRED); - - //Mark as UNSTARRED - item_ids = dbConn.getAllNewUnstarredItems(); - _Reader.Start_AsyncTask_PerformTagAction(-1, getActivity(), onAsyncTask_PerformTagExecute, item_ids, TAGS.MARK_ITEM_AS_UNSTARRED); - } finally { - dbConn.closeDatabase(); - } - - if(eListView != null) - eListView.getLoadingLayoutProxy().setLastUpdatedLabel(getString(R.string.pull_to_refresh_updateTags)); - //_Reader.Start_AsyncTask_GetFolder(0, getActivity(), onAsyncTask_GetTopReaderTags); - } - else - //_Reader.attachToRunningTask(0, getActivity(), onAsyncTask_GetTopReaderTags); - _Reader.attachToRunningTask(-1, getActivity(), onAsyncTask_PerformTagExecute); - } - - UpdateSyncButtonLayout(); - } - - OnAsyncTaskCompletedListener onAsyncTask_PerformTagExecute = new OnAsyncTaskCompletedListener() { - @Override - public void onAsyncTaskCompleted(int task_id, Object task_result) { - if(task_result != null)//task result is null if there was an error - { - if((Boolean) task_result) - { - //dbConn.resetDatabase(); - - if(task_id == -1) - { - _Reader.Start_AsyncTask_GetFolder(1, getActivity(), onAsyncTask_GetTopReaderTags); - if(eListView != null) - eListView.getLoadingLayoutProxy().setLastUpdatedLabel(getString(R.string.pull_to_refresh_updateFolder)); - } - else - _Reader.setSyncRunning(true); - } - else - UpdateSyncButtonLayout(); - } - else - UpdateSyncButtonLayout(); - } - }; - - OnAsyncTaskCompletedListener onAsyncTask_GetTopReaderTags = new OnAsyncTaskCompletedListener() { - - - @Override - public void onAsyncTaskCompleted(int task_id, Object task_result) { - Log.d(TAG, "onAsyncTask_GetTopReaderTags started: " + task_id); - - if(task_result != null) - { - if(task_result instanceof HttpHostConnectException) - ShowToastLong("Cannot connect to the Host !"); - else if(task_result instanceof HttpResponseException) - { - HttpResponseException responseException = (HttpResponseException) task_result; - //if(responseException.getStatusCode() == 401) - // ShowToastLong("Authentication failed"); - //else - ShowToastLong(responseException.getLocalizedMessage()); - } - else - ShowToastLong(((Exception)task_result).getLocalizedMessage()); - - UpdateSyncButtonLayout(); - } - else - { - _Reader.Start_AsyncTask_GetFeeds(1, getActivity(), onAsyncTask_GetSubReaderTags); - if(eListView != null) - eListView.getLoadingLayoutProxy().setLastUpdatedLabel(getString(R.string.pull_to_refresh_updateFeeds)); - } - - lvAdapter.notifyDataSetChanged(); - Log.d(TAG, "onAsyncTask_GetTopReaderTags Finished"); - } - }; - - public void ShowToastLong(String message) - { - Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); - } - - OnAsyncTaskCompletedListener onAsyncTask_GetSubReaderTags = new OnAsyncTaskCompletedListener() { - - @Override - public void onAsyncTaskCompleted(int task_id, Object task_result) { - - Log.d(TAG, "onAsyncTask_GetSubReaderTags Finished"); - - if(task_result != null) - { - ShowToastLong(((Exception)task_result).getLocalizedMessage()); - UpdateSyncButtonLayout(); - } - else - { - //dbConn.resetRssItemsDatabase(); - - _Reader.Start_AsyncTask_GetItems(2, getActivity(), onAsyncTask_GetFeeds, TAGS.ALL);//Recieve all unread Items - //_Reader.Start_AsyncTask_GetFeeds(3, getActivity(), onAsyncTask_GetFeeds, TAGS.ALL_STARRED);//Recieve all starred Items - - if(eListView != null) - eListView.getLoadingLayoutProxy().setLastUpdatedLabel(getString(R.string.pull_to_refresh_updateItems)); - } - - - - lvAdapter.ReloadAdapter(); - //lvAdapter.notifyDataSetChanged(); - //eListView.setAdapter(new SubscriptionExpandableListAdapter(getActivity(), dbConn)); - - //new AsyncTask_GetFeeds(0, getActivity(), onAsyncTask_GetFeeds).execute(username, password, Constants._TAG_LABEL_UNREAD); - //new AsyncTask_GetFeeds(0, getActivity(), onAsyncTask_GetFeeds).execute(username, password, Constants._TAG_LABEL_STARRED); - } - }; - - OnAsyncTaskCompletedListener onAsyncTask_GetFeeds = new OnAsyncTaskCompletedListener() { - - @Override - public void onAsyncTaskCompleted(int task_id, Object task_result) { - - if(task_result != null) - ShowToastLong(((Exception)task_result).getLocalizedMessage()); - - lvAdapter.notifyDataSetChanged(); - //Activity act = getActivity(); - //lvAdapter = new SubscriptionExpandableListAdapter(act, dbConn); - - Log.d(TAG, "onAsyncTask_GetFeeds Finished"); - - if(eListView != null) - eListView.getLoadingLayoutProxy().setLastUpdatedLabel(null); - - UpdateSyncButtonLayout(); - - lvAdapter.ReloadAdapter(); - - NewsReaderListActivity nlActivity = (NewsReaderListActivity) getActivity(); - nlActivity.UpdateItemList(); - - //fireUpdateFinishedClicked(); - } - }; - - - @Override - public View onCreateView(LayoutInflater inflater, ViewGroup container, - Bundle savedInstanceState) { - View V = null; - try - { - V = inflater.inflate(R.layout.expandable_list_layout, container, false); - //eListView = (ExpandableListView) V.findViewById(R.id.expandableListView); - eListView = (PullToRefreshExpandableListView) V.findViewById(R.id.expandableListView); - - - //eListView.setGroupIndicator(getResources().getDrawable(R.drawable.expandable_group_indicator)); - eListView.setGroupIndicator(null); - - //eListView.demo(); - eListView.setShowIndicator(false); - - eListView.setOnRefreshListener(new OnRefreshListener() { - @Override - public void onRefresh(PullToRefreshBase refreshView) { - StartSync(); - } - }); - - eListView.setOnChildClickListener(onChildClickListener); - //eListView.setSmoothScrollbarEnabled(true); - - View empty = inflater.inflate(R.layout.subscription_list_item_empty, null, false); - getActivity().addContentView(empty, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); - eListView.setEmptyView(empty); - /* - eListView.setClickable(true); - eListView.setOnGroupClickListener(new OnGroupClickListener() { - - @Override - public boolean onGroupClick(ExpandableListView parent, View v, - int groupPosition, long id) { - Log.d("hi", String.valueOf(groupPosition)); - //return false; - return true; - } - });*/ - eListView.setExpandableAdapter(lvAdapter); - - - //Start auto sync if enabled - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); - if(mPrefs.getBoolean(SettingsActivity.CB_SYNCONSTARTUP_STRING, false)) - StartSync(); - - } - catch(Exception ex) - { - ex.printStackTrace(); - } - - return V; - //return super.onCreateView(inflater, container, savedInstanceState); - } - - @Override - public void onViewCreated(View view, Bundle savedInstanceState) { - super.onViewCreated(view, savedInstanceState); - - - // Restore the previously serialized activated item position. - if (savedInstanceState != null - && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) { - setActivatedPosition(savedInstanceState - .getInt(STATE_ACTIVATED_POSITION)); - } - } - - @Override - public void onAttach(Activity activity) { - super.onAttach(activity); - - // Activities containing this fragment must implement its callbacks. - if (!(activity instanceof Callbacks)) { - throw new IllegalStateException( - "Activity must implement fragment's callbacks."); - } - - mCallbacks = (Callbacks) activity; - } - - @Override - public void onDetach() { - super.onDetach(); - - // Reset the active callbacks interface to the dummy implementation. - mCallbacks = sExpListCallbacks; - } - - ExpListTextClicked expListTextClickedListener = new ExpListTextClicked() { - - @Override - public void onTextClicked(String idSubscription, Context context, boolean isFolder, String optional_folder_id) { - mCallbacks.onTopItemClicked(idSubscription, isFolder, optional_folder_id); - } - }; - - /* - @Override - public void onListItemClick(ListView listView, View view, int position, - long id) { - super.onListItemClick(listView, view, position, id); - - // Notify the active callbacks interface (the activity, if the - // fragment is attached to one) that an item has been selected. - - //mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id); - }*/ - - @Override - public void onSaveInstanceState(Bundle outState) { - super.onSaveInstanceState(outState); - if (mActivatedPosition != ListView.INVALID_POSITION) { - // Serialize and persist the activated item position. - outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); - } - } - - OnChildClickListener onChildClickListener = new OnChildClickListener() { - - @Override - public boolean onChildClick(ExpandableListView parent, View v, - int groupPosition, int childPosition, long id) { - - long idItem = lvAdapter.getChildId(groupPosition, childPosition); - - String optional_id_folder = null; - FolderSubscribtionItem groupItem = (FolderSubscribtionItem) lvAdapter.getGroup(groupPosition); - if(groupItem != null) - optional_id_folder = String.valueOf(groupItem.id_database); - - mCallbacks.onChildItemClicked(String.valueOf(idItem), optional_id_folder); - - return false; - } - }; - - /** - * Turns on activate-on-click mode. When this mode is on, list items will be - * given the 'activated' state when touched. - */ - public void setActivateOnItemClick(boolean activateOnItemClick) { - // When setting CHOICE_MODE_SINGLE, ListView will automatically - // give items the 'activated' state when touched. - - - //eListView.setChoiceMode(activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE);//TODO comment this in - } - - private void setActivatedPosition(int position) {/*//TODO comment this in - if (position == ListView.INVALID_POSITION) { - //getListView().setItemChecked(mActivatedPosition, false); - eListView.setItemChecked(mActivatedPosition, false); - } else { - eListView.setItemChecked(position, true); - //getListView().setItemChecked(position, true); - }*/ - - mActivatedPosition = position; - } - - - public void UpdateSyncButtonLayout() - { - if(getActivity() != null) - ((NewsReaderListActivity) getActivity()).UpdateButtonSyncLayout(); - } - - /* - public void setUpdateFinishedListener(AsyncUpdateFinished listener) - { - asyncUpdateFinished = listener; - } - protected void fireUpdateFinishedClicked() - { - if(asyncUpdateFinished != null) - asyncUpdateFinished.FinishedUpdate(); - }*/ -} - - -/* - dbConn.insertNewSubscription("Ungelesene Artikel"); - dbConn.insertNewSubscription("Markierte Artikel"); - dbConn.insertNewSubscription("Android"); - dbConn.insertNewSubscription("Apple"); - dbConn.insertNewSubscription("Bugtracker"); - dbConn.insertNewSubscription("Development"); - dbConn.insertNewSubscription("Linux"); - dbConn.insertNewSubscription("Software"); - dbConn.insertNewSubscription("Owncloud"); - dbConn.insertNewSubscription("Other"); - - dbConn.insertNewSub_Subscription("4droid", dbConn.getIdOfSubscription("Android")); - dbConn.insertNewSub_Subscription("GIGA Rss Feed", dbConn.getIdOfSubscription("Android")); - - dbConn.insertNewSub_Subscription("macnews.de", dbConn.getIdOfSubscription("Apple")); - dbConn.insertNewSub_Subscription("MACNOTES.DE", dbConn.getIdOfSubscription("Apple")); - - dbConn.insertNewSub_Subscription("FS Bugtracker", dbConn.getIdOfSubscription("Bugtracker")); - - dbConn.insertNewSub_Subscription("Code 2 Learn", dbConn.getIdOfSubscription("Development")); - dbConn.insertNewSub_Subscription("Coding Horror", dbConn.getIdOfSubscription("Development")); - - dbConn.insertNewSub_Subscription("Canoncial", dbConn.getIdOfSubscription("Linux")); - - dbConn.insertNewSub_Subscription("iTek Zone", dbConn.getIdOfSubscription("Software")); - - dbConn.insertNewSub_Subscription("CNET", dbConn.getIdOfSubscription("Other")); - - dbConn.insertNewSub_Subscription("ownCloud.org", dbConn.getIdOfSubscription("Owncloud")); - - dbConn.insertNewFeed("Samsung Game Pad pops up on Galaxy S4 site, outs Note 3?", - "http://news.cnet.com/8301-17938_105-57574766-1/samsung-game-pad-pops-up-on-galaxy-s4-site-outs-note-3/?part\u003drss\u0026subj\u003dnews\u0026tag\u003d2547-1_3-0-20", - "The gaming controller works with devices up to 6.3 inches, perhaps suggesting Samsung is planning a bigger phablet, or should we be calling it a \"tabone?\"", - "0", - dbConn.getIdOfSubscription("CNET")); - - */ - +package de.luhmer.owncloudnewsreader; + +import java.util.List; + +import org.apache.http.client.HttpResponseException; +import org.apache.http.conn.HttpHostConnectException; + +import android.app.Activity; +import android.content.Context; +import android.content.SharedPreferences; +import android.os.Bundle; +import android.preference.PreferenceManager; +import android.util.Log; +import android.view.LayoutInflater; +import android.view.View; +import android.view.View.OnCreateContextMenuListener; +import android.view.ViewGroup; +import android.view.ViewGroup.LayoutParams; +import android.widget.ExpandableListView; +import android.widget.ExpandableListView.OnChildClickListener; +import android.widget.ListView; +import android.widget.Toast; + +import com.actionbarsherlock.app.SherlockFragment; +import com.handmark.pulltorefresh.library.PullToRefreshBase; +import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener; +import com.handmark.pulltorefresh.library.PullToRefreshExpandableListView; + +import de.luhmer.owncloudnewsreader.ListView.SubscriptionExpandableListAdapter; +import de.luhmer.owncloudnewsreader.data.FolderSubscribtionItem; +import de.luhmer.owncloudnewsreader.database.DatabaseConnection; +import de.luhmer.owncloudnewsreader.interfaces.ExpListTextClicked; +import de.luhmer.owncloudnewsreader.reader.FeedItemTags.TAGS; +import de.luhmer.owncloudnewsreader.reader.IReader; +import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; +import de.luhmer.owncloudnewsreader.reader.owncloud.API; +import de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloud_Reader; +import de.luhmer.owncloudnewsreader.reader.owncloud.apiv1.APIv1; +import de.luhmer.owncloudnewsreader.reader.owncloud.apiv2.APIv2; + +/** + * A list fragment representing a list of NewsReader. This fragment also + * supports tablet devices by allowing list items to be given an 'activated' + * state upon selection. This helps indicate which item is currently being + * viewed in a {@link NewsReaderDetailFragment}. + *

+ * Activities containing this fragment MUST implement the {@link Callbacks} + * interface. + */ +public class NewsReaderListFragment extends SherlockFragment implements OnCreateContextMenuListener /*, + ExpandableListView.OnChildClickListener, + ExpandableListView.OnGroupCollapseListener, + ExpandableListView.OnGroupExpandListener*/ { + + + + /** + * The serialization (saved instance state) Bundle key representing the + * activated item position. Only used on tablets. + */ + private static final String STATE_ACTIVATED_POSITION = "activated_position"; + + protected static final String TAG = "NewsReaderListFragment"; + + /** + * The fragment's current callback object, which is notified of list item + * clicks. + */ + private Callbacks mCallbacks = sExpListCallbacks; + + /** + * The current activated item position. Only used on tablets. + */ + private int mActivatedPosition = ListView.INVALID_POSITION; + + /** + * A callback interface that all activities containing this fragment must + * implement. This mechanism allows activities to be notified of item + * selections. + */ + public interface Callbacks { + /** + * Callback for when an item has been selected. + */ + public void onChildItemClicked(String idSubscription, String optional_folder_id); + public void onTopItemClicked(String idSubscription, boolean isFolder, String optional_folder_id); + } + + /** + * A dummy implementation of the {@link Callbacks} interface that does + * nothing. Used only when this fragment is not attached to an activity. + */ + private static Callbacks sExpListCallbacks = new Callbacks() { + @Override + public void onChildItemClicked(String idSubscription, String optional_folder_id) { + } + + @Override + public void onTopItemClicked(String idSubscription, boolean isFolder, String optional_folder_id) { + } + }; + + DatabaseConnection dbConn; + //SubscriptionExpandableListAdapter lvAdapter; + SubscriptionExpandableListAdapter lvAdapter; + //ExpandableListView eListView; + PullToRefreshExpandableListView eListView; + public static IReader _Reader = null; //AsyncTask_GetGReaderTags asyncTask_GetUnreadFeeds = null; + + public static String username; + public static String password; + //AsyncUpdateFinished asyncUpdateFinished; + + /** + * Mandatory empty constructor for the fragment manager to instantiate the + * fragment (e.g. upon screen orientation changes). + */ + public NewsReaderListFragment() { + } + + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + + setRetainInstance(true); + + try + { + dbConn = new DatabaseConnection(getActivity()); + + //dbConn.resetDatabase(); + + //dbConn.clearDatabaseOverSize(); + + username = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).getString("edt_username", ""); + password = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()).getString("edt_password", ""); + + //dbConn.resetRssItemsDatabase(); + + lvAdapter = new SubscriptionExpandableListAdapter(getActivity(), dbConn); + lvAdapter.setHandlerListener(expListTextClickedListener); + + if(_Reader == null) + _Reader = new OwnCloud_Reader(); + } + catch(Exception ex) + { + ex.printStackTrace(); + } + } + + + + public void StartSync() + { + SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); + if(mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, null) == null) + { + NewsReaderListActivity nla = (NewsReaderListActivity) getActivity(); + nla.StartLoginFragment(); + + } else { + if (!_Reader.isSyncRunning()) + { + OwnCloud_Reader ocReader = (OwnCloud_Reader) _Reader; + ocReader.Start_AsyncTask_GetVersion(-10, getActivity(), onAsyncTask_GetVersionFinished, username, password); + } + else + _Reader.attachToRunningTask(-10, getActivity(), onAsyncTask_GetVersionFinished); + } + + UpdateSyncButtonLayout(); + } + + OnAsyncTaskCompletedListener onAsyncTask_GetVersionFinished = new OnAsyncTaskCompletedListener() { + + @Override + public void onAsyncTaskCompleted(int task_id, Object task_result) { + + if(!(task_result instanceof Exception)) + { + API api = null; + String appVersion = task_result.toString(); + int versionCode = 0; + if(appVersion != null) + { + appVersion = appVersion.replace(".", ""); + versionCode = Integer.parseInt(appVersion); + } + if (versionCode >= 1101) { + api = new APIv2(getActivity()); + } else { + api = new APIv1(getActivity()); + } + + ((OwnCloud_Reader) _Reader).setApi(api); + + DatabaseConnection dbConn = new DatabaseConnection(getActivity()); + try { + //Mark as READ + List item_ids = dbConn.getAllNewReadItems(); + _Reader.Start_AsyncTask_PerformTagAction(-4, getActivity(), onAsyncTask_PerformTagExecute, item_ids, TAGS.MARK_ITEM_AS_READ); + + //Mark as UNREAD + item_ids = dbConn.getAllNewUnreadItems(); + _Reader.Start_AsyncTask_PerformTagAction(-3, getActivity(), onAsyncTask_PerformTagExecute, item_ids, TAGS.MARK_ITEM_AS_UNREAD); + + //Mark as STARRED + item_ids = dbConn.getAllNewStarredItems(); + _Reader.Start_AsyncTask_PerformTagAction(-2, getActivity(), onAsyncTask_PerformTagExecute, item_ids, TAGS.MARK_ITEM_AS_STARRED); + + //Mark as UNSTARRED + item_ids = dbConn.getAllNewUnstarredItems(); + _Reader.Start_AsyncTask_PerformTagAction(-1, getActivity(), onAsyncTask_PerformTagExecute, item_ids, TAGS.MARK_ITEM_AS_UNSTARRED); + } finally { + dbConn.closeDatabase(); + } + + if(eListView != null) + eListView.getLoadingLayoutProxy().setLastUpdatedLabel(getString(R.string.pull_to_refresh_updateTags)); + //_Reader.Start_AsyncTask_GetFolder(0, getActivity(), onAsyncTask_GetTopReaderTags); + } + UpdateSyncButtonLayout(); + } + }; + + //Sync state of items e.g. read/unread/starred/unstarred + OnAsyncTaskCompletedListener onAsyncTask_PerformTagExecute = new OnAsyncTaskCompletedListener() { + @Override + public void onAsyncTaskCompleted(int task_id, Object task_result) { + if(task_result != null)//task result is null if there was an error + { + if((Boolean) task_result) + { + //dbConn.resetDatabase(); + + if(task_id == -1) + { + _Reader.Start_AsyncTask_GetFolder(1, getActivity(), onAsyncTask_GetFolder); + if(eListView != null) + eListView.getLoadingLayoutProxy().setLastUpdatedLabel(getString(R.string.pull_to_refresh_updateFolder)); + } + else + _Reader.setSyncRunning(true); + } + else + UpdateSyncButtonLayout(); + } + else + UpdateSyncButtonLayout(); + } + }; + + + OnAsyncTaskCompletedListener onAsyncTask_GetFolder = new OnAsyncTaskCompletedListener() { + + + @Override + public void onAsyncTaskCompleted(int task_id, Object task_result) { + Log.d(TAG, "onAsyncTask_GetTopReaderTags started: " + task_id); + + if(task_result != null) + { + if(task_result instanceof HttpHostConnectException) + ShowToastLong("Cannot connect to the Host !"); + else if(task_result instanceof HttpResponseException) + { + HttpResponseException responseException = (HttpResponseException) task_result; + //if(responseException.getStatusCode() == 401) + // ShowToastLong("Authentication failed"); + //else + ShowToastLong(responseException.getLocalizedMessage()); + } + else + ShowToastLong(((Exception)task_result).getLocalizedMessage()); + + UpdateSyncButtonLayout(); + } + else + { + _Reader.Start_AsyncTask_GetFeeds(1, getActivity(), onAsyncTask_GetFeed); + if(eListView != null) + eListView.getLoadingLayoutProxy().setLastUpdatedLabel(getString(R.string.pull_to_refresh_updateFeeds)); + } + + lvAdapter.notifyDataSetChanged(); + Log.d(TAG, "onAsyncTask_GetTopReaderTags Finished"); + } + }; + + public void ShowToastLong(String message) + { + Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show(); + } + + OnAsyncTaskCompletedListener onAsyncTask_GetFeed = new OnAsyncTaskCompletedListener() { + + @Override + public void onAsyncTaskCompleted(int task_id, Object task_result) { + + Log.d(TAG, "onAsyncTask_GetSubReaderTags Finished"); + + if(task_result != null) + { + ShowToastLong(((Exception)task_result).getLocalizedMessage()); + UpdateSyncButtonLayout(); + } + else + { + //dbConn.resetRssItemsDatabase(); + + _Reader.Start_AsyncTask_GetItems(2, getActivity(), onAsyncTask_GetItems, TAGS.ALL);//Recieve all unread Items + //_Reader.Start_AsyncTask_GetFeeds(3, getActivity(), onAsyncTask_GetFeeds, TAGS.ALL_STARRED);//Recieve all starred Items + + if(eListView != null) + eListView.getLoadingLayoutProxy().setLastUpdatedLabel(getString(R.string.pull_to_refresh_updateItems)); + } + + + + lvAdapter.ReloadAdapter(); + //lvAdapter.notifyDataSetChanged(); + //eListView.setAdapter(new SubscriptionExpandableListAdapter(getActivity(), dbConn)); + + //new AsyncTask_GetFeeds(0, getActivity(), onAsyncTask_GetFeeds).execute(username, password, Constants._TAG_LABEL_UNREAD); + //new AsyncTask_GetFeeds(0, getActivity(), onAsyncTask_GetFeeds).execute(username, password, Constants._TAG_LABEL_STARRED); + } + }; + + OnAsyncTaskCompletedListener onAsyncTask_GetItems = new OnAsyncTaskCompletedListener() { + + @Override + public void onAsyncTaskCompleted(int task_id, Object task_result) { + + if(task_result != null) + ShowToastLong(((Exception)task_result).getLocalizedMessage()); + + lvAdapter.notifyDataSetChanged(); + //Activity act = getActivity(); + //lvAdapter = new SubscriptionExpandableListAdapter(act, dbConn); + + Log.d(TAG, "onAsyncTask_GetFeeds Finished"); + + if(eListView != null) + eListView.getLoadingLayoutProxy().setLastUpdatedLabel(null); + + UpdateSyncButtonLayout(); + + lvAdapter.ReloadAdapter(); + + NewsReaderListActivity nlActivity = (NewsReaderListActivity) getActivity(); + nlActivity.UpdateItemList(); + + //fireUpdateFinishedClicked(); + } + }; + + + @Override + public View onCreateView(LayoutInflater inflater, ViewGroup container, + Bundle savedInstanceState) { + View V = null; + try + { + V = inflater.inflate(R.layout.expandable_list_layout, container, false); + //eListView = (ExpandableListView) V.findViewById(R.id.expandableListView); + eListView = (PullToRefreshExpandableListView) V.findViewById(R.id.expandableListView); + + + //eListView.setGroupIndicator(getResources().getDrawable(R.drawable.expandable_group_indicator)); + eListView.setGroupIndicator(null); + + //eListView.demo(); + eListView.setShowIndicator(false); + + eListView.setOnRefreshListener(new OnRefreshListener() { + @Override + public void onRefresh(PullToRefreshBase refreshView) { + StartSync(); + } + }); + + eListView.setOnChildClickListener(onChildClickListener); + //eListView.setSmoothScrollbarEnabled(true); + + View empty = inflater.inflate(R.layout.subscription_list_item_empty, null, false); + getActivity().addContentView(empty, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT)); + eListView.setEmptyView(empty); + /* + eListView.setClickable(true); + eListView.setOnGroupClickListener(new OnGroupClickListener() { + + @Override + public boolean onGroupClick(ExpandableListView parent, View v, + int groupPosition, long id) { + Log.d("hi", String.valueOf(groupPosition)); + //return false; + return true; + } + });*/ + eListView.setExpandableAdapter(lvAdapter); + + + //Start auto sync if enabled + SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(getActivity()); + if(mPrefs.getBoolean(SettingsActivity.CB_SYNCONSTARTUP_STRING, false)) + StartSync(); + + } + catch(Exception ex) + { + ex.printStackTrace(); + } + + return V; + //return super.onCreateView(inflater, container, savedInstanceState); + } + + @Override + public void onViewCreated(View view, Bundle savedInstanceState) { + super.onViewCreated(view, savedInstanceState); + + + // Restore the previously serialized activated item position. + if (savedInstanceState != null + && savedInstanceState.containsKey(STATE_ACTIVATED_POSITION)) { + setActivatedPosition(savedInstanceState + .getInt(STATE_ACTIVATED_POSITION)); + } + } + + @Override + public void onAttach(Activity activity) { + super.onAttach(activity); + + // Activities containing this fragment must implement its callbacks. + if (!(activity instanceof Callbacks)) { + throw new IllegalStateException( + "Activity must implement fragment's callbacks."); + } + + mCallbacks = (Callbacks) activity; + } + + @Override + public void onDetach() { + super.onDetach(); + + // Reset the active callbacks interface to the dummy implementation. + mCallbacks = sExpListCallbacks; + } + + ExpListTextClicked expListTextClickedListener = new ExpListTextClicked() { + + @Override + public void onTextClicked(String idSubscription, Context context, boolean isFolder, String optional_folder_id) { + mCallbacks.onTopItemClicked(idSubscription, isFolder, optional_folder_id); + } + }; + + /* + @Override + public void onListItemClick(ListView listView, View view, int position, + long id) { + super.onListItemClick(listView, view, position, id); + + // Notify the active callbacks interface (the activity, if the + // fragment is attached to one) that an item has been selected. + + //mCallbacks.onItemSelected(DummyContent.ITEMS.get(position).id); + }*/ + + @Override + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + if (mActivatedPosition != ListView.INVALID_POSITION) { + // Serialize and persist the activated item position. + outState.putInt(STATE_ACTIVATED_POSITION, mActivatedPosition); + } + } + + OnChildClickListener onChildClickListener = new OnChildClickListener() { + + @Override + public boolean onChildClick(ExpandableListView parent, View v, + int groupPosition, int childPosition, long id) { + + long idItem = lvAdapter.getChildId(groupPosition, childPosition); + + String optional_id_folder = null; + FolderSubscribtionItem groupItem = (FolderSubscribtionItem) lvAdapter.getGroup(groupPosition); + if(groupItem != null) + optional_id_folder = String.valueOf(groupItem.id_database); + + mCallbacks.onChildItemClicked(String.valueOf(idItem), optional_id_folder); + + return false; + } + }; + + /** + * Turns on activate-on-click mode. When this mode is on, list items will be + * given the 'activated' state when touched. + */ + public void setActivateOnItemClick(boolean activateOnItemClick) { + // When setting CHOICE_MODE_SINGLE, ListView will automatically + // give items the 'activated' state when touched. + + + //eListView.setChoiceMode(activateOnItemClick ? ListView.CHOICE_MODE_SINGLE : ListView.CHOICE_MODE_NONE);//TODO comment this in + } + + private void setActivatedPosition(int position) {/*//TODO comment this in + if (position == ListView.INVALID_POSITION) { + //getListView().setItemChecked(mActivatedPosition, false); + eListView.setItemChecked(mActivatedPosition, false); + } else { + eListView.setItemChecked(position, true); + //getListView().setItemChecked(position, true); + }*/ + + mActivatedPosition = position; + } + + + public void UpdateSyncButtonLayout() + { + if(getActivity() != null) + ((NewsReaderListActivity) getActivity()).UpdateButtonSyncLayout(); + } + + /** + * @return the eListView + */ + public PullToRefreshExpandableListView geteListView() { + return eListView; + } + + /* + public void setUpdateFinishedListener(AsyncUpdateFinished listener) + { + asyncUpdateFinished = listener; + } + protected void fireUpdateFinishedClicked() + { + if(asyncUpdateFinished != null) + asyncUpdateFinished.FinishedUpdate(); + }*/ +} + + +/* + dbConn.insertNewSubscription("Ungelesene Artikel"); + dbConn.insertNewSubscription("Markierte Artikel"); + dbConn.insertNewSubscription("Android"); + dbConn.insertNewSubscription("Apple"); + dbConn.insertNewSubscription("Bugtracker"); + dbConn.insertNewSubscription("Development"); + dbConn.insertNewSubscription("Linux"); + dbConn.insertNewSubscription("Software"); + dbConn.insertNewSubscription("Owncloud"); + dbConn.insertNewSubscription("Other"); + + dbConn.insertNewSub_Subscription("4droid", dbConn.getIdOfSubscription("Android")); + dbConn.insertNewSub_Subscription("GIGA Rss Feed", dbConn.getIdOfSubscription("Android")); + + dbConn.insertNewSub_Subscription("macnews.de", dbConn.getIdOfSubscription("Apple")); + dbConn.insertNewSub_Subscription("MACNOTES.DE", dbConn.getIdOfSubscription("Apple")); + + dbConn.insertNewSub_Subscription("FS Bugtracker", dbConn.getIdOfSubscription("Bugtracker")); + + dbConn.insertNewSub_Subscription("Code 2 Learn", dbConn.getIdOfSubscription("Development")); + dbConn.insertNewSub_Subscription("Coding Horror", dbConn.getIdOfSubscription("Development")); + + dbConn.insertNewSub_Subscription("Canoncial", dbConn.getIdOfSubscription("Linux")); + + dbConn.insertNewSub_Subscription("iTek Zone", dbConn.getIdOfSubscription("Software")); + + dbConn.insertNewSub_Subscription("CNET", dbConn.getIdOfSubscription("Other")); + + dbConn.insertNewSub_Subscription("ownCloud.org", dbConn.getIdOfSubscription("Owncloud")); + + dbConn.insertNewFeed("Samsung Game Pad pops up on Galaxy S4 site, outs Note 3?", + "http://news.cnet.com/8301-17938_105-57574766-1/samsung-game-pad-pops-up-on-galaxy-s4-site-outs-note-3/?part\u003drss\u0026subj\u003dnews\u0026tag\u003d2547-1_3-0-20", + "The gaming controller works with devices up to 6.3 inches, perhaps suggesting Samsung is planning a bigger phablet, or should we be calling it a \"tabone?\"", + "0", + dbConn.getIdOfSubscription("CNET")); + + */ + diff --git a/src/de/luhmer/owncloudnewsreader/cursor/NewsListCursorAdapter.java b/src/de/luhmer/owncloudnewsreader/cursor/NewsListCursorAdapter.java index df86c518..e46526c7 100644 --- a/src/de/luhmer/owncloudnewsreader/cursor/NewsListCursorAdapter.java +++ b/src/de/luhmer/owncloudnewsreader/cursor/NewsListCursorAdapter.java @@ -1,318 +1,347 @@ -package de.luhmer.owncloudnewsreader.cursor; - -import java.text.SimpleDateFormat; -import java.util.Date; - -import android.annotation.SuppressLint; -import android.annotation.TargetApi; -import android.content.Context; -import android.content.SharedPreferences; -import android.database.Cursor; -import android.os.Build; -import android.preference.PreferenceManager; -import android.support.v4.widget.CursorAdapter; -import android.text.Html; -import android.text.Spannable; -import android.text.SpannableString; -import android.text.style.ForegroundColorSpan; -import android.view.LayoutInflater; -import android.view.View; -import android.view.ViewGroup; -import android.webkit.WebView; -import android.widget.CheckBox; -import android.widget.CompoundButton; -import android.widget.CompoundButton.OnCheckedChangeListener; -import android.widget.LinearLayout; -import android.widget.TextView; -import de.luhmer.owncloudnewsreader.NewsDetailFragment; -import de.luhmer.owncloudnewsreader.R; -import de.luhmer.owncloudnewsreader.SettingsActivity; -import de.luhmer.owncloudnewsreader.database.DatabaseConnection; -import de.luhmer.owncloudnewsreader.reader.IReader; -import de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloud_Reader; - -public class NewsListCursorAdapter extends CursorAdapter { - DatabaseConnection dbConn; - IReader _Reader; - SimpleDateFormat simpleDateFormat; - final int LengthBody = 300; - ForegroundColorSpan bodyForegroundColor; - - int selectedDesign = 0; - - @SuppressLint("SimpleDateFormat") - @SuppressWarnings("deprecation") - public NewsListCursorAdapter(Context context, Cursor c) { - super(context, c); - - simpleDateFormat = new SimpleDateFormat("EEE, d. MMM HH:mm:ss"); - bodyForegroundColor = new ForegroundColorSpan(context.getResources().getColor(android.R.color.secondary_text_dark)); - - _Reader = new OwnCloud_Reader(); - dbConn = new DatabaseConnection(context); - - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext); - selectedDesign = Integer.valueOf(mPrefs.getString(SettingsActivity.SP_FEED_LIST_LAYOUT, "0")); - } - - @Override - public void bindView(View view, final Context context, Cursor cursor) { - final String idItemDb = cursor.getString(0); - //final String idItem = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_RSSITEM_ID)); - - switch (selectedDesign) { - case 0: - setSimpleLayout(view, cursor); - break; - - case 1: - setExtendedLayout(view, cursor); - break; - - case 2: - setExtendedLayoutWebView(view, cursor); - break; - - default: - break; - } - - CheckBox cb = (CheckBox) view.findViewById(R.id.cb_lv_item_starred); - cb.setOnCheckedChangeListener(null); - - Boolean isStarred = dbConn.isFeedUnreadStarred(cursor.getString(0), false);//false => starred will be checked - //Log.d("ISSTARRED", "" + isStarred + " - Cursor: " + cursor.getString(0)); - cb.setChecked(isStarred);/* - if(isStarred) - cb.setButtonDrawable(R.drawable.btn_rating_star_on_normal_holo_light); - else - cb.setButtonDrawable(R.drawable.btn_rating_star_off_normal_holo_light); - */ - cb.setClickable(true); - cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { - - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - /* - if(isChecked) - buttonView.setButtonDrawable(R.drawable.btn_rating_star_on_normal_holo_light); - else - buttonView.setButtonDrawable(R.drawable.btn_rating_star_off_normal_holo_light); - */ - - dbConn.updateIsStarredOfFeed(idItemDb, isChecked); - - if(isChecked) - UpdateIsReadCheckBox(buttonView, idItemDb); - - /* - List idItems = new ArrayList(); - idItems.add(idItem); - if(isChecked) - _Reader.Start_AsyncTask_PerformTagAction(0, context, asyncTaskCompletedPerformTagRead, idItems, FeedItemTags.TAGS.MARK_ITEM_AS_STARRED); - else - _Reader.Start_AsyncTask_PerformTagAction(0, context, asyncTaskCompletedPerformTagRead, idItems, FeedItemTags.TAGS.MARK_ITEM_AS_UNSTARRED); - */ - - } - }); - - - CheckBox cbRead = (CheckBox) view.findViewById(R.id.cb_lv_item_read); - cbRead.setOnCheckedChangeListener(null); - Boolean isChecked = dbConn.isFeedUnreadStarred(cursor.getString(0), true); - //Log.d("ISREAD", "" + isChecked + " - Cursor: " + cursor.getString(0)); - cbRead.setChecked(isChecked); - cbRead.setClickable(true); - cbRead.setOnCheckedChangeListener(new OnCheckedChangeListener() { - - @Override - public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { - //GoogleReaderMethods.MarkItemAsRead(isChecked, getCursorForCurrentRow(buttonView), dbConn, context, asyncTaskCompletedPerformTagStarred); - - dbConn.updateIsReadOfFeed(idItemDb, isChecked); - - /* - //TODO THIS IS IMPORTANT CODE ! - List idItems = new ArrayList(); - idItems.add(idItem); - if(isChecked) - _Reader.Start_AsyncTask_PerformTagActionForSingleItem(0, context, asyncTaskCompletedPerformTagRead, idItems, FeedItemTags.TAGS.MARK_ITEM_AS_READ); - else - _Reader.Start_AsyncTask_PerformTagActionForSingleItem(0, context, asyncTaskCompletedPerformTagRead, idItems, FeedItemTags.TAGS.MARK_ITEM_AS_UNREAD); - */ - } - }); - - //Log.d("NewsListCursor", "BIND VIEW.."); - //((CheckBox) view.findViewById(R.id.cb_lv_item_starred)).setButtonDrawable(R.drawable.btn_rating_star_off_normal_holo_light); - } - - public void setSimpleLayout(View view, Cursor cursor) - { - TextView textViewSummary = (TextView) view.findViewById(R.id.summary); - textViewSummary.setText(Html.fromHtml(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_TITLE))).toString()); - - TextView textViewItemDate = (TextView) view.findViewById(R.id.tv_item_date); - long pubDate = cursor.getLong(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_PUBDATE)); - textViewItemDate.setText(simpleDateFormat.format(new Date(pubDate))); - - TextView textViewTitle = (TextView) view.findViewById(R.id.tv_subscription); - textViewTitle.setText(dbConn.getTitleOfSubscriptionByRowID(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_SUBSCRIPTION_ID)))); - textViewSummary.setTag(cursor.getString(0)); - } - - public void setExtendedLayout(View view, Cursor cursor) - { - TextView textViewSummary = (TextView) view.findViewById(R.id.summary); - textViewSummary.setText(Html.fromHtml(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_TITLE))).toString()); - - TextView textViewItemDate = (TextView) view.findViewById(R.id.tv_item_date); - long pubDate = cursor.getLong(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_PUBDATE)); - textViewItemDate.setText(simpleDateFormat.format(new Date(pubDate))); - - TextView textViewItemBody = (TextView) view.findViewById(R.id.body); - String body = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_BODY)); - textViewItemBody.setText(getBodyText(body)); - - TextView textViewTitle = (TextView) view.findViewById(R.id.tv_subscription); - textViewTitle.setText(dbConn.getTitleOfSubscriptionByRowID(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_SUBSCRIPTION_ID)))); - textViewSummary.setTag(cursor.getString(0)); - } - - @TargetApi(Build.VERSION_CODES.HONEYCOMB) - public void setExtendedLayoutWebView(View view, Cursor cursor) - { - - /* - TextView textViewSummary = (TextView) view.findViewById(R.id.summary); - textViewSummary.setText(Html.fromHtml(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_TITLE))).toString()); - - TextView textViewItemDate = (TextView) view.findViewById(R.id.tv_item_date); - long pubDate = cursor.getLong(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_PUBDATE)); - textViewItemDate.setText(simpleDateFormat.format(new Date(pubDate))); - */ - - WebView webViewContent = (WebView) view.findViewById(R.id.webView_body); - webViewContent.setClickable(false); - webViewContent.setFocusable(false); - //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) - // webViewContent.setLayerType(View.LAYER_TYPE_SOFTWARE, null); - - webViewContent.loadDataWithBaseURL("", NewsDetailFragment.getHtmlPage(mContext, dbConn , cursor.getInt(0)), "text/html", "UTF-8", ""); - - /* - TextView textViewTitle = (TextView) view.findViewById(R.id.tv_subscription); - textViewTitle.setText(dbConn.getTitleOfSubscriptionByRowID(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_SUBSCRIPTION_ID)))); - textViewSummary.setTag(cursor.getString(0)); - */ - } - - - /* - class ItemHolder { - TextView txt_feed; - TextView txt_item_date; - TextView txt_summary; - TextView txt_body; - CheckBox cb_starred; - CheckBox cb_read; - }*/ - - public void CloseDatabaseConnection() - { - if(dbConn != null) - dbConn.closeDatabase(); - } - - private void UpdateIsReadCheckBox(View view, String idItemDb) - { - LinearLayout lLayout = (LinearLayout) view.getParent(); - Boolean isChecked = dbConn.isFeedUnreadStarred(idItemDb, true); - CheckBox cbRead = (CheckBox) lLayout.findViewById(R.id.cb_lv_item_read); - cbRead.setChecked(isChecked); - } - - private String getBodyText(String body) - { - //if(body.length() > LengthBody) - // body = body.substring(0, LengthBody); - - body = body.replaceAll("]*>", ""); - body = body.replaceAll("]*>", ""); - - SpannableString bodyStringSpannable = new SpannableString(Html.fromHtml(body)); - bodyStringSpannable.setSpan(bodyForegroundColor, 0, bodyStringSpannable.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); - - String bodyString = bodyStringSpannable.toString().trim(); - - if(bodyString.length() > LengthBody) - bodyString = bodyString.substring(0, LengthBody); - - return bodyString; - } - - /* - private Cursor getCursorForCurrentRow(CompoundButton buttonView) - { - TextView tv = (TextView) ((ViewGroup)((ViewGroup) buttonView.getParent()).getChildAt(1)).getChildAt(1); - String id_DB_Feed = (String) tv.getTag(); - //String id_DB_Feed = (String) ((View)buttonView.getParent()).getTag(); - - Cursor cur = dbConn.getFeedByID(id_DB_Feed); - cur.moveToFirst(); - return cur; - }*/ - - @Override - public View newView(Context arg0, Cursor cursor, ViewGroup parent) { - // when the view will be created for first time, - // we need to tell the adapters, how each item will look - LayoutInflater inflater = LayoutInflater.from(parent.getContext()); - View retView = null; - - switch (selectedDesign) { - case 0: - retView = inflater.inflate(R.layout.subscription_detail_list_item_simple, parent, false); - break; - case 1: - retView = inflater.inflate(R.layout.subscription_detail_list_item_extended, parent, false); - break; - - case 2: - retView = inflater.inflate(R.layout.subscription_detail_list_item_extended_webview, parent, false); - break; - - default: - break; - } - - if(retView != null) - retView.setTag(cursor.getString(0)); - - - - - //retView.getLocationOnScreen(location); - //Log.d("NewsListCursor", "NEW VIEW.."); - - return retView; - } - - /* - OnAsyncTaskCompletedListener asyncTaskCompletedPerformTagRead = new OnAsyncTaskCompletedListener() { - - @Override - public void onAsyncTaskCompleted(int task_id, Object task_result) { - Log.d("FINISHED PERFORM TAG READ ", "" + task_result); - } - }; - - OnAsyncTaskCompletedListener asyncTaskCompletedPerformTagStarred = new OnAsyncTaskCompletedListener() { - - @Override - public void onAsyncTaskCompleted(int task_id, Object task_result) { - Log.d("FINISHED PERFORM TAG STARRED ", "" + task_result); - } - };*/ -} +package de.luhmer.owncloudnewsreader.cursor; + +import java.text.SimpleDateFormat; +import java.util.Date; + +import android.annotation.SuppressLint; +import android.annotation.TargetApi; +import android.content.Context; +import android.content.SharedPreferences; +import android.database.Cursor; +import android.os.Build; +import android.preference.PreferenceManager; +import android.support.v4.widget.CursorAdapter; +import android.text.Html; +import android.text.Spannable; +import android.text.SpannableString; +import android.text.style.ForegroundColorSpan; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.webkit.WebView; +import android.widget.CheckBox; +import android.widget.CompoundButton; +import android.widget.CompoundButton.OnCheckedChangeListener; +import android.widget.LinearLayout; +import android.widget.TextView; + +import com.actionbarsherlock.app.SherlockFragmentActivity; + +import de.luhmer.owncloudnewsreader.NewsDetailFragment; +import de.luhmer.owncloudnewsreader.NewsReaderListActivity; +import de.luhmer.owncloudnewsreader.R; +import de.luhmer.owncloudnewsreader.SettingsActivity; +import de.luhmer.owncloudnewsreader.database.DatabaseConnection; +import de.luhmer.owncloudnewsreader.reader.IReader; +import de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloud_Reader; + +public class NewsListCursorAdapter extends CursorAdapter { + DatabaseConnection dbConn; + IReader _Reader; + SimpleDateFormat simpleDateFormat; + final int LengthBody = 300; + ForegroundColorSpan bodyForegroundColor; + + int selectedDesign = 0; + + @SuppressLint("SimpleDateFormat") + @SuppressWarnings("deprecation") + public NewsListCursorAdapter(Context context, Cursor c) { + super(context, c); + + simpleDateFormat = new SimpleDateFormat("EEE, d. MMM HH:mm:ss"); + bodyForegroundColor = new ForegroundColorSpan(context.getResources().getColor(android.R.color.secondary_text_dark)); + + _Reader = new OwnCloud_Reader(); + dbConn = new DatabaseConnection(context); + + SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext); + selectedDesign = Integer.valueOf(mPrefs.getString(SettingsActivity.SP_FEED_LIST_LAYOUT, "0")); + } + + @Override + public void bindView(View view, final Context context, Cursor cursor) { + final String idItemDb = cursor.getString(0); + //final String idItem = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_RSSITEM_ID)); + + switch (selectedDesign) { + case 0: + setSimpleLayout(view, cursor); + break; + + case 1: + setExtendedLayout(view, cursor); + break; + + case 2: + setExtendedLayoutWebView(view, cursor); + break; + + default: + break; + } + + CheckBox cb = (CheckBox) view.findViewById(R.id.cb_lv_item_starred); + cb.setOnCheckedChangeListener(null); + + Boolean isStarred = dbConn.isFeedUnreadStarred(cursor.getString(0), false);//false => starred will be checked + //Log.d("ISSTARRED", "" + isStarred + " - Cursor: " + cursor.getString(0)); + cb.setChecked(isStarred);/* + if(isStarred) + cb.setButtonDrawable(R.drawable.btn_rating_star_on_normal_holo_light); + else + cb.setButtonDrawable(R.drawable.btn_rating_star_off_normal_holo_light); + */ + + cb.setClickable(true); + cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + /* + if(isChecked) + buttonView.setButtonDrawable(R.drawable.btn_rating_star_on_normal_holo_light); + else + buttonView.setButtonDrawable(R.drawable.btn_rating_star_off_normal_holo_light); + */ + + dbConn.updateIsStarredOfFeed(idItemDb, isChecked); + + if(isChecked) + UpdateIsReadCheckBox(buttonView, idItemDb); + + /* + List idItems = new ArrayList(); + idItems.add(idItem); + if(isChecked) + _Reader.Start_AsyncTask_PerformTagAction(0, context, asyncTaskCompletedPerformTagRead, idItems, FeedItemTags.TAGS.MARK_ITEM_AS_STARRED); + else + _Reader.Start_AsyncTask_PerformTagAction(0, context, asyncTaskCompletedPerformTagRead, idItems, FeedItemTags.TAGS.MARK_ITEM_AS_UNSTARRED); + */ + + } + }); + + + CheckBox cbRead = (CheckBox) view.findViewById(R.id.cb_lv_item_read); + cbRead.setOnCheckedChangeListener(null); + Boolean isChecked = dbConn.isFeedUnreadStarred(cursor.getString(0), true); + //Log.d("ISREAD", "" + isChecked + " - Cursor: " + cursor.getString(0)); + cbRead.setChecked(isChecked); + cbRead.setClickable(true); + cbRead.setOnCheckedChangeListener(new OnCheckedChangeListener() { + + @Override + public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { + //GoogleReaderMethods.MarkItemAsRead(isChecked, getCursorForCurrentRow(buttonView), dbConn, context, asyncTaskCompletedPerformTagStarred); + + dbConn.updateIsReadOfFeed(idItemDb, isChecked); + UpdateListCursor(mContext); + /* + //TODO THIS IS IMPORTANT CODE ! + List idItems = new ArrayList(); + idItems.add(idItem); + if(isChecked) + _Reader.Start_AsyncTask_PerformTagActionForSingleItem(0, context, asyncTaskCompletedPerformTagRead, idItems, FeedItemTags.TAGS.MARK_ITEM_AS_READ); + else + _Reader.Start_AsyncTask_PerformTagActionForSingleItem(0, context, asyncTaskCompletedPerformTagRead, idItems, FeedItemTags.TAGS.MARK_ITEM_AS_UNREAD); + */ + } + }); + + //Log.d("NewsListCursor", "BIND VIEW.."); + //((CheckBox) view.findViewById(R.id.cb_lv_item_starred)).setButtonDrawable(R.drawable.btn_rating_star_off_normal_holo_light); + } + + public void setSimpleLayout(View view, Cursor cursor) + { + TextView textViewSummary = (TextView) view.findViewById(R.id.summary); + textViewSummary.setText(Html.fromHtml(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_TITLE))).toString()); + + TextView textViewItemDate = (TextView) view.findViewById(R.id.tv_item_date); + long pubDate = cursor.getLong(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_PUBDATE)); + textViewItemDate.setText(simpleDateFormat.format(new Date(pubDate))); + + TextView textViewTitle = (TextView) view.findViewById(R.id.tv_subscription); + textViewTitle.setText(dbConn.getTitleOfSubscriptionByRowID(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_SUBSCRIPTION_ID)))); + textViewSummary.setTag(cursor.getString(0)); + } + + public void setExtendedLayout(View view, Cursor cursor) + { + TextView textViewSummary = (TextView) view.findViewById(R.id.summary); + textViewSummary.setText(Html.fromHtml(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_TITLE))).toString()); + + TextView textViewItemDate = (TextView) view.findViewById(R.id.tv_item_date); + long pubDate = cursor.getLong(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_PUBDATE)); + textViewItemDate.setText(simpleDateFormat.format(new Date(pubDate))); + + TextView textViewItemBody = (TextView) view.findViewById(R.id.body); + String body = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_BODY)); + textViewItemBody.setText(getBodyText(body)); + + TextView textViewTitle = (TextView) view.findViewById(R.id.tv_subscription); + textViewTitle.setText(dbConn.getTitleOfSubscriptionByRowID(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_SUBSCRIPTION_ID)))); + textViewSummary.setTag(cursor.getString(0)); + } + + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + public void setExtendedLayoutWebView(View view, Cursor cursor) + { + + /* + TextView textViewSummary = (TextView) view.findViewById(R.id.summary); + textViewSummary.setText(Html.fromHtml(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_TITLE))).toString()); + + TextView textViewItemDate = (TextView) view.findViewById(R.id.tv_item_date); + long pubDate = cursor.getLong(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_PUBDATE)); + textViewItemDate.setText(simpleDateFormat.format(new Date(pubDate))); + */ + + WebView webViewContent = (WebView) view.findViewById(R.id.webView_body); + webViewContent.setClickable(false); + webViewContent.setFocusable(false); + //if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) + // webViewContent.setLayerType(View.LAYER_TYPE_SOFTWARE, null); + + webViewContent.loadDataWithBaseURL("", NewsDetailFragment.getHtmlPage(mContext, dbConn , cursor.getInt(0)), "text/html", "UTF-8", ""); + + /* + TextView textViewTitle = (TextView) view.findViewById(R.id.tv_subscription); + textViewTitle.setText(dbConn.getTitleOfSubscriptionByRowID(cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_SUBSCRIPTION_ID)))); + textViewSummary.setTag(cursor.getString(0)); + */ + } + + + /* + class ItemHolder { + TextView txt_feed; + TextView txt_item_date; + TextView txt_summary; + TextView txt_body; + CheckBox cb_starred; + CheckBox cb_read; + }*/ + + public void CloseDatabaseConnection() + { + if(dbConn != null) + dbConn.closeDatabase(); + } + + private void UpdateIsReadCheckBox(View view, String idItemDb) + { + LinearLayout lLayout = (LinearLayout) view.getParent(); + Boolean isChecked = dbConn.isFeedUnreadStarred(idItemDb, true); + CheckBox cbRead = (CheckBox) lLayout.findViewById(R.id.cb_lv_item_read); + //ChangeCheckBoxState(cbRead, isChecked, mContext); + cbRead.setChecked(isChecked); + } + + public static void ChangeCheckBoxState(CheckBox cb, boolean state, Context context) + { + if(cb != null) + { + if(cb.isChecked() != state) + { + cb.setChecked(state); + + UpdateListCursor(context); + } + } + } + + public static void UpdateListCursor(Context context)//TODO make this better + { + SherlockFragmentActivity sfa = (SherlockFragmentActivity) context; + + //if tablet view is enabled --> update the listview + if(sfa instanceof NewsReaderListActivity) + ((NewsReaderListActivity) sfa).updateAdapter(); + } + + + private String getBodyText(String body) + { + //if(body.length() > LengthBody) + // body = body.substring(0, LengthBody); + + body = body.replaceAll("]*>", ""); + body = body.replaceAll("]*>", ""); + + SpannableString bodyStringSpannable = new SpannableString(Html.fromHtml(body)); + bodyStringSpannable.setSpan(bodyForegroundColor, 0, bodyStringSpannable.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE); + + String bodyString = bodyStringSpannable.toString().trim(); + + if(bodyString.length() > LengthBody) + bodyString = bodyString.substring(0, LengthBody); + + return bodyString; + } + + /* + private Cursor getCursorForCurrentRow(CompoundButton buttonView) + { + TextView tv = (TextView) ((ViewGroup)((ViewGroup) buttonView.getParent()).getChildAt(1)).getChildAt(1); + String id_DB_Feed = (String) tv.getTag(); + //String id_DB_Feed = (String) ((View)buttonView.getParent()).getTag(); + + Cursor cur = dbConn.getFeedByID(id_DB_Feed); + cur.moveToFirst(); + return cur; + }*/ + + @Override + public View newView(Context arg0, Cursor cursor, ViewGroup parent) { + // when the view will be created for first time, + // we need to tell the adapters, how each item will look + LayoutInflater inflater = LayoutInflater.from(parent.getContext()); + View retView = null; + + switch (selectedDesign) { + case 0: + retView = inflater.inflate(R.layout.subscription_detail_list_item_simple, parent, false); + break; + case 1: + retView = inflater.inflate(R.layout.subscription_detail_list_item_extended, parent, false); + break; + + case 2: + retView = inflater.inflate(R.layout.subscription_detail_list_item_extended_webview, parent, false); + break; + + default: + break; + } + + if(retView != null) + retView.setTag(cursor.getString(0)); + + + + + //retView.getLocationOnScreen(location); + //Log.d("NewsListCursor", "NEW VIEW.."); + + return retView; + } + + /* + OnAsyncTaskCompletedListener asyncTaskCompletedPerformTagRead = new OnAsyncTaskCompletedListener() { + + @Override + public void onAsyncTaskCompleted(int task_id, Object task_result) { + Log.d("FINISHED PERFORM TAG READ ", "" + task_result); + } + }; + + OnAsyncTaskCompletedListener asyncTaskCompletedPerformTagStarred = new OnAsyncTaskCompletedListener() { + + @Override + public void onAsyncTaskCompleted(int task_id, Object task_result) { + Log.d("FINISHED PERFORM TAG STARRED ", "" + task_result); + } + };*/ +} diff --git a/src/de/luhmer/owncloudnewsreader/data/ConcreteSubscribtionItem.java b/src/de/luhmer/owncloudnewsreader/data/ConcreteFeedItem.java similarity index 65% rename from src/de/luhmer/owncloudnewsreader/data/ConcreteSubscribtionItem.java rename to src/de/luhmer/owncloudnewsreader/data/ConcreteFeedItem.java index 97826176..0ec87c7d 100644 --- a/src/de/luhmer/owncloudnewsreader/data/ConcreteSubscribtionItem.java +++ b/src/de/luhmer/owncloudnewsreader/data/ConcreteFeedItem.java @@ -1,19 +1,19 @@ -package de.luhmer.owncloudnewsreader.data; - -public class ConcreteSubscribtionItem { - - public String folder_id; - public String subscription_id; - public String favIcon; - public String header; - public long id_database; - - public ConcreteSubscribtionItem(String header, String folder_id, String subscription_id, String favIcon, long id_database/*, String parent_title*/) { - - this.header = header; - this.folder_id = folder_id; - this.subscription_id = subscription_id; - this.favIcon = favIcon; - this.id_database = id_database; - } -} +package de.luhmer.owncloudnewsreader.data; + +public class ConcreteFeedItem { + + public String folder_id; + public String subscription_id; + public String favIcon; + public String header; + public long id_database; + + public ConcreteFeedItem(String header, String folder_id, String subscription_id, String favIcon, long id_database/*, String parent_title*/) { + + this.header = header; + this.folder_id = folder_id; + this.subscription_id = subscription_id; + this.favIcon = favIcon; + this.id_database = id_database; + } +} diff --git a/src/de/luhmer/owncloudnewsreader/database/DatabaseConnection.java b/src/de/luhmer/owncloudnewsreader/database/DatabaseConnection.java index 887697ff..a3a44978 100644 --- a/src/de/luhmer/owncloudnewsreader/database/DatabaseConnection.java +++ b/src/de/luhmer/owncloudnewsreader/database/DatabaseConnection.java @@ -1,806 +1,807 @@ -package de.luhmer.owncloudnewsreader.database; - -import java.util.ArrayList; -import java.util.Date; -import java.util.List; - -import android.content.ContentValues; -import android.content.Context; -import android.database.Cursor; -import android.database.sqlite.SQLiteDatabase; -import android.util.Log; -import de.luhmer.owncloudnewsreader.ListView.SubscriptionExpandableListAdapter; - -public class DatabaseConnection { - private DatabaseHelper openHelper; - private SQLiteDatabase database; - - public static final String FOLDER_TABLE = "folder"; - public static final String FOLDER_LABEL = "label"; - public static final String FOLDER_LABEL_ID = "label_id"; - - public static final String SUBSCRIPTION_TABLE = "subscription"; - public static final String SUBSCRIPTION_HEADERTEXT = "header_text"; - //public static final String SUBSCRIPTION_SUBSCRIPTION_ID = "subscription_id_subscription"; - public static final String SUBSCRIPTION_FOLDER_ID = "folder_idfolder"; - public static final String SUBSCRIPTION_ID = "subscription_id"; - public static final String SUBSCRIPTION_FAVICON_URL = "favicon_url"; - public static final String SUBSCRIPTION_LINK = "link"; - - public static final String RSS_ITEM_TABLE = "rss_item"; - public static final String RSS_ITEM_SUBSCRIPTION_ID = "subscription_id_subscription"; - public static final String RSS_ITEM_TITLE = "title"; - public static final String RSS_ITEM_LINK = "link"; - public static final String RSS_ITEM_BODY = "body"; - public static final String RSS_ITEM_READ = "read"; - public static final String RSS_ITEM_RSSITEM_ID = "rssitem_id"; - public static final String RSS_ITEM_STARRED = "starred"; - public static final String RSS_ITEM_PUBDATE = "pubdate"; - public static final String RSS_ITEM_AUTHOR = "author"; - public static final String RSS_ITEM_GUID = "guid"; - public static final String RSS_ITEM_GUIDHASH = "guidHash"; - public static final String RSS_ITEM_LAST_MODIFIED = "lastModified"; - - public static final String RSS_ITEM_READ_TEMP = "read_temp"; - public static final String RSS_ITEM_STARRED_TEMP = "starred_temp"; - - - public static final boolean DATABASE_DEBUG_MODE = false; //(false && Constants.DEBUG_MODE) ? true: false; - - - public DatabaseConnection(Context aContext) { - openHelper = new DatabaseHelper(aContext); - openDatabase(); - } - - public SQLiteDatabase getDatabase() - { - return database; - } - - - public void clearDatabaseOverSize() - { - //If i have 9023 rows in the database, when i run that query it should delete 8023 rows and leave me with 1000 - //database.execSQL("DELETE FROM " + RSS_ITEM_TABLE + " WHERE " + + "ORDER BY rowid DESC LIMIT 1000 * - - //Let's say it said 1005 - you need to delete 5 rows. - //DELETE FROM table ORDER BY dateRegistered ASC LIMIT 5 - - - int max = 1000; - int total = (int) getLongValueBySQL("SELECT COUNT(*) FROM rss_item"); - int unread = (int) getLongValueBySQL("SELECT COUNT(*) FROM rss_item WHERE read_temp != 1"); - int read = total - unread; - - if(total > max) - { - int overSize = total - max; - //Soll verhindern, dass ungelesene Artikel gelöscht werden - if(overSize > read) - overSize = read; - database.execSQL("DELETE FROM rss_item WHERE read_temp = 1 AND rowid IN (SELECT rowid FROM rss_item WHERE read_temp = 1 ORDER BY rowid asc LIMIT " + overSize + ")"); - /* SELECT * FROM rss_item WHERE read_temp = 1 ORDER BY rowid asc LIMIT 3; */ - } - } - - public void markAllItemsAsRead(List itemIds) - { - if(itemIds != null) - for(Integer idItem : itemIds) - updateIsReadOfFeed(String.valueOf(idItem), true); - } - - public int getCountOfAllItems(boolean execludeStarred) - { - String buildSQL = "SELECT count(*) FROM " + RSS_ITEM_TABLE; - if(execludeStarred) - buildSQL += " WHERE " + RSS_ITEM_STARRED_TEMP + " != 1"; - - int result = 0; - - Cursor cursor = database.rawQuery(buildSQL, null); - try - { - if(cursor != null) - { - cursor.moveToFirst(); - result = cursor.getInt(0); - } - } finally { - cursor.close(); - } - - return result; - } - - public long getLastModfied() - { - String buildSQL = "SELECT MAX(" + RSS_ITEM_LAST_MODIFIED + ") FROM " + RSS_ITEM_TABLE; - long result = 0; - - Cursor cursor = database.rawQuery(buildSQL, null); - try - { - if(cursor != null) - { - cursor.moveToFirst(); - result = cursor.getLong(0); - } - } finally { - cursor.close(); - } - - return result; - } - - public long getItemDbIdAtPosition(int positionXRow) - { - String buildSQL = "SELECT rowid FROM " + RSS_ITEM_TABLE; - long result = -1; - - Cursor cursor = database.rawQuery(buildSQL, null); - try - { - if(cursor != null) - { - if(cursor.move(cursor.getCount() - (positionXRow - 1))) - result = cursor.getLong(0); - } - } finally { - cursor.close(); - } - - return result; - } - - public List getAllNewReadItems() - { - String buildSQL = "SELECT " + RSS_ITEM_RSSITEM_ID + " FROM " + RSS_ITEM_TABLE + " WHERE " - + RSS_ITEM_READ_TEMP + " = 1 AND " - + RSS_ITEM_READ + " = 0"; - Cursor cursor = database.rawQuery(buildSQL, null); - return convertCursorToStringArray(cursor, 0); - } - - public List getAllNewUnreadItems() - { - String buildSQL = "SELECT " + RSS_ITEM_RSSITEM_ID + " FROM " + RSS_ITEM_TABLE + " WHERE " - + RSS_ITEM_READ_TEMP + " = 0 AND " - + RSS_ITEM_READ + " = 1"; - Cursor cursor = database.rawQuery(buildSQL, null); - return convertCursorToStringArray(cursor, 0); - } - - public List getAllNewStarredItems() - { - String buildSQL = "SELECT " + RSS_ITEM_RSSITEM_ID + " FROM " + RSS_ITEM_TABLE + " WHERE " - + RSS_ITEM_STARRED_TEMP + " = 1 AND " - + RSS_ITEM_STARRED + " = 0"; - Cursor cursor = database.rawQuery(buildSQL, null); - return convertCursorToStringArray(cursor, 0); - } - - public List getAllNewUnstarredItems() - { - String buildSQL = "SELECT " + RSS_ITEM_RSSITEM_ID + " FROM " + RSS_ITEM_TABLE + " WHERE " - + RSS_ITEM_STARRED_TEMP + " = 0 AND " - + RSS_ITEM_STARRED + " = 1"; - Cursor cursor = database.rawQuery(buildSQL, null); - return convertCursorToStringArray(cursor, 0); - } - - public Cursor getAllItemsWithIdHigher(String id_item) { - //String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE subscription_id_subscription IS NULL"; - String buildSQL = "SELECT rowid as _id, * FROM " + RSS_ITEM_TABLE + " WHERE " + RSS_ITEM_RSSITEM_ID + " > " + id_item; - - - if(DATABASE_DEBUG_MODE) - Log.d("DB_HELPER", "getAllItemsWithIdHigher SQL: " + buildSQL); - return database.rawQuery(buildSQL, null); - } - - public long getLowestItemId(boolean onlyStarred) - { - String buildSQL = "SELECT MIN(" + RSS_ITEM_RSSITEM_ID + ") FROM " + RSS_ITEM_TABLE; - - if(onlyStarred) - buildSQL += " WHERE " + RSS_ITEM_STARRED_TEMP + " = 1"; - - return getLongValueBySQL(buildSQL); - } - - public long getLowestItemIdByFeed(String id_feed) - { - String buildSQL = "SELECT MIN(" + RSS_ITEM_RSSITEM_ID + ") FROM " + RSS_ITEM_TABLE + " WHERE " + RSS_ITEM_SUBSCRIPTION_ID + " = " + id_feed; - return getLongValueBySQL(buildSQL); - } - - public long getLowestItemIdByFolder(String id_folder) - { - String buildSQL = "SELECT MIN(" + RSS_ITEM_RSSITEM_ID + ") " + - "FROM " + RSS_ITEM_TABLE + " rss " + - "JOIN " + SUBSCRIPTION_TABLE + " sc ON rss." + RSS_ITEM_SUBSCRIPTION_ID + " = sc.rowid " + - "WHERE " + SUBSCRIPTION_FOLDER_ID + " = " + id_folder; - return getLongValueBySQL(buildSQL); - } - - public long getLowestItemIdStarred() - { - String buildSQL = "SELECT MIN(" + RSS_ITEM_RSSITEM_ID + ") FROM " + RSS_ITEM_TABLE + " WHERE " + RSS_ITEM_STARRED_TEMP + " == 1"; - return getLongValueBySQL(buildSQL); - } - - public long getLowestItemIdUnread() - { - String buildSQL = "SELECT MIN(" + RSS_ITEM_RSSITEM_ID + ") FROM " + RSS_ITEM_TABLE + " WHERE " + RSS_ITEM_READ_TEMP + " != 1"; - return getLongValueBySQL(buildSQL); - } - - public long getHighestItemId() - { - String buildSQL = "SELECT MAX(" + RSS_ITEM_RSSITEM_ID + ") FROM " + RSS_ITEM_TABLE; - return getLongValueBySQL(buildSQL); - } - - public int removeAllItemsWithIdLowerThan(String id_db) - { - return database.delete(RSS_ITEM_TABLE, "rowid < ?", new String[] { id_db }); - } - - /* - public Cursor getAllData(String TABLE_NAME) { - String buildSQL = "SELECT rowid as _id, * FROM " + TABLE_NAME; - Log.d("DB_HELPER", "getAllData SQL: " + buildSQL); - return database.rawQuery(buildSQL, null); - } - */ - - public Cursor getAllTopSubscriptions(boolean onlyUnread) { - //String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE subscription_id_subscription IS NULL"; - String buildSQL = "SELECT DISTINCT(f.rowid) as _id, * FROM " + FOLDER_TABLE + " f "; - if(onlyUnread) - { - buildSQL += " JOIN " + SUBSCRIPTION_TABLE + " sc ON f.rowid = sc." + SUBSCRIPTION_FOLDER_ID + - " JOIN " + RSS_ITEM_TABLE + " rss ON sc.rowid = rss." + RSS_ITEM_SUBSCRIPTION_ID + - " WHERE " + RSS_ITEM_READ_TEMP + " != 1" + - " GROUP BY f.rowid " + - " HAVING COUNT(*) > 0"; - } - - if(DATABASE_DEBUG_MODE) - Log.d("DB_HELPER", "getAllTopSubscriptions SQL: " + buildSQL); - return database.rawQuery(buildSQL, null); - } - - public Cursor getAllTopSubscriptionsWithoutFolder(boolean onlyUnread) { - //String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE subscription_id_subscription IS NULL"; - String buildSQL = "SELECT DISTINCT(sc.rowid) as _id, * FROM " + SUBSCRIPTION_TABLE + " sc "; - - if(onlyUnread) - { - buildSQL += " JOIN " + RSS_ITEM_TABLE + " rss ON sc.rowid = rss." + RSS_ITEM_SUBSCRIPTION_ID + - " WHERE " + SUBSCRIPTION_FOLDER_ID + " IS NULL" + - " AND " + RSS_ITEM_READ_TEMP + " != 1" + - " GROUP BY sc.rowid " + - " HAVING COUNT(*) > 0"; - } - else - buildSQL += " WHERE " + SUBSCRIPTION_FOLDER_ID + " IS NULL"; - - if(DATABASE_DEBUG_MODE) - Log.d("DB_HELPER", "getAllTopSubscriptions SQL: " + buildSQL); - return database.rawQuery(buildSQL, null); - } - - /* - public Cursor getAllTopSubscriptionsWithUnreadFeeds() { - //String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE subscription_id_subscription IS NULL"; - String buildSQL = "SELECT f.rowid as _id, * FROM " + FOLDER_TABLE + " f "+ - " JOIN " + SUBSCRIPTION_TABLE + " sc ON f.rowid = sc." + SUBSCRIPTION_FOLDER_ID + - " JOIN " + RSS_ITEM_TABLE + " rss ON sc.rowid = rss." + RSS_ITEM_SUBSCRIPTION_ID + - " GROUP BY f.rowid " + - " HAVING COUNT(*) > 0"; - Log.d("DB_HELPER", "getAllTopData SQL: " + buildSQL); - return database.rawQuery(buildSQL, null); - }*/ - - - public Cursor getAllSubSubscriptions() { - //String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE subscription_id_subscription IS NOT NULL"; - String buildSQL = "SELECT DISTINCT(rowid) as _id, * FROM " + SUBSCRIPTION_TABLE; - - if(DATABASE_DEBUG_MODE) - Log.d("DB_HELPER", "getAllSubSubscriptions SQL: " + buildSQL); - return database.rawQuery(buildSQL, null); - } - - public Cursor getFeedByDbID(String ID_FEED_DB) {//Feeds - String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE rowid = '" + ID_FEED_DB + "'"; - - if(DATABASE_DEBUG_MODE) - Log.d("DB_HELPER", "getSubSubscriptionsByID SQL: " + buildSQL); - return database.rawQuery(buildSQL, null); - } - - public Cursor getFeedByFeedID(String ID_FEED) {//Feeds - String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE " + SUBSCRIPTION_ID + " = '" + ID_FEED + "'"; - - if(DATABASE_DEBUG_MODE) - Log.d("DB_HELPER", "getSubSubscriptionsByID SQL: " + buildSQL); - return database.rawQuery(buildSQL, null); - } - - public int getCountItemsForSubscription(String ID_SUBSCRIPTION, boolean onlyUnread, boolean execludeStarredItems) { - - String buildSQL = "SELECT COUNT(*) " + - " FROM " + RSS_ITEM_TABLE + - //" WHERE read != 1" + - " WHERE " + RSS_ITEM_READ_TEMP +" != 1 AND " + RSS_ITEM_STARRED + " != 1" + - " AND subscription_id_subscription IN " + - "(SELECT rowid " + - "FROM subscription " + - "WHERE rowid = " + ID_SUBSCRIPTION + ");"; - - - - if(!onlyUnread) - buildSQL = buildSQL.replace("read_temp != 1 AND", ""); - - if(!execludeStarredItems) - buildSQL = buildSQL.replace(RSS_ITEM_STARRED + " != 1 AND", RSS_ITEM_STARRED_TEMP + " = 1 AND"); - - return (int)getLongValueBySQL(buildSQL); - } - - public Boolean isFeedUnreadStarred(String FEED_ID, Boolean checkUnread) { - String buildSQL; - /* - if(checkUnread) - buildSQL = "SELECT read "; - else//Wenn nicht checkRead auf true steht, soll geprueft werden ob das Feed Markiert ist. - buildSQL = "SELECT starred "; - */ - - if(checkUnread) - buildSQL = "SELECT read_temp "; - else//Wenn nicht checkRead auf true steht, soll geprueft werden ob das Feed Markiert ist. - buildSQL = "SELECT starred_temp "; - - buildSQL += " FROM " + RSS_ITEM_TABLE + - " WHERE rowid = " + FEED_ID; - - return checkSqlForBoolean(buildSQL); - } - - private Boolean checkSqlForBoolean(String buildSQL) - { - Boolean result = false; - Cursor cursor = database.rawQuery(buildSQL, null); - if (cursor != null) - { - if(cursor.moveToFirst()) - { - String val = cursor.getString(0); - if(val != null) - if(val.equals("1")) - result = true; - } - } - cursor.close(); - - return result; - } - - public void updateIsReadOfFeed(String FEED_ID, Boolean isRead) { - ContentValues args = new ContentValues(); - //args.put(RSS_ITEM_READ, isRead); - args.put(RSS_ITEM_READ_TEMP, isRead); - int result = database.update(RSS_ITEM_TABLE, args, "rowid=?", new String[] { FEED_ID }); - - if(DATABASE_DEBUG_MODE) - Log.d("RESULT UPDATE DATABASE", "RESULT: " + result); - } - - public void updateIsStarredOfFeed(String FEED_ID, Boolean isStarred) { - - if(isStarred)//Wenn ein Feed markiert ist muss es auch als gelesen markiert werden. - updateIsReadOfFeed(FEED_ID, true); - - - ContentValues args = new ContentValues(); - //args.put(RSS_ITEM_STARRED, isStarred); - args.put(RSS_ITEM_STARRED_TEMP, isStarred); - int result = database.update(RSS_ITEM_TABLE, args, "rowid=?", new String[] { FEED_ID }); - - if(DATABASE_DEBUG_MODE) - Log.d("RESULT UPDATE DATABASE", "RESULT: " + result); - } - - private String getAllFeedsSelectStatement() - { - return "SELECT DISTINCT(rowid) as _id, " + RSS_ITEM_TITLE + ", " + RSS_ITEM_RSSITEM_ID + ", " + RSS_ITEM_LINK + ", " + RSS_ITEM_BODY + ", " + RSS_ITEM_READ + ", " + RSS_ITEM_SUBSCRIPTION_ID + ", " - + RSS_ITEM_PUBDATE + ", " + RSS_ITEM_STARRED + ", " + RSS_ITEM_GUIDHASH + ", " + RSS_ITEM_GUID + ", " + RSS_ITEM_STARRED_TEMP + ", " + RSS_ITEM_READ_TEMP; - } - - public Cursor getAllItemsForFeed(String ID_SUBSCRIPTION, boolean onlyUnread, boolean onlyStarredItems) { - - String buildSQL = getAllFeedsSelectStatement() + - " FROM " + RSS_ITEM_TABLE + - " WHERE subscription_id_subscription IN " + - "(SELECT rowid " + - "FROM subscription " + - "WHERE rowid = " + ID_SUBSCRIPTION + ")"; - - if(onlyUnread && !onlyStarredItems) - buildSQL += " AND " + RSS_ITEM_READ_TEMP + " != 1"; - else if(onlyStarredItems) - buildSQL += " AND " + RSS_ITEM_STARRED_TEMP + " = 1"; - - buildSQL += " ORDER BY " + RSS_ITEM_PUBDATE + " desc"; - - if(DATABASE_DEBUG_MODE) - Log.d("DB_HELPER", "getAllItemsForFeed SQL: " + buildSQL); - return database.rawQuery(buildSQL, null); - } - - public Cursor getArticleByID(String ID_FEED) { - String buildSQL = getAllFeedsSelectStatement() + - " FROM " + RSS_ITEM_TABLE + - " WHERE rowid = " + ID_FEED; - - if(DATABASE_DEBUG_MODE) - Log.d("DB_HELPER", "getFeedByID SQL: " + buildSQL); - return database.rawQuery(buildSQL, null); - } - - public String getRowIdOfFeedByItemID(String ID_FEED) - { - String buildSQL = "SELECT rowid " + - " FROM " + RSS_ITEM_TABLE + - " WHERE " + RSS_ITEM_RSSITEM_ID + " = " + ID_FEED; - - return getStringValueBySQL(buildSQL); - } - - /* - public String getCountUnreadFeedsForFolder(String ID_FOLDER, boolean onlyUnread) { //TODO optimize this here !!!! - String buildSQL = "SELECT COUNT(*) " + - " FROM " + RSS_ITEM_TABLE + - " WHERE " + RSS_ITEM_READ_TEMP + " != 1 "; - if(!ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS)) - buildSQL += " AND subscription_id_subscription IN " + - "(SELECT sc.rowid " + - "FROM subscription sc " + - "JOIN folder f ON sc." + SUBSCRIPTION_FOLDER_ID + " = f.rowid " + - "WHERE f.rowid = " + ID_FOLDER + ")"; - - if(onlyUnread) - buildSQL += " AND "; - String result = "0"; - Cursor cursor = database.rawQuery(buildSQL, null); - if (cursor != null) - { - if(cursor.moveToFirst()) - result = cursor.getString(0); - } - cursor.close(); - - return result; - }*/ - - public int getCountFeedsForFolder(String ID_FOLDER, boolean onlyUnread) { - - Cursor cursor = getAllItemsForFolder(ID_FOLDER, onlyUnread); - int count = cursor.getCount(); - cursor.close(); - - return count; - - - } - /* - public String getCountFeedsForFolder(String ID_FOLDER, boolean onlyUnread) { - String buildSQL = "SELECT COUNT(*) " + - " FROM " + RSS_ITEM_TABLE; - - if(!(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS) || ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS))) - { - buildSQL += " WHERE subscription_id_subscription IN " + - "(SELECT sc.rowid " + - "FROM subscription sc " + - "JOIN folder f ON sc." + SUBSCRIPTION_FOLDER_ID + " = f.rowid " + - "WHERE f.rowid = " + ID_FOLDER + ") "; - - if(onlyUnread) - buildSQL += " AND read_temp != 1"; - } - else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS))//UNREAD - buildSQL += " WHERE starred != 1 and read_temp != 1"; - else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS))//STARRED - buildSQL += " WHERE starred_temp = 1"; - // buildSQL += " WHERE starred = 1"; - - - - String result = "0"; - Cursor cursor = database.rawQuery(buildSQL, null); - if (cursor != null) - { - if(cursor.moveToFirst()) - result = cursor.getString(0); - } - cursor.close(); - - return result; - }*/ - - public Cursor getAllItemsForFolder(String ID_FOLDER, boolean onlyUnread) { - String buildSQL = getAllFeedsSelectStatement() + - " FROM " + RSS_ITEM_TABLE; - - if(!(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS) || ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS)))//Wenn nicht Alle Artikel ausgewaehlt wurde (-10) oder (-11) fuer Starred Feeds - { - buildSQL += " WHERE subscription_id_subscription IN " + - "(SELECT sc.rowid " + - "FROM subscription sc " + - "JOIN folder f ON sc." + SUBSCRIPTION_FOLDER_ID + " = f.rowid " + - "WHERE f.rowid = " + ID_FOLDER + ")"; - - if(onlyUnread) - buildSQL += " AND " + RSS_ITEM_READ_TEMP + " != 1"; - } - //else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS) && onlyUnread)//only unRead should only be null when testing the size of items - else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS)) - buildSQL += " WHERE " + RSS_ITEM_STARRED_TEMP + " != 1 AND " + RSS_ITEM_READ_TEMP + " != 1"; - //else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS)) - // buildSQL += " WHERE " + RSS_ITEM_STARRED + " != 1"; - //else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS) && onlyUnread) - // buildSQL += " WHERE " + RSS_ITEM_STARRED_TEMP + " = 1 AND " + RSS_ITEM_READ_TEMP + " != 1"; - else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS)) - buildSQL += " WHERE " + RSS_ITEM_STARRED_TEMP + " = 1"; - - - buildSQL += " ORDER BY " + RSS_ITEM_PUBDATE + " desc"; - - // buildSQL += " WHERE starred = 1"; - - if(DATABASE_DEBUG_MODE) - Log.d("DB_HELPER", "getAllFeedData SQL: " + buildSQL); - return database.rawQuery(buildSQL, null); - } - - public Cursor getAllSubscriptionForFolder(String ID_FOLDER, boolean onlyUnread) { - //String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE " + SUBSCRIPTION_SUBSCRIPTION_ID + "=" + ID_SUBSCRIPTION; - String buildSQL = "SELECT sc.rowid as _id, sc.* " + - "FROM " + SUBSCRIPTION_TABLE + " sc " + - "LEFT OUTER JOIN folder f ON sc.folder_idfolder = f.rowid "; - - if(ID_FOLDER.equals("-11"))//Starred - { - buildSQL += " JOIN " + RSS_ITEM_TABLE + " rss ON sc.rowid = rss." + RSS_ITEM_SUBSCRIPTION_ID + - " WHERE rss." + RSS_ITEM_STARRED_TEMP + " = 1" + - " GROUP BY sc.rowid " + - " HAVING COUNT(*) > 0"; - } - else if(onlyUnread || ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS) /*ID_SUBSCRIPTION.matches("-10|-11")*/) - { - buildSQL += " JOIN " + RSS_ITEM_TABLE + " rss ON sc.rowid = rss." + RSS_ITEM_SUBSCRIPTION_ID + - " WHERE f.rowid = " + ID_FOLDER + " AND rss." + RSS_ITEM_READ_TEMP + " != 1" + - " GROUP BY sc.rowid " + - " HAVING COUNT(*) > 0"; - - if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS)) - buildSQL = buildSQL.replace("f.rowid = " + ID_FOLDER + " AND", "");//Remove to ID stuff because i want the result of all feeds where are unread items in - } - else - buildSQL += "WHERE f.rowid = " + ID_FOLDER; - - if(DATABASE_DEBUG_MODE) - Log.d("DB_HELPER", "getAllSub_SubscriptionForSubscription SQL: " + buildSQL); - return database.rawQuery(buildSQL, null); - } - - public void insertNewFolder (String label, String label_path) { - ContentValues contentValues = new ContentValues(); - contentValues.put(FOLDER_LABEL, label); - contentValues.put(FOLDER_LABEL_ID, label_path); - database.insert(FOLDER_TABLE, null, contentValues); - } - - /* - public int updateFolder (String label, String label_path) { - ContentValues contentValues = new ContentValues(); - contentValues.put(FOLDER_LABEL, label); - return database.update(FOLDER_TABLE, contentValues, FOLDER_LABEL_ID + "=?", new String[] { label_path }); - }*/ - - public void insertNewFeed (String headerText, String ID_FOLDER, String subscription_id, String FAVICON_URL) { - ContentValues contentValues = new ContentValues(); - contentValues.put(SUBSCRIPTION_HEADERTEXT, headerText); - contentValues.put(SUBSCRIPTION_FOLDER_ID, ID_FOLDER); - contentValues.put(SUBSCRIPTION_ID , subscription_id); - contentValues.put(SUBSCRIPTION_FAVICON_URL, FAVICON_URL); - database.insert(SUBSCRIPTION_TABLE, null, contentValues); - } - - public int updateFeed (String headerText, String ID_FOLDER, String subscription_id, String FAVICON_URL) { - ContentValues contentValues = new ContentValues(); - contentValues.put(SUBSCRIPTION_HEADERTEXT, headerText); - contentValues.put(SUBSCRIPTION_FOLDER_ID, ID_FOLDER); - contentValues.put(SUBSCRIPTION_FAVICON_URL, FAVICON_URL); - return database.update(SUBSCRIPTION_TABLE, contentValues, SUBSCRIPTION_ID + "= ?", new String[] { subscription_id }); - } - - public void insertNewItem (String Titel, String link, String description, Boolean isRead, String ID_SUBSCRIPTION, String ID_RSSITEM, Date timestamp, Boolean isStarred, String guid, String guidHash, String lastModified) { - ContentValues contentValues = new ContentValues(); - contentValues.put(RSS_ITEM_TITLE, Titel); - contentValues.put(RSS_ITEM_LINK, link); - contentValues.put(RSS_ITEM_BODY, description); - contentValues.put(RSS_ITEM_READ, isRead); - contentValues.put(RSS_ITEM_SUBSCRIPTION_ID, ID_SUBSCRIPTION); - contentValues.put(RSS_ITEM_RSSITEM_ID, ID_RSSITEM); - contentValues.put(RSS_ITEM_PUBDATE, timestamp.getTime()); - contentValues.put(RSS_ITEM_STARRED, isStarred); - contentValues.put(RSS_ITEM_GUID, guid); - contentValues.put(RSS_ITEM_GUIDHASH, guidHash); - contentValues.put(RSS_ITEM_LAST_MODIFIED, lastModified); - - contentValues.put(RSS_ITEM_READ_TEMP, isRead); - contentValues.put(RSS_ITEM_STARRED_TEMP, isStarred); - - database.insert(RSS_ITEM_TABLE, null, contentValues); - } - - public String getIdOfFolder (String FolderName) { - //String buildSQL = "SELECT rowid as _id FROM " + SUBSCRIPTION_TABLE + " WHERE " + SUBSCRIPTION_HEADERTEXT + " = '" + SubscriptionName + "'"; - String buildSQL = "SELECT rowid as _id FROM " + FOLDER_TABLE + " WHERE " + FOLDER_LABEL + " = '" + FolderName + "'"; - - return getStringValueBySQL(buildSQL); - } - - public String getIdOfFolderByLabelPath (String FolderLabelPath) { - //String buildSQL = "SELECT rowid as _id FROM " + SUBSCRIPTION_TABLE + " WHERE " + SUBSCRIPTION_HEADERTEXT + " = '" + SubscriptionName + "'"; - String buildSQL = "SELECT rowid as _id FROM " + FOLDER_TABLE + " WHERE " + FOLDER_LABEL_ID + " = '" + FolderLabelPath + "'"; - - return getStringValueBySQL(buildSQL); - } - - public String getRowIdBySubscriptionID (String StreamID) { - //String buildSQL = "SELECT rowid as _id FROM " + SUBSCRIPTION_TABLE + " WHERE " + SUBSCRIPTION_HEADERTEXT + " = '" + SubscriptionName + "'"; - String buildSQL = "SELECT rowid as _id FROM " + SUBSCRIPTION_TABLE + " WHERE " + SUBSCRIPTION_ID + " = '" + StreamID + "'"; - return getStringValueBySQL(buildSQL); - } - - public String getSubscriptionIdByRowID (String ID) { - - String buildSQL = "SELECT " + SUBSCRIPTION_ID + " FROM " + SUBSCRIPTION_TABLE + " WHERE rowid = '" + ID + "'"; - return getStringValueBySQL(buildSQL); - } - - public String getTitleOfFolderByID (String FolderID) { - //String buildSQL = "SELECT " + SUBSCRIPTION_HEADERTEXT + " FROM " + SUBSCRIPTION_TABLE + " WHERE rowid = '" + SubscriptionID + "'"; - String buildSQL = "SELECT " + FOLDER_LABEL + " FROM " + FOLDER_TABLE + " WHERE rowid = '" + FolderID + "'"; - return getStringValueBySQL(buildSQL); - } - - public String getTitleOfSubscriptionByRowID (String SubscriptionID) { - String buildSQL = "SELECT " + SUBSCRIPTION_HEADERTEXT + " FROM " + SUBSCRIPTION_TABLE + " WHERE rowid = '" + SubscriptionID + "'"; - return getStringValueBySQL(buildSQL); - } - - public String getTitleOfSubscriptionByFeedItemID (String SubscriptionID) { - String buildSQL = "SELECT " + SUBSCRIPTION_HEADERTEXT + " FROM " + SUBSCRIPTION_TABLE + " sc " + - "JOIN " + RSS_ITEM_TABLE + " rss ON sc.rowid = rss." + RSS_ITEM_SUBSCRIPTION_ID + " " + - "WHERE rss.rowid = '" + SubscriptionID + "'"; - return getStringValueBySQL(buildSQL); - } - - public int removeTopSubscriptionItemByTag(String TAG) - { - return database.delete(SUBSCRIPTION_TABLE, SUBSCRIPTION_HEADERTEXT + " = ?", new String[] { TAG }); - } - - public int removeFolderByFolderLabel(String FolderLabel) - { - return database.delete(FOLDER_TABLE, FOLDER_LABEL + " = ?", new String[] { FolderLabel }); - } - - public int removeItemByItemId(String idRssItem) - { - return database.delete(RSS_ITEM_TABLE, RSS_ITEM_RSSITEM_ID + " = ?", new String[] { idRssItem }); - } - - public List convertCursorToStringArray(Cursor cursor, int column_id) - { - List items = new ArrayList(); - try - { - if(cursor != null) - { - if(cursor.getCount() > 0) - { - cursor.moveToFirst(); - do { - items.add(cursor.getString(column_id)); - } while(cursor.moveToNext()); - } - } - } finally { - cursor.close(); - } - return items; - - } - - private String getStringValueBySQL(String buildSQL) - { - String result = null; - - Cursor cursor = database.rawQuery(buildSQL, null); - try - { - if(cursor != null) - { - if(cursor.moveToFirst()) - result = cursor.getString(0); - } - } finally { - cursor.close(); - } - - return result; - } - - public long getLongValueBySQL(String buildSQL) - { - long result = -1; - - Cursor cursor = database.rawQuery(buildSQL, null); - try - { - if(cursor != null) - { - if(cursor.moveToFirst()) - result = cursor.getLong(0); - } - } finally { - cursor.close(); - } - - return result; - } - - public Boolean doesRssItemAlreadyExsists(String idRssItem)//idRssItem = id aus dem Google Reader Stream - { - String buildSQL = "SELECT " + RSS_ITEM_TITLE + " FROM " + RSS_ITEM_TABLE + " WHERE " + RSS_ITEM_RSSITEM_ID + " = '" + idRssItem + "'"; - Cursor cursor = database.rawQuery(buildSQL, null); - int count = cursor.getCount(); - cursor.close(); - if(count > 0) - return true; - else - return false; - } - - public int resetRssItemsDatabase() - { - int result = database.delete(RSS_ITEM_TABLE, null, null); - return result; - } - - public void resetDatabase() - { - openHelper.resetDatabase(database); - } - - public void openDatabase() - { - database = openHelper.getWritableDatabase(); - } - - public void closeDatabase() - { - database.close(); - } -} +package de.luhmer.owncloudnewsreader.database; + +import java.util.ArrayList; +import java.util.Date; +import java.util.List; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.sqlite.SQLiteDatabase; +import android.util.Log; +import de.luhmer.owncloudnewsreader.Constants; +import de.luhmer.owncloudnewsreader.ListView.SubscriptionExpandableListAdapter; + +public class DatabaseConnection { + private DatabaseHelper openHelper; + private SQLiteDatabase database; + + public static final String FOLDER_TABLE = "folder"; + public static final String FOLDER_LABEL = "label"; + public static final String FOLDER_LABEL_ID = "label_id"; + + public static final String SUBSCRIPTION_TABLE = "subscription"; + public static final String SUBSCRIPTION_HEADERTEXT = "header_text"; + //public static final String SUBSCRIPTION_SUBSCRIPTION_ID = "subscription_id_subscription"; + public static final String SUBSCRIPTION_FOLDER_ID = "folder_idfolder"; + public static final String SUBSCRIPTION_ID = "subscription_id"; + public static final String SUBSCRIPTION_FAVICON_URL = "favicon_url"; + public static final String SUBSCRIPTION_LINK = "link"; + + public static final String RSS_ITEM_TABLE = "rss_item"; + public static final String RSS_ITEM_SUBSCRIPTION_ID = "subscription_id_subscription"; + public static final String RSS_ITEM_TITLE = "title"; + public static final String RSS_ITEM_LINK = "link"; + public static final String RSS_ITEM_BODY = "body"; + public static final String RSS_ITEM_READ = "read"; + public static final String RSS_ITEM_RSSITEM_ID = "rssitem_id"; + public static final String RSS_ITEM_STARRED = "starred"; + public static final String RSS_ITEM_PUBDATE = "pubdate"; + public static final String RSS_ITEM_AUTHOR = "author"; + public static final String RSS_ITEM_GUID = "guid"; + public static final String RSS_ITEM_GUIDHASH = "guidHash"; + public static final String RSS_ITEM_LAST_MODIFIED = "lastModified"; + + public static final String RSS_ITEM_READ_TEMP = "read_temp"; + public static final String RSS_ITEM_STARRED_TEMP = "starred_temp"; + + + public static final boolean DATABASE_DEBUG_MODE = false; //(false && Constants.DEBUG_MODE) ? true: false; + + + public DatabaseConnection(Context aContext) { + openHelper = new DatabaseHelper(aContext); + openDatabase(); + } + + public SQLiteDatabase getDatabase() + { + return database; + } + + + public void clearDatabaseOverSize() + { + //If i have 9023 rows in the database, when i run that query it should delete 8023 rows and leave me with 1000 + //database.execSQL("DELETE FROM " + RSS_ITEM_TABLE + " WHERE " + + "ORDER BY rowid DESC LIMIT 1000 * + + //Let's say it said 1005 - you need to delete 5 rows. + //DELETE FROM table ORDER BY dateRegistered ASC LIMIT 5 + + + int max = Constants.maxItemsCount; + int total = (int) getLongValueBySQL("SELECT COUNT(*) FROM rss_item"); + int unread = (int) getLongValueBySQL("SELECT COUNT(*) FROM rss_item WHERE read_temp != 1"); + int read = total - unread; + + if(total > max) + { + int overSize = total - max; + //Soll verhindern, dass ungelesene Artikel gelöscht werden + if(overSize > read) + overSize = read; + database.execSQL("DELETE FROM rss_item WHERE read_temp = 1 AND rowid IN (SELECT rowid FROM rss_item WHERE read_temp = 1 ORDER BY rowid asc LIMIT " + overSize + ")"); + /* SELECT * FROM rss_item WHERE read_temp = 1 ORDER BY rowid asc LIMIT 3; */ + } + } + + public void markAllItemsAsRead(List itemIds) + { + if(itemIds != null) + for(Integer idItem : itemIds) + updateIsReadOfFeed(String.valueOf(idItem), true); + } + + public int getCountOfAllItems(boolean execludeStarred) + { + String buildSQL = "SELECT count(*) FROM " + RSS_ITEM_TABLE; + if(execludeStarred) + buildSQL += " WHERE " + RSS_ITEM_STARRED_TEMP + " != 1"; + + int result = 0; + + Cursor cursor = database.rawQuery(buildSQL, null); + try + { + if(cursor != null) + { + cursor.moveToFirst(); + result = cursor.getInt(0); + } + } finally { + cursor.close(); + } + + return result; + } + + public long getLastModfied() + { + String buildSQL = "SELECT MAX(" + RSS_ITEM_LAST_MODIFIED + ") FROM " + RSS_ITEM_TABLE; + long result = 0; + + Cursor cursor = database.rawQuery(buildSQL, null); + try + { + if(cursor != null) + { + cursor.moveToFirst(); + result = cursor.getLong(0); + } + } finally { + cursor.close(); + } + + return result; + } + + public long getItemDbIdAtPosition(int positionXRow) + { + String buildSQL = "SELECT rowid FROM " + RSS_ITEM_TABLE; + long result = -1; + + Cursor cursor = database.rawQuery(buildSQL, null); + try + { + if(cursor != null) + { + if(cursor.move(cursor.getCount() - (positionXRow - 1))) + result = cursor.getLong(0); + } + } finally { + cursor.close(); + } + + return result; + } + + public List getAllNewReadItems() + { + String buildSQL = "SELECT " + RSS_ITEM_RSSITEM_ID + " FROM " + RSS_ITEM_TABLE + " WHERE " + + RSS_ITEM_READ_TEMP + " = 1 AND " + + RSS_ITEM_READ + " = 0"; + Cursor cursor = database.rawQuery(buildSQL, null); + return convertCursorToStringArray(cursor, 0); + } + + public List getAllNewUnreadItems() + { + String buildSQL = "SELECT " + RSS_ITEM_RSSITEM_ID + " FROM " + RSS_ITEM_TABLE + " WHERE " + + RSS_ITEM_READ_TEMP + " = 0 AND " + + RSS_ITEM_READ + " = 1"; + Cursor cursor = database.rawQuery(buildSQL, null); + return convertCursorToStringArray(cursor, 0); + } + + public List getAllNewStarredItems() + { + String buildSQL = "SELECT " + RSS_ITEM_RSSITEM_ID + " FROM " + RSS_ITEM_TABLE + " WHERE " + + RSS_ITEM_STARRED_TEMP + " = 1 AND " + + RSS_ITEM_STARRED + " = 0"; + Cursor cursor = database.rawQuery(buildSQL, null); + return convertCursorToStringArray(cursor, 0); + } + + public List getAllNewUnstarredItems() + { + String buildSQL = "SELECT " + RSS_ITEM_RSSITEM_ID + " FROM " + RSS_ITEM_TABLE + " WHERE " + + RSS_ITEM_STARRED_TEMP + " = 0 AND " + + RSS_ITEM_STARRED + " = 1"; + Cursor cursor = database.rawQuery(buildSQL, null); + return convertCursorToStringArray(cursor, 0); + } + + public Cursor getAllItemsWithIdHigher(String id_item) { + //String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE subscription_id_subscription IS NULL"; + String buildSQL = "SELECT rowid as _id, * FROM " + RSS_ITEM_TABLE + " WHERE " + RSS_ITEM_RSSITEM_ID + " > " + id_item; + + + if(DATABASE_DEBUG_MODE) + Log.d("DB_HELPER", "getAllItemsWithIdHigher SQL: " + buildSQL); + return database.rawQuery(buildSQL, null); + } + + public long getLowestItemId(boolean onlyStarred) + { + String buildSQL = "SELECT MIN(" + RSS_ITEM_RSSITEM_ID + ") FROM " + RSS_ITEM_TABLE; + + if(onlyStarred) + buildSQL += " WHERE " + RSS_ITEM_STARRED_TEMP + " = 1"; + + return getLongValueBySQL(buildSQL); + } + + public long getLowestItemIdByFeed(String id_feed) + { + String buildSQL = "SELECT MIN(" + RSS_ITEM_RSSITEM_ID + ") FROM " + RSS_ITEM_TABLE + " WHERE " + RSS_ITEM_SUBSCRIPTION_ID + " = " + id_feed; + return getLongValueBySQL(buildSQL); + } + + public long getLowestItemIdByFolder(String id_folder) + { + String buildSQL = "SELECT MIN(" + RSS_ITEM_RSSITEM_ID + ") " + + "FROM " + RSS_ITEM_TABLE + " rss " + + "JOIN " + SUBSCRIPTION_TABLE + " sc ON rss." + RSS_ITEM_SUBSCRIPTION_ID + " = sc.rowid " + + "WHERE " + SUBSCRIPTION_FOLDER_ID + " = " + id_folder; + return getLongValueBySQL(buildSQL); + } + + public long getLowestItemIdStarred() + { + String buildSQL = "SELECT MIN(" + RSS_ITEM_RSSITEM_ID + ") FROM " + RSS_ITEM_TABLE + " WHERE " + RSS_ITEM_STARRED_TEMP + " == 1"; + return getLongValueBySQL(buildSQL); + } + + public long getLowestItemIdUnread() + { + String buildSQL = "SELECT MIN(" + RSS_ITEM_RSSITEM_ID + ") FROM " + RSS_ITEM_TABLE + " WHERE " + RSS_ITEM_READ_TEMP + " != 1"; + return getLongValueBySQL(buildSQL); + } + + public long getHighestItemId() + { + String buildSQL = "SELECT MAX(" + RSS_ITEM_RSSITEM_ID + ") FROM " + RSS_ITEM_TABLE; + return getLongValueBySQL(buildSQL); + } + + public int removeAllItemsWithIdLowerThan(String id_db) + { + return database.delete(RSS_ITEM_TABLE, "rowid < ?", new String[] { id_db }); + } + + /* + public Cursor getAllData(String TABLE_NAME) { + String buildSQL = "SELECT rowid as _id, * FROM " + TABLE_NAME; + Log.d("DB_HELPER", "getAllData SQL: " + buildSQL); + return database.rawQuery(buildSQL, null); + } + */ + + public Cursor getAllTopSubscriptions(boolean onlyUnread) { + //String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE subscription_id_subscription IS NULL"; + String buildSQL = "SELECT DISTINCT(f.rowid) as _id, * FROM " + FOLDER_TABLE + " f "; + if(onlyUnread) + { + buildSQL += " JOIN " + SUBSCRIPTION_TABLE + " sc ON f.rowid = sc." + SUBSCRIPTION_FOLDER_ID + + " JOIN " + RSS_ITEM_TABLE + " rss ON sc.rowid = rss." + RSS_ITEM_SUBSCRIPTION_ID + + " WHERE " + RSS_ITEM_READ_TEMP + " != 1" + + " GROUP BY f.rowid " + + " HAVING COUNT(*) > 0"; + } + + if(DATABASE_DEBUG_MODE) + Log.d("DB_HELPER", "getAllTopSubscriptions SQL: " + buildSQL); + return database.rawQuery(buildSQL, null); + } + + public Cursor getAllTopSubscriptionsWithoutFolder(boolean onlyUnread) { + //String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE subscription_id_subscription IS NULL"; + String buildSQL = "SELECT DISTINCT(sc.rowid) as _id, * FROM " + SUBSCRIPTION_TABLE + " sc "; + + if(onlyUnread) + { + buildSQL += " JOIN " + RSS_ITEM_TABLE + " rss ON sc.rowid = rss." + RSS_ITEM_SUBSCRIPTION_ID + + " WHERE " + SUBSCRIPTION_FOLDER_ID + " IS NULL" + + " AND " + RSS_ITEM_READ_TEMP + " != 1" + + " GROUP BY sc.rowid " + + " HAVING COUNT(*) > 0"; + } + else + buildSQL += " WHERE " + SUBSCRIPTION_FOLDER_ID + " IS NULL"; + + if(DATABASE_DEBUG_MODE) + Log.d("DB_HELPER", "getAllTopSubscriptions SQL: " + buildSQL); + return database.rawQuery(buildSQL, null); + } + + /* + public Cursor getAllTopSubscriptionsWithUnreadFeeds() { + //String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE subscription_id_subscription IS NULL"; + String buildSQL = "SELECT f.rowid as _id, * FROM " + FOLDER_TABLE + " f "+ + " JOIN " + SUBSCRIPTION_TABLE + " sc ON f.rowid = sc." + SUBSCRIPTION_FOLDER_ID + + " JOIN " + RSS_ITEM_TABLE + " rss ON sc.rowid = rss." + RSS_ITEM_SUBSCRIPTION_ID + + " GROUP BY f.rowid " + + " HAVING COUNT(*) > 0"; + Log.d("DB_HELPER", "getAllTopData SQL: " + buildSQL); + return database.rawQuery(buildSQL, null); + }*/ + + + public Cursor getAllSubSubscriptions() { + //String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE subscription_id_subscription IS NOT NULL"; + String buildSQL = "SELECT DISTINCT(rowid) as _id, * FROM " + SUBSCRIPTION_TABLE; + + if(DATABASE_DEBUG_MODE) + Log.d("DB_HELPER", "getAllSubSubscriptions SQL: " + buildSQL); + return database.rawQuery(buildSQL, null); + } + + public Cursor getFeedByDbID(String ID_FEED_DB) {//Feeds + String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE rowid = '" + ID_FEED_DB + "'"; + + if(DATABASE_DEBUG_MODE) + Log.d("DB_HELPER", "getSubSubscriptionsByID SQL: " + buildSQL); + return database.rawQuery(buildSQL, null); + } + + public Cursor getFeedByFeedID(String ID_FEED) {//Feeds + String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE " + SUBSCRIPTION_ID + " = '" + ID_FEED + "'"; + + if(DATABASE_DEBUG_MODE) + Log.d("DB_HELPER", "getSubSubscriptionsByID SQL: " + buildSQL); + return database.rawQuery(buildSQL, null); + } + + public int getCountItemsForSubscription(String ID_SUBSCRIPTION, boolean onlyUnread, boolean execludeStarredItems) { + + String buildSQL = "SELECT COUNT(*) " + + " FROM " + RSS_ITEM_TABLE + + //" WHERE read != 1" + + " WHERE " + RSS_ITEM_READ_TEMP +" != 1 AND " + RSS_ITEM_STARRED + " != 1" + + " AND subscription_id_subscription IN " + + "(SELECT rowid " + + "FROM subscription " + + "WHERE rowid = " + ID_SUBSCRIPTION + ");"; + + + + if(!onlyUnread) + buildSQL = buildSQL.replace("read_temp != 1 AND", ""); + + if(!execludeStarredItems) + buildSQL = buildSQL.replace(RSS_ITEM_STARRED + " != 1 AND", RSS_ITEM_STARRED_TEMP + " = 1 AND"); + + return (int)getLongValueBySQL(buildSQL); + } + + public Boolean isFeedUnreadStarred(String FEED_ID, Boolean checkUnread) { + String buildSQL; + /* + if(checkUnread) + buildSQL = "SELECT read "; + else//Wenn nicht checkRead auf true steht, soll geprueft werden ob das Feed Markiert ist. + buildSQL = "SELECT starred "; + */ + + if(checkUnread) + buildSQL = "SELECT read_temp "; + else//Wenn nicht checkRead auf true steht, soll geprueft werden ob das Feed Markiert ist. + buildSQL = "SELECT starred_temp "; + + buildSQL += " FROM " + RSS_ITEM_TABLE + + " WHERE rowid = " + FEED_ID; + + return checkSqlForBoolean(buildSQL); + } + + private Boolean checkSqlForBoolean(String buildSQL) + { + Boolean result = false; + Cursor cursor = database.rawQuery(buildSQL, null); + if (cursor != null) + { + if(cursor.moveToFirst()) + { + String val = cursor.getString(0); + if(val != null) + if(val.equals("1")) + result = true; + } + } + cursor.close(); + + return result; + } + + public void updateIsReadOfFeed(String FEED_ID, Boolean isRead) { + ContentValues args = new ContentValues(); + //args.put(RSS_ITEM_READ, isRead); + args.put(RSS_ITEM_READ_TEMP, isRead); + int result = database.update(RSS_ITEM_TABLE, args, "rowid=?", new String[] { FEED_ID }); + + if(DATABASE_DEBUG_MODE) + Log.d("RESULT UPDATE DATABASE", "RESULT: " + result); + } + + public void updateIsStarredOfFeed(String FEED_ID, Boolean isStarred) { + + if(isStarred)//Wenn ein Feed markiert ist muss es auch als gelesen markiert werden. + updateIsReadOfFeed(FEED_ID, true); + + + ContentValues args = new ContentValues(); + //args.put(RSS_ITEM_STARRED, isStarred); + args.put(RSS_ITEM_STARRED_TEMP, isStarred); + int result = database.update(RSS_ITEM_TABLE, args, "rowid=?", new String[] { FEED_ID }); + + if(DATABASE_DEBUG_MODE) + Log.d("RESULT UPDATE DATABASE", "RESULT: " + result); + } + + private String getAllFeedsSelectStatement() + { + return "SELECT DISTINCT(rowid) as _id, " + RSS_ITEM_TITLE + ", " + RSS_ITEM_RSSITEM_ID + ", " + RSS_ITEM_LINK + ", " + RSS_ITEM_BODY + ", " + RSS_ITEM_READ + ", " + RSS_ITEM_SUBSCRIPTION_ID + ", " + + RSS_ITEM_PUBDATE + ", " + RSS_ITEM_STARRED + ", " + RSS_ITEM_GUIDHASH + ", " + RSS_ITEM_GUID + ", " + RSS_ITEM_STARRED_TEMP + ", " + RSS_ITEM_READ_TEMP; + } + + public Cursor getAllItemsForFeed(String ID_SUBSCRIPTION, boolean onlyUnread, boolean onlyStarredItems) { + + String buildSQL = getAllFeedsSelectStatement() + + " FROM " + RSS_ITEM_TABLE + + " WHERE subscription_id_subscription IN " + + "(SELECT rowid " + + "FROM subscription " + + "WHERE rowid = " + ID_SUBSCRIPTION + ")"; + + if(onlyUnread && !onlyStarredItems) + buildSQL += " AND " + RSS_ITEM_READ_TEMP + " != 1"; + else if(onlyStarredItems) + buildSQL += " AND " + RSS_ITEM_STARRED_TEMP + " = 1"; + + buildSQL += " ORDER BY " + RSS_ITEM_PUBDATE + " desc"; + + if(DATABASE_DEBUG_MODE) + Log.d("DB_HELPER", "getAllItemsForFeed SQL: " + buildSQL); + return database.rawQuery(buildSQL, null); + } + + public Cursor getArticleByID(String ID_FEED) { + String buildSQL = getAllFeedsSelectStatement() + + " FROM " + RSS_ITEM_TABLE + + " WHERE rowid = " + ID_FEED; + + if(DATABASE_DEBUG_MODE) + Log.d("DB_HELPER", "getFeedByID SQL: " + buildSQL); + return database.rawQuery(buildSQL, null); + } + + public String getRowIdOfFeedByItemID(String ID_FEED) + { + String buildSQL = "SELECT rowid " + + " FROM " + RSS_ITEM_TABLE + + " WHERE " + RSS_ITEM_RSSITEM_ID + " = " + ID_FEED; + + return getStringValueBySQL(buildSQL); + } + + /* + public String getCountUnreadFeedsForFolder(String ID_FOLDER, boolean onlyUnread) { //TODO optimize this here !!!! + String buildSQL = "SELECT COUNT(*) " + + " FROM " + RSS_ITEM_TABLE + + " WHERE " + RSS_ITEM_READ_TEMP + " != 1 "; + if(!ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS)) + buildSQL += " AND subscription_id_subscription IN " + + "(SELECT sc.rowid " + + "FROM subscription sc " + + "JOIN folder f ON sc." + SUBSCRIPTION_FOLDER_ID + " = f.rowid " + + "WHERE f.rowid = " + ID_FOLDER + ")"; + + if(onlyUnread) + buildSQL += " AND "; + String result = "0"; + Cursor cursor = database.rawQuery(buildSQL, null); + if (cursor != null) + { + if(cursor.moveToFirst()) + result = cursor.getString(0); + } + cursor.close(); + + return result; + }*/ + + public int getCountFeedsForFolder(String ID_FOLDER, boolean onlyUnread) { + + Cursor cursor = getAllItemsForFolder(ID_FOLDER, onlyUnread); + int count = cursor.getCount(); + cursor.close(); + + return count; + + + } + /* + public String getCountFeedsForFolder(String ID_FOLDER, boolean onlyUnread) { + String buildSQL = "SELECT COUNT(*) " + + " FROM " + RSS_ITEM_TABLE; + + if(!(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS) || ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS))) + { + buildSQL += " WHERE subscription_id_subscription IN " + + "(SELECT sc.rowid " + + "FROM subscription sc " + + "JOIN folder f ON sc." + SUBSCRIPTION_FOLDER_ID + " = f.rowid " + + "WHERE f.rowid = " + ID_FOLDER + ") "; + + if(onlyUnread) + buildSQL += " AND read_temp != 1"; + } + else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS))//UNREAD + buildSQL += " WHERE starred != 1 and read_temp != 1"; + else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS))//STARRED + buildSQL += " WHERE starred_temp = 1"; + // buildSQL += " WHERE starred = 1"; + + + + String result = "0"; + Cursor cursor = database.rawQuery(buildSQL, null); + if (cursor != null) + { + if(cursor.moveToFirst()) + result = cursor.getString(0); + } + cursor.close(); + + return result; + }*/ + + public Cursor getAllItemsForFolder(String ID_FOLDER, boolean onlyUnread) { + String buildSQL = getAllFeedsSelectStatement() + + " FROM " + RSS_ITEM_TABLE; + + if(!(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS) || ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS)))//Wenn nicht Alle Artikel ausgewaehlt wurde (-10) oder (-11) fuer Starred Feeds + { + buildSQL += " WHERE subscription_id_subscription IN " + + "(SELECT sc.rowid " + + "FROM subscription sc " + + "JOIN folder f ON sc." + SUBSCRIPTION_FOLDER_ID + " = f.rowid " + + "WHERE f.rowid = " + ID_FOLDER + ")"; + + if(onlyUnread) + buildSQL += " AND " + RSS_ITEM_READ_TEMP + " != 1"; + } + //else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS) && onlyUnread)//only unRead should only be null when testing the size of items + else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS)) + buildSQL += " WHERE " + RSS_ITEM_STARRED_TEMP + " != 1 AND " + RSS_ITEM_READ_TEMP + " != 1"; + //else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS)) + // buildSQL += " WHERE " + RSS_ITEM_STARRED + " != 1"; + //else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS) && onlyUnread) + // buildSQL += " WHERE " + RSS_ITEM_STARRED_TEMP + " = 1 AND " + RSS_ITEM_READ_TEMP + " != 1"; + else if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS)) + buildSQL += " WHERE " + RSS_ITEM_STARRED_TEMP + " = 1"; + + + buildSQL += " ORDER BY " + RSS_ITEM_PUBDATE + " desc"; + + // buildSQL += " WHERE starred = 1"; + + if(DATABASE_DEBUG_MODE) + Log.d("DB_HELPER", "getAllFeedData SQL: " + buildSQL); + return database.rawQuery(buildSQL, null); + } + + public Cursor getAllSubscriptionForFolder(String ID_FOLDER, boolean onlyUnread) { + //String buildSQL = "SELECT rowid as _id, * FROM " + SUBSCRIPTION_TABLE + " WHERE " + SUBSCRIPTION_SUBSCRIPTION_ID + "=" + ID_SUBSCRIPTION; + String buildSQL = "SELECT sc.rowid as _id, sc.* " + + "FROM " + SUBSCRIPTION_TABLE + " sc " + + "LEFT OUTER JOIN folder f ON sc.folder_idfolder = f.rowid "; + + if(ID_FOLDER.equals("-11"))//Starred + { + buildSQL += " JOIN " + RSS_ITEM_TABLE + " rss ON sc.rowid = rss." + RSS_ITEM_SUBSCRIPTION_ID + + " WHERE rss." + RSS_ITEM_STARRED_TEMP + " = 1" + + " GROUP BY sc.rowid " + + " HAVING COUNT(*) > 0"; + } + else if(onlyUnread || ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS) /*ID_SUBSCRIPTION.matches("-10|-11")*/) + { + buildSQL += " JOIN " + RSS_ITEM_TABLE + " rss ON sc.rowid = rss." + RSS_ITEM_SUBSCRIPTION_ID + + " WHERE f.rowid = " + ID_FOLDER + " AND rss." + RSS_ITEM_READ_TEMP + " != 1" + + " GROUP BY sc.rowid " + + " HAVING COUNT(*) > 0"; + + if(ID_FOLDER.equals(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS)) + buildSQL = buildSQL.replace("f.rowid = " + ID_FOLDER + " AND", "");//Remove to ID stuff because i want the result of all feeds where are unread items in + } + else + buildSQL += "WHERE f.rowid = " + ID_FOLDER; + + if(DATABASE_DEBUG_MODE) + Log.d("DB_HELPER", "getAllSub_SubscriptionForSubscription SQL: " + buildSQL); + return database.rawQuery(buildSQL, null); + } + + public void insertNewFolder (String label, String label_path) { + ContentValues contentValues = new ContentValues(); + contentValues.put(FOLDER_LABEL, label); + contentValues.put(FOLDER_LABEL_ID, label_path); + database.insert(FOLDER_TABLE, null, contentValues); + } + + /* + public int updateFolder (String label, String label_path) { + ContentValues contentValues = new ContentValues(); + contentValues.put(FOLDER_LABEL, label); + return database.update(FOLDER_TABLE, contentValues, FOLDER_LABEL_ID + "=?", new String[] { label_path }); + }*/ + + public void insertNewFeed (String headerText, String ID_FOLDER, String subscription_id, String FAVICON_URL) { + ContentValues contentValues = new ContentValues(); + contentValues.put(SUBSCRIPTION_HEADERTEXT, headerText); + contentValues.put(SUBSCRIPTION_FOLDER_ID, ID_FOLDER); + contentValues.put(SUBSCRIPTION_ID , subscription_id); + contentValues.put(SUBSCRIPTION_FAVICON_URL, FAVICON_URL); + database.insert(SUBSCRIPTION_TABLE, null, contentValues); + } + + public int updateFeed (String headerText, String ID_FOLDER, String subscription_id, String FAVICON_URL) { + ContentValues contentValues = new ContentValues(); + contentValues.put(SUBSCRIPTION_HEADERTEXT, headerText); + contentValues.put(SUBSCRIPTION_FOLDER_ID, ID_FOLDER); + contentValues.put(SUBSCRIPTION_FAVICON_URL, FAVICON_URL); + return database.update(SUBSCRIPTION_TABLE, contentValues, SUBSCRIPTION_ID + "= ?", new String[] { subscription_id }); + } + + public void insertNewItem (String Titel, String link, String description, Boolean isRead, String ID_SUBSCRIPTION, String ID_RSSITEM, Date timestamp, Boolean isStarred, String guid, String guidHash, String lastModified) { + ContentValues contentValues = new ContentValues(); + contentValues.put(RSS_ITEM_TITLE, Titel); + contentValues.put(RSS_ITEM_LINK, link); + contentValues.put(RSS_ITEM_BODY, description); + contentValues.put(RSS_ITEM_READ, isRead); + contentValues.put(RSS_ITEM_SUBSCRIPTION_ID, ID_SUBSCRIPTION); + contentValues.put(RSS_ITEM_RSSITEM_ID, ID_RSSITEM); + contentValues.put(RSS_ITEM_PUBDATE, timestamp.getTime()); + contentValues.put(RSS_ITEM_STARRED, isStarred); + contentValues.put(RSS_ITEM_GUID, guid); + contentValues.put(RSS_ITEM_GUIDHASH, guidHash); + contentValues.put(RSS_ITEM_LAST_MODIFIED, lastModified); + + contentValues.put(RSS_ITEM_READ_TEMP, isRead); + contentValues.put(RSS_ITEM_STARRED_TEMP, isStarred); + + database.insert(RSS_ITEM_TABLE, null, contentValues); + } + + public String getIdOfFolder (String FolderName) { + //String buildSQL = "SELECT rowid as _id FROM " + SUBSCRIPTION_TABLE + " WHERE " + SUBSCRIPTION_HEADERTEXT + " = '" + SubscriptionName + "'"; + String buildSQL = "SELECT rowid as _id FROM " + FOLDER_TABLE + " WHERE " + FOLDER_LABEL + " = '" + FolderName + "'"; + + return getStringValueBySQL(buildSQL); + } + + public String getIdOfFolderByLabelPath (String FolderLabelPath) { + //String buildSQL = "SELECT rowid as _id FROM " + SUBSCRIPTION_TABLE + " WHERE " + SUBSCRIPTION_HEADERTEXT + " = '" + SubscriptionName + "'"; + String buildSQL = "SELECT rowid as _id FROM " + FOLDER_TABLE + " WHERE " + FOLDER_LABEL_ID + " = '" + FolderLabelPath + "'"; + + return getStringValueBySQL(buildSQL); + } + + public String getRowIdBySubscriptionID (String StreamID) { + //String buildSQL = "SELECT rowid as _id FROM " + SUBSCRIPTION_TABLE + " WHERE " + SUBSCRIPTION_HEADERTEXT + " = '" + SubscriptionName + "'"; + String buildSQL = "SELECT rowid as _id FROM " + SUBSCRIPTION_TABLE + " WHERE " + SUBSCRIPTION_ID + " = '" + StreamID + "'"; + return getStringValueBySQL(buildSQL); + } + + public String getSubscriptionIdByRowID (String ID) { + + String buildSQL = "SELECT " + SUBSCRIPTION_ID + " FROM " + SUBSCRIPTION_TABLE + " WHERE rowid = '" + ID + "'"; + return getStringValueBySQL(buildSQL); + } + + public String getTitleOfFolderByID (String FolderID) { + //String buildSQL = "SELECT " + SUBSCRIPTION_HEADERTEXT + " FROM " + SUBSCRIPTION_TABLE + " WHERE rowid = '" + SubscriptionID + "'"; + String buildSQL = "SELECT " + FOLDER_LABEL + " FROM " + FOLDER_TABLE + " WHERE rowid = '" + FolderID + "'"; + return getStringValueBySQL(buildSQL); + } + + public String getTitleOfSubscriptionByRowID (String SubscriptionID) { + String buildSQL = "SELECT " + SUBSCRIPTION_HEADERTEXT + " FROM " + SUBSCRIPTION_TABLE + " WHERE rowid = '" + SubscriptionID + "'"; + return getStringValueBySQL(buildSQL); + } + + public String getTitleOfSubscriptionByFeedItemID (String SubscriptionID) { + String buildSQL = "SELECT " + SUBSCRIPTION_HEADERTEXT + " FROM " + SUBSCRIPTION_TABLE + " sc " + + "JOIN " + RSS_ITEM_TABLE + " rss ON sc.rowid = rss." + RSS_ITEM_SUBSCRIPTION_ID + " " + + "WHERE rss.rowid = '" + SubscriptionID + "'"; + return getStringValueBySQL(buildSQL); + } + + public int removeTopSubscriptionItemByTag(String TAG) + { + return database.delete(SUBSCRIPTION_TABLE, SUBSCRIPTION_HEADERTEXT + " = ?", new String[] { TAG }); + } + + public int removeFolderByFolderLabel(String FolderLabel) + { + return database.delete(FOLDER_TABLE, FOLDER_LABEL + " = ?", new String[] { FolderLabel }); + } + + public int removeItemByItemId(String idRssItem) + { + return database.delete(RSS_ITEM_TABLE, RSS_ITEM_RSSITEM_ID + " = ?", new String[] { idRssItem }); + } + + public List convertCursorToStringArray(Cursor cursor, int column_id) + { + List items = new ArrayList(); + try + { + if(cursor != null) + { + if(cursor.getCount() > 0) + { + cursor.moveToFirst(); + do { + items.add(cursor.getString(column_id)); + } while(cursor.moveToNext()); + } + } + } finally { + cursor.close(); + } + return items; + + } + + private String getStringValueBySQL(String buildSQL) + { + String result = null; + + Cursor cursor = database.rawQuery(buildSQL, null); + try + { + if(cursor != null) + { + if(cursor.moveToFirst()) + result = cursor.getString(0); + } + } finally { + cursor.close(); + } + + return result; + } + + public long getLongValueBySQL(String buildSQL) + { + long result = -1; + + Cursor cursor = database.rawQuery(buildSQL, null); + try + { + if(cursor != null) + { + if(cursor.moveToFirst()) + result = cursor.getLong(0); + } + } finally { + cursor.close(); + } + + return result; + } + + public Boolean doesRssItemAlreadyExsists(String idRssItem)//idRssItem = id aus dem Google Reader Stream + { + String buildSQL = "SELECT " + RSS_ITEM_TITLE + " FROM " + RSS_ITEM_TABLE + " WHERE " + RSS_ITEM_RSSITEM_ID + " = '" + idRssItem + "'"; + Cursor cursor = database.rawQuery(buildSQL, null); + int count = cursor.getCount(); + cursor.close(); + if(count > 0) + return true; + else + return false; + } + + public int resetRssItemsDatabase() + { + int result = database.delete(RSS_ITEM_TABLE, null, null); + return result; + } + + public void resetDatabase() + { + openHelper.resetDatabase(database); + } + + public void openDatabase() + { + database = openHelper.getWritableDatabase(); + } + + public void closeDatabase() + { + database.close(); + } +} diff --git a/src/de/luhmer/owncloudnewsreader/helper/MenuUtilsSherlockFragmentActivity.java b/src/de/luhmer/owncloudnewsreader/helper/MenuUtilsSherlockFragmentActivity.java index 4b01b9e4..797eb907 100644 --- a/src/de/luhmer/owncloudnewsreader/helper/MenuUtilsSherlockFragmentActivity.java +++ b/src/de/luhmer/owncloudnewsreader/helper/MenuUtilsSherlockFragmentActivity.java @@ -1,158 +1,201 @@ -package de.luhmer.owncloudnewsreader.helper; - -import android.support.v4.app.FragmentActivity; -import android.util.Log; -import android.widget.Toast; - -import com.actionbarsherlock.app.SherlockDialogFragment; -import com.actionbarsherlock.app.SherlockFragmentActivity; -import com.actionbarsherlock.view.Menu; -import com.actionbarsherlock.view.MenuInflater; -import com.actionbarsherlock.view.MenuItem; - -import de.luhmer.owncloudnewsreader.NewsReaderDetailActivity; -import de.luhmer.owncloudnewsreader.NewsReaderDetailFragment; -import de.luhmer.owncloudnewsreader.NewsReaderListActivity; -import de.luhmer.owncloudnewsreader.R; -import de.luhmer.owncloudnewsreader.VersionInfoDialogFragment; -import de.luhmer.owncloudnewsreader.database.DatabaseConnection; -import de.luhmer.owncloudnewsreader.reader.IReader; -import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; -import de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloud_Reader; - -public class MenuUtilsSherlockFragmentActivity extends SherlockFragmentActivity { - protected static final String TAG = "MenuUtils"; - - static FragmentActivity activity; - - static MenuItem menuItemSettings; - static MenuItem menuItemLogin; - static MenuItem menuItemStartImageCaching; - - - private static MenuItem menuItemUpdater; - private static MenuItem menuItemMarkAllAsRead; - private static MenuItem menuItemDownloadMoreItems; - - /** - * @return the menuItemUpdater - */ - public static MenuItem getMenuItemUpdater() { - return menuItemUpdater; - } - - /** - * @return the menuItemMarkAllAsRead - */ - public static MenuItem getMenuItemMarkAllAsRead() { - return menuItemMarkAllAsRead; - } - - /** - * @return the menuItemDownloadMoreItems - */ - public static MenuItem getMenuItemDownloadMoreItems() { - return menuItemDownloadMoreItems; - } - - - - - public static void onCreateOptionsMenu(Menu menu, MenuInflater inflater, boolean mTwoPane, FragmentActivity act) { - inflater.inflate(R.menu.news_reader, menu); - - activity = act; - - menuItemSettings = menu.findItem(R.id.action_settings); - menuItemLogin = menu.findItem(R.id.action_login); - menuItemStartImageCaching = menu.findItem(R.id.menu_StartImageCaching); - - menuItemUpdater = menu.findItem(R.id.menu_update); - menuItemMarkAllAsRead = menu.findItem(R.id.menu_markAllAsRead); - menuItemDownloadMoreItems = menu.findItem(R.id.menu_downloadMoreItems); - - - menuItemMarkAllAsRead.setEnabled(false); - menuItemDownloadMoreItems.setEnabled(false); - - if(!mTwoPane && act instanceof NewsReaderListActivity)//On Smartphones disable this... - { - menuItemMarkAllAsRead.setVisible(false); - menuItemDownloadMoreItems.setVisible(false); - - menuItemDownloadMoreItems = null; - menuItemMarkAllAsRead = null; - } else if(act instanceof NewsReaderDetailActivity) { - menuItemLogin.setVisible(false); - menuItemSettings.setVisible(false); - menuItemStartImageCaching.setVisible(false); - menuItemUpdater.setVisible(false); - - menuItemMarkAllAsRead.setEnabled(true); - menuItemDownloadMoreItems.setEnabled(true); - } - - NewsReaderDetailFragment ndf = ((NewsReaderDetailFragment) activity.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)); - if(ndf != null) - ndf.UpdateMenuItemsState();//Is called on Smartphones - } - - public static boolean onOptionsItemSelected(MenuItem item, FragmentActivity activity) { - switch (item.getItemId()) { - case R.id.menu_About_Changelog: - SherlockDialogFragment dialog = new VersionInfoDialogFragment(); - dialog.show(activity.getSupportFragmentManager(), "VersionChangelogDialogFragment"); - return true; - - case R.id.menu_markAllAsRead: - NewsReaderDetailFragment ndf = ((NewsReaderDetailFragment) activity.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)); - if(ndf != null) - { - /* - for(int i = 0; i < ndf.getListView().getChildCount(); i++) - { - View view = ndf.getListView().getChildAt(i); - CheckBox cb = (CheckBox) view.findViewById(R.id.cb_lv_item_read); - if(!cb.isChecked()) - cb.setChecked(true); - } - */ - - DatabaseConnection dbConn = new DatabaseConnection(activity); - try { - dbConn.markAllItemsAsRead(ndf.getDatabaseIdsOfItems()); - } finally { - dbConn.closeDatabase(); - } - ndf.UpdateCursor(); - - } - return true; - - case R.id.menu_downloadMoreItems: - DownloadMoreItems(); - return true; - } - return false; - } - - private static void DownloadMoreItems() - { - NewsReaderDetailFragment ndf = ((NewsReaderDetailFragment) activity.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)); - IReader _Reader = new OwnCloud_Reader(); - _Reader.Start_AsyncTask_GetOldItems(0, activity, onAsyncTaskComplete, ndf.getIdFeed(), ndf.getIdFolder()); - - Toast.makeText(activity, activity.getString(R.string.toast_GettingMoreItems), Toast.LENGTH_SHORT).show(); - } - - static OnAsyncTaskCompletedListener onAsyncTaskComplete = new OnAsyncTaskCompletedListener() { - @Override - public void onAsyncTaskCompleted(int task_id, Object task_result) { - NewsReaderDetailFragment ndf = ((NewsReaderDetailFragment) activity.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)); - if(ndf != null) - ndf.UpdateCursor(); - - Log.d(TAG, "Finished Download extra items.."); - } - }; +package de.luhmer.owncloudnewsreader.helper; + +import android.annotation.TargetApi; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.os.Build; +import android.support.v4.app.FragmentActivity; +import android.util.Log; +import android.widget.Toast; + +import com.actionbarsherlock.app.SherlockDialogFragment; +import com.actionbarsherlock.app.SherlockFragmentActivity; +import com.actionbarsherlock.view.Menu; +import com.actionbarsherlock.view.MenuInflater; +import com.actionbarsherlock.view.MenuItem; + +import de.luhmer.owncloudnewsreader.Constants; +import de.luhmer.owncloudnewsreader.NewsReaderDetailActivity; +import de.luhmer.owncloudnewsreader.NewsReaderDetailFragment; +import de.luhmer.owncloudnewsreader.NewsReaderListActivity; +import de.luhmer.owncloudnewsreader.R; +import de.luhmer.owncloudnewsreader.VersionInfoDialogFragment; +import de.luhmer.owncloudnewsreader.ListView.SubscriptionExpandableListAdapter; +import de.luhmer.owncloudnewsreader.database.DatabaseConnection; +import de.luhmer.owncloudnewsreader.reader.IReader; +import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; +import de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloud_Reader; + +public class MenuUtilsSherlockFragmentActivity extends SherlockFragmentActivity { + /* (non-Javadoc) + * @see android.support.v4.app.FragmentActivity#onResume() + */ + + protected static final String TAG = "MenuUtils"; + + static FragmentActivity activity; + + static MenuItem menuItemSettings; + static MenuItem menuItemLogin; + static MenuItem menuItemStartImageCaching; + + + private static MenuItem menuItemUpdater; + private static MenuItem menuItemMarkAllAsRead; + private static MenuItem menuItemDownloadMoreItems; + + /** + * @return the menuItemUpdater + */ + public static MenuItem getMenuItemUpdater() { + return menuItemUpdater; + } + + /** + * @return the menuItemMarkAllAsRead + */ + public static MenuItem getMenuItemMarkAllAsRead() { + return menuItemMarkAllAsRead; + } + + /** + * @return the menuItemDownloadMoreItems + */ + public static MenuItem getMenuItemDownloadMoreItems() { + return menuItemDownloadMoreItems; + } + + + @TargetApi(Build.VERSION_CODES.HONEYCOMB) + @Override + protected void onResume() { + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) { + invalidateOptionsMenu(); + } + super.onResume(); + } + + + public static void onCreateOptionsMenu(Menu menu, MenuInflater inflater, boolean mTwoPane, FragmentActivity act) { + inflater.inflate(R.menu.news_reader, menu); + + activity = act; + + menuItemSettings = menu.findItem(R.id.action_settings); + menuItemLogin = menu.findItem(R.id.action_login); + menuItemStartImageCaching = menu.findItem(R.id.menu_StartImageCaching); + + menuItemUpdater = menu.findItem(R.id.menu_update); + menuItemMarkAllAsRead = menu.findItem(R.id.menu_markAllAsRead); + menuItemDownloadMoreItems = menu.findItem(R.id.menu_downloadMoreItems); + + + menuItemMarkAllAsRead.setEnabled(false); + menuItemDownloadMoreItems.setEnabled(false); + + if(!mTwoPane && act instanceof NewsReaderListActivity)//On Smartphones disable this... + { + menuItemMarkAllAsRead.setVisible(false); + menuItemDownloadMoreItems.setVisible(false); + + menuItemDownloadMoreItems = null; + menuItemMarkAllAsRead = null; + } else if(act instanceof NewsReaderDetailActivity) { + menuItemLogin.setVisible(false); + menuItemSettings.setVisible(false); + menuItemStartImageCaching.setVisible(false); + menuItemUpdater.setVisible(false); + + menuItemMarkAllAsRead.setEnabled(true); + menuItemDownloadMoreItems.setEnabled(true); + } + + NewsReaderDetailFragment ndf = ((NewsReaderDetailFragment) activity.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)); + if(ndf != null) + ndf.UpdateMenuItemsState();//Is called on Smartphones + } + + public static boolean onOptionsItemSelected(MenuItem item, FragmentActivity activity) { + switch (item.getItemId()) { + case R.id.menu_About_Changelog: + SherlockDialogFragment dialog = new VersionInfoDialogFragment(); + dialog.show(activity.getSupportFragmentManager(), "VersionChangelogDialogFragment"); + return true; + + case R.id.menu_markAllAsRead: + NewsReaderDetailFragment ndf = ((NewsReaderDetailFragment) activity.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)); + if(ndf != null) + { + /* + for(int i = 0; i < ndf.getListView().getChildCount(); i++) + { + View view = ndf.getListView().getChildAt(i); + CheckBox cb = (CheckBox) view.findViewById(R.id.cb_lv_item_read); + if(!cb.isChecked()) + cb.setChecked(true); + } + */ + + DatabaseConnection dbConn = new DatabaseConnection(activity); + try { + dbConn.markAllItemsAsRead(ndf.getDatabaseIdsOfItems()); + } finally { + dbConn.closeDatabase(); + } + ndf.UpdateCursor(); + + //If tablet view is enabled update the listview as well + if(activity instanceof NewsReaderListActivity) + ((NewsReaderListActivity) activity).updateAdapter(); + + } + return true; + + case R.id.menu_downloadMoreItems: + DownloadMoreItems(); + return true; + } + return false; + } + + private static void DownloadMoreItems() + { + NewsReaderDetailFragment ndf = ((NewsReaderDetailFragment) activity.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)); + + DatabaseConnection dbConn = new DatabaseConnection(activity); + int count = dbConn.getCountFeedsForFolder(SubscriptionExpandableListAdapter.ALL_UNREAD_ITEMS, true); + if(count > Constants.maxItemsCount) + { + String text = activity.getString(R.string.max_items_count_reached); + text = text.replace("XX", "" + Constants.maxItemsCount); + new AlertDialog.Builder(activity) + .setTitle(activity.getString(R.string.empty_view_header)) + .setMessage(text) + .setPositiveButton(activity.getString(android.R.string.ok), new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int id) { + } + }) + .create() + .show(); + //Toast.makeText(activity, text, Toast.LENGTH_LONG).show(); + } + else + { + IReader _Reader = new OwnCloud_Reader(); + _Reader.Start_AsyncTask_GetOldItems(0, activity, onAsyncTaskComplete, ndf.getIdFeed(), ndf.getIdFolder()); + + Toast.makeText(activity, activity.getString(R.string.toast_GettingMoreItems), Toast.LENGTH_SHORT).show(); + } + } + + static OnAsyncTaskCompletedListener onAsyncTaskComplete = new OnAsyncTaskCompletedListener() { + @Override + public void onAsyncTaskCompleted(int task_id, Object task_result) { + NewsReaderDetailFragment ndf = ((NewsReaderDetailFragment) activity.getSupportFragmentManager().findFragmentById(R.id.newsreader_detail_container)); + if(ndf != null) + ndf.UpdateCursor(); + + Log.d(TAG, "Finished Download extra items.."); + } + }; } \ No newline at end of file diff --git a/src/de/luhmer/owncloudnewsreader/interfaces/AsyncUpdateFinished.java b/src/de/luhmer/owncloudnewsreader/interfaces/AsyncUpdateFinished.java index a0e5e1ca..faad4742 100644 --- a/src/de/luhmer/owncloudnewsreader/interfaces/AsyncUpdateFinished.java +++ b/src/de/luhmer/owncloudnewsreader/interfaces/AsyncUpdateFinished.java @@ -1,5 +1,5 @@ -package de.luhmer.owncloudnewsreader.interfaces; - -public interface AsyncUpdateFinished { - public void FinishedUpdate(); -} +package de.luhmer.owncloudnewsreader.interfaces; + +public interface AsyncUpdateFinished { + public void FinishedUpdate(); +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/AsyncTask_Reader.java b/src/de/luhmer/owncloudnewsreader/reader/AsyncTask_Reader.java index fb6ddcd2..c4c95547 100644 --- a/src/de/luhmer/owncloudnewsreader/reader/AsyncTask_Reader.java +++ b/src/de/luhmer/owncloudnewsreader/reader/AsyncTask_Reader.java @@ -1,7 +1,45 @@ -package de.luhmer.owncloudnewsreader.reader; - -import android.app.Activity; - -public interface AsyncTask_Reader { - public void attach(final Activity context, final OnAsyncTaskCompletedListener[] listener); -} +package de.luhmer.owncloudnewsreader.reader; + +import android.app.Activity; +import android.os.AsyncTask; + +public abstract class AsyncTask_Reader extends AsyncTask { + protected Activity context; + protected int task_id; + protected OnAsyncTaskCompletedListener[] listener; + + public AsyncTask_Reader(final int task_id, final Activity context, final OnAsyncTaskCompletedListener[] listener) { + this.context = context; + this.task_id = task_id; + this.listener = listener; + } + + //public abstract void attach(final Activity context, final OnAsyncTaskCompletedListener[] listener); + + //Activity meldet sich zurueck nach OrientationChange + public void attach(final Activity context, final OnAsyncTaskCompletedListener[] listener) { + this.context = context; + this.listener = listener; + } + + //Activity meldet sich ab + public void detach() { + if (context != null) { + context = null; + } + + if (listener != null) { + listener = null; + } + } + + @Override + protected void onPostExecute(Object ex) { + for (OnAsyncTaskCompletedListener listenerInstance : listener) { + if(listenerInstance != null) + listenerInstance.onAsyncTaskCompleted(task_id, ex); + } + + detach(); + } +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/HttpJsonRequest.java b/src/de/luhmer/owncloudnewsreader/reader/HttpJsonRequest.java index f57bebc3..7675e245 100644 --- a/src/de/luhmer/owncloudnewsreader/reader/HttpJsonRequest.java +++ b/src/de/luhmer/owncloudnewsreader/reader/HttpJsonRequest.java @@ -1,260 +1,253 @@ -package de.luhmer.owncloudnewsreader.reader; - -import java.net.URL; -import java.util.List; - -import javax.net.ssl.HostnameVerifier; -import javax.net.ssl.SSLSession; - -import org.apache.http.HttpResponse; -import org.apache.http.NameValuePair; -import org.apache.http.auth.AuthScope; -import org.apache.http.auth.UsernamePasswordCredentials; -import org.apache.http.client.ResponseHandler; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.methods.HttpPut; -import org.apache.http.client.utils.URLEncodedUtils; -import org.apache.http.entity.StringEntity; -import org.apache.http.impl.client.BasicResponseHandler; -import org.apache.http.impl.client.DefaultHttpClient; -import org.json.JSONObject; - -import android.annotation.SuppressLint; -import android.content.Context; -import android.content.SharedPreferences; -import android.preference.PreferenceManager; -import de.luhmer.owncloudnewsreader.SettingsActivity; -import de.luhmer.owncloudnewsreader.helper.SSLHttpClient; - -public class HttpJsonRequest { - //private static final String TAG = "HttpJsonRequest"; - - - @SuppressLint("DefaultLocale") - public static JSONObject PerformJsonRequest(String urlString, List nameValuePairs, String username, String password, Context context) throws Exception - { - if(nameValuePairs != null) - { - urlString += "&" + URLEncodedUtils.format(nameValuePairs, "utf-8"); - /* - JSONObject jObj = new JSONObject(); - - for (NameValuePair nameValuePair : nameValuePairs) { - jObj.put(nameValuePair.getName(), nameValuePair.getValue()); - }*/ - - //request.setEntity(new ByteArrayEntity(jObj.toString().getBytes("UTF8"))); - - //httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); - } - - URL url = new URL(urlString); - - // Instantiate an HttpClient - //HttpClient httpclient = new DefaultHttpClient(p); - DefaultHttpClient httpClient = null; - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); - if(sp.getBoolean(SettingsActivity.CB_ALLOWALLSSLCERTIFICATES_STRING, false) && url.getProtocol().toLowerCase().equals("https")) - httpClient = new SSLHttpClient(context); - else - httpClient = new DefaultHttpClient(); - - if(username != null && password != null) - httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username,password)); - - //HttpGet request = new HttpGet(url); - //HttpPost request = new HttpPost(url); - //httpClient.setParams(params) - - /* - HttpParams params = new BasicHttpParams(); - for (NameValuePair nameValuePair : nameValuePairs) { - params.setIntParameter(nameValuePair.getName(), Integer.parseInt(nameValuePair.getValue())); - } - - httpClient.setParams(params);*/ - - // Instantiate a GET HTTP method - HttpGet request = new HttpGet(url.toString()); - - ResponseHandler responseHandler = new BasicResponseHandler(); - String responseBody = httpClient.execute(request, responseHandler); - JSONObject json = new JSONObject(responseBody); - return json; - //HttpResponse response = httpClient.execute(request); - //return null; - - // Log.i(getClass().getSimpleName(), "send task - end"); - - - /* - URLConnection conn = null; - InputStream inputStream = null; - URL urlInstance = new URL(url); - conn = urlInstance.openConnection(); - HttpURLConnection httpConn = (HttpURLConnection) conn; - httpConn.setRequestMethod("GET"); - httpConn.connect(); - if (httpConn.getResponseCode() == HttpURLConnection.HTTP_OK) { - inputStream = httpConn.getInputStream(); - - BufferedReader r = new BufferedReader(new InputStreamReader(inputStream)); - StringBuilder total = new StringBuilder(); - String line; - while ((line = r.readLine()) != null) { - total.append(line); - } - - return new JSONObject(total.toString()); - } - else - Log.d(TAG, "Response Code: " + httpConn.getResponseCode()); - */ - } - - /* - public static int performTagChangeRequest(String url) - { - try - { - URLConnection conn = null; - //InputStream inputStream = null; - URL urlInstance = new URL(url); - conn = urlInstance.openConnection(); - HttpURLConnection httpConn = (HttpURLConnection) conn; - httpConn.setRequestMethod("GET"); - httpConn.connect(); - return httpConn.getResponseCode(); - } - catch(Exception ex) - { - ex.printStackTrace(); - } - return -1; - } - */ - - - @SuppressLint("DefaultLocale") - public static int performTagChangeRequest(String urlString, String username, String password, Context context, String content) throws Exception - { - //url = "http://192.168.10.126/owncloud/ocs/v1.php/apps/news/items/3787/read"; -/* - String authString = username + ":" + password; - String authStringEnc = Base64.encode(authString.getBytes()); - - URL urlConn = new URL(url); - - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); - - HttpURLConnection httpConnection = null; - if (urlConn.getProtocol().toLowerCase().equals("https") && sp.getBoolean(SettingsActivity.CB_ALLOWALLSSLCERTIFICATES_STRING, false)) { - trustAllHosts(); - HttpsURLConnection https = (HttpsURLConnection) urlConn.openConnection(); - https.setHostnameVerifier(DO_NOT_VERIFY); - httpConnection = https; - } else { - httpConnection = (HttpURLConnection) urlConn.openConnection(); - } - - httpConnection.setRequestProperty("Authorization", "Basic " + authStringEnc); - httpConnection.setRequestMethod("PUT"); - - if(nameValuePairs != null) - { - httpConnection.setEntity(new UrlEncodedFormEntity(nameValuePairs)); - } - - InputStreamReader in = new InputStreamReader((InputStream) httpConnection.getContent()); - BufferedReader buff = new BufferedReader(in); - String text = ""; - String line; - do { - line = buff.readLine(); - if(line != null) - text += line + "\n"; - } while (line != null); - Log.d(TAG, text); - - - return httpConnection.getResponseCode(); - */ - - - URL url = new URL(urlString); - DefaultHttpClient httpClient; - SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); - if(sp.getBoolean(SettingsActivity.CB_ALLOWALLSSLCERTIFICATES_STRING, false) && url.getProtocol().toLowerCase().equals("https")) - httpClient = new SSLHttpClient(context); - else - httpClient = new DefaultHttpClient(); - - if(username != null && password != null) - httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(username,password)); - - /* - HttpParams params = new BasicHttpParams(); - if(nameValuePairs != null) - for (NameValuePair nameValuePair : nameValuePairs) - params.setParameter(nameValuePair.getName(), nameValuePair.getValue()); - httpClient.setParams(params); - */ - - HttpPut request = new HttpPut(url.toString()); - //if(nameValuePairs != null) - // request.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8)); - request.setEntity(new StringEntity(content)); - request.addHeader("Accept", "application/json"); - - - HttpResponse response = httpClient.execute(request); - //ResponseHandler responseHandler = new BasicResponseHandler(); - //String responseBody = httpClient.execute(request, responseHandler); - - //Thread.sleep(5000); - - return response.getStatusLine().getStatusCode(); - //return 200; - } - - - - - // always verify the host - dont check for certificate - final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { - public boolean verify(String hostname, SSLSession session) { - return true; - } - }; - - /** - * Trust every server - dont check for any certificate - */ - /* - private static void trustAllHosts() { - // Create a trust manager that does not validate certificate chains - TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { - public java.security.cert.X509Certificate[] getAcceptedIssuers() { - return new java.security.cert.X509Certificate[] {}; - } - - public void checkClientTrusted(X509Certificate[] chain, - String authType) throws CertificateException { - } - - public void checkServerTrusted(X509Certificate[] chain, - String authType) throws CertificateException { - } - } }; - - // Install the all-trusting trust manager - try { - SSLContext sc = SSLContext.getInstance("TLS"); - sc.init(null, trustAllCerts, new java.security.SecureRandom()); - HttpsURLConnection - .setDefaultSSLSocketFactory(sc.getSocketFactory()); - } catch (Exception e) { - e.printStackTrace(); - } - }*/ -} +package de.luhmer.owncloudnewsreader.reader; + +import java.io.InputStream; +import java.net.HttpURLConnection; +import java.net.URL; +import java.util.List; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLSession; + +import org.apache.http.HttpResponse; +import org.apache.http.NameValuePair; +import org.apache.http.auth.AuthScope; +import org.apache.http.auth.UsernamePasswordCredentials; +import org.apache.http.client.ResponseHandler; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.utils.URLEncodedUtils; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.BasicResponseHandler; +import org.apache.http.impl.client.DefaultHttpClient; +import org.json.JSONObject; + +import android.annotation.SuppressLint; +import android.content.Context; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; +import de.luhmer.owncloudnewsreader.SettingsActivity; +import de.luhmer.owncloudnewsreader.helper.SSLHttpClient; +import de.luhmer.owncloudnewsreader.util.Base64; + +public class HttpJsonRequest { + //private static final String TAG = "HttpJsonRequest"; + + public static InputStream PerformJsonRequest(String urlString, List nameValuePairs, final String username, final String password, Context context) throws Exception + { + if(nameValuePairs != null) + urlString += "&" + URLEncodedUtils.format(nameValuePairs, "utf-8"); + + URL url = new URL(urlString); + + HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); + + + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); + /* + if(sp.getBoolean(SettingsActivity.CB_ALLOWALLSSLCERTIFICATES_STRING, false) && url.getProtocol().toLowerCase().equals("https")) + httpClient = new SSLHttpClient(context); + else + httpClient = new DefaultHttpClient(); + */ + + //urlConnection.setDefaultSSLSocketFactory(new MySSLSocketFactory()); getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username,password)); + + if(username != null && password != null) + urlConnection.setRequestProperty("Authorization", "Basic " + Base64.encode((username + ":" + password).getBytes())); + /* + Authenticator.setDefault(new Authenticator(){ + protected PasswordAuthentication getPasswordAuthentication() { + return new PasswordAuthentication(username, password.toCharArray()); + }});*/ + + urlConnection.setDoOutput(false); + urlConnection.setDoInput(true); + urlConnection.setRequestMethod("GET"); + //urlConnection.setFollowRedirects(true); + urlConnection.setUseCaches(false); + urlConnection.setConnectTimeout(10000); + urlConnection.setReadTimeout(120000);//2min + urlConnection.setRequestProperty("Content-Type","application/json"); + + //urlConnection.setRequestProperty("Host", "de.luhmer.ownCloudNewsReader"); + urlConnection.connect(); + + int HttpResult = urlConnection.getResponseCode(); + if(HttpResult == HttpURLConnection.HTTP_OK) { + return urlConnection.getInputStream(); + } else { + throw new Exception(urlConnection.getResponseMessage()); + } + } + + + @SuppressLint("DefaultLocale") + public static JSONObject PerformJsonRequest_old(String urlString, List nameValuePairs, String username, String password, Context context) throws Exception + { + if(nameValuePairs != null) + urlString += "&" + URLEncodedUtils.format(nameValuePairs, "utf-8"); + + URL url = new URL(urlString); + + // Instantiate an HttpClient + //HttpClient httpclient = new DefaultHttpClient(p); + DefaultHttpClient httpClient = null; + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); + if(sp.getBoolean(SettingsActivity.CB_ALLOWALLSSLCERTIFICATES_STRING, false) && url.getProtocol().toLowerCase().equals("https")) + httpClient = new SSLHttpClient(context); + else + httpClient = new DefaultHttpClient(); + + if(username != null && password != null) + httpClient.getCredentialsProvider().setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), new UsernamePasswordCredentials(username,password)); + + //HttpGet request = new HttpGet(url); + //HttpPost request = new HttpPost(url); + //httpClient.setParams(params) + + /* + HttpParams params = new BasicHttpParams(); + for (NameValuePair nameValuePair : nameValuePairs) { + params.setIntParameter(nameValuePair.getName(), Integer.parseInt(nameValuePair.getValue())); + } + + httpClient.setParams(params);*/ + + // Instantiate a GET HTTP method + HttpGet request = new HttpGet(url.toString()); + + ResponseHandler responseHandler = new BasicResponseHandler(); + String responseBody = httpClient.execute(request, responseHandler); + JSONObject json = new JSONObject(responseBody); + return json; + //HttpResponse response = httpClient.execute(request); + //return null; + + // Log.i(getClass().getSimpleName(), "send task - end"); + } + + + + @SuppressLint("DefaultLocale") + public static int performTagChangeRequest(String urlString, String username, String password, Context context, String content) throws Exception + { + //url = "http://192.168.10.126/owncloud/ocs/v1.php/apps/news/items/3787/read"; +/* + String authString = username + ":" + password; + String authStringEnc = Base64.encode(authString.getBytes()); + + URL urlConn = new URL(url); + + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); + + HttpURLConnection httpConnection = null; + if (urlConn.getProtocol().toLowerCase().equals("https") && sp.getBoolean(SettingsActivity.CB_ALLOWALLSSLCERTIFICATES_STRING, false)) { + trustAllHosts(); + HttpsURLConnection https = (HttpsURLConnection) urlConn.openConnection(); + https.setHostnameVerifier(DO_NOT_VERIFY); + httpConnection = https; + } else { + httpConnection = (HttpURLConnection) urlConn.openConnection(); + } + + httpConnection.setRequestProperty("Authorization", "Basic " + authStringEnc); + httpConnection.setRequestMethod("PUT"); + + if(nameValuePairs != null) + { + httpConnection.setEntity(new UrlEncodedFormEntity(nameValuePairs)); + } + + InputStreamReader in = new InputStreamReader((InputStream) httpConnection.getContent()); + BufferedReader buff = new BufferedReader(in); + String text = ""; + String line; + do { + line = buff.readLine(); + if(line != null) + text += line + "\n"; + } while (line != null); + Log.d(TAG, text); + + + return httpConnection.getResponseCode(); + */ + + + URL url = new URL(urlString); + DefaultHttpClient httpClient; + SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); + if(sp.getBoolean(SettingsActivity.CB_ALLOWALLSSLCERTIFICATES_STRING, false) && url.getProtocol().toLowerCase().equals("https")) + httpClient = new SSLHttpClient(context); + else + httpClient = new DefaultHttpClient(); + + if(username != null && password != null) + httpClient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), new UsernamePasswordCredentials(username,password)); + + /* + HttpParams params = new BasicHttpParams(); + if(nameValuePairs != null) + for (NameValuePair nameValuePair : nameValuePairs) + params.setParameter(nameValuePair.getName(), nameValuePair.getValue()); + httpClient.setParams(params); + */ + + HttpPut request = new HttpPut(url.toString()); + //if(nameValuePairs != null) + // request.setEntity(new UrlEncodedFormEntity(nameValuePairs, HTTP.UTF_8)); + request.setEntity(new StringEntity(content)); + request.addHeader("Accept", "application/json"); + + + HttpResponse response = httpClient.execute(request); + //ResponseHandler responseHandler = new BasicResponseHandler(); + //String responseBody = httpClient.execute(request, responseHandler); + + //Thread.sleep(5000); + + return response.getStatusLine().getStatusCode(); + //return 200; + } + + + + + // always verify the host - dont check for certificate + final static HostnameVerifier DO_NOT_VERIFY = new HostnameVerifier() { + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + + /** + * Trust every server - dont check for any certificate + */ + /* + private static void trustAllHosts() { + // Create a trust manager that does not validate certificate chains + TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[] {}; + } + + public void checkClientTrusted(X509Certificate[] chain, + String authType) throws CertificateException { + } + + public void checkServerTrusted(X509Certificate[] chain, + String authType) throws CertificateException { + } + } }; + + // Install the all-trusting trust manager + try { + SSLContext sc = SSLContext.getInstance("TLS"); + sc.init(null, trustAllCerts, new java.security.SecureRandom()); + HttpsURLConnection + .setDefaultSSLSocketFactory(sc.getSocketFactory()); + } catch (Exception e) { + e.printStackTrace(); + } + }*/ +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/IReader.java b/src/de/luhmer/owncloudnewsreader/reader/IReader.java index ef6bd1c2..40a31a9d 100644 --- a/src/de/luhmer/owncloudnewsreader/reader/IReader.java +++ b/src/de/luhmer/owncloudnewsreader/reader/IReader.java @@ -1,25 +1,24 @@ -package de.luhmer.owncloudnewsreader.reader; - -import java.util.List; - -import android.app.Activity; -import android.content.Context; -import android.util.SparseArray; - -public interface IReader { - public boolean isSyncRunning(); - public void setSyncRunning(boolean status); - - public SparseArray getRunningAsyncTasks(); - public void attachToRunningTask(int task_id, Activity activity, OnAsyncTaskCompletedListener listener); - - public void Start_AsyncTask_GetItems(final int task_id, final Activity context, final OnAsyncTaskCompletedListener listener, FeedItemTags.TAGS tag); - public void Start_AsyncTask_GetOldItems(final int task_id, final Activity context, final OnAsyncTaskCompletedListener listener, String feed_id, String folder_id); - - public void Start_AsyncTask_GetFolder(final int task_id, final Activity context, final OnAsyncTaskCompletedListener listener); - public void Start_AsyncTask_GetFeeds(final int task_id, final Activity context, final OnAsyncTaskCompletedListener listener); - public void Start_AsyncTask_PerformTagAction(final int task_id, final Context context, final OnAsyncTaskCompletedListener listener, List itemIds, FeedItemTags.TAGS tag); - public void Start_AsyncTask_Authenticate(final int task_id, final Activity context, final OnAsyncTaskCompletedListener listener); - - public abstract void onAsyncTaskCompleted(final int task_id, final Object task_result); -} +package de.luhmer.owncloudnewsreader.reader; + +import java.util.List; + +import android.app.Activity; +import android.util.SparseArray; + +public interface IReader { + public boolean isSyncRunning(); + public void setSyncRunning(boolean status); + + public SparseArray getRunningAsyncTasks(); + public void attachToRunningTask(int task_id, Activity activity, OnAsyncTaskCompletedListener listener); + + public void Start_AsyncTask_GetItems(final int task_id, final Activity context, final OnAsyncTaskCompletedListener listener, FeedItemTags.TAGS tag); + public void Start_AsyncTask_GetOldItems(final int task_id, final Activity context, final OnAsyncTaskCompletedListener listener, String feed_id, String folder_id); + + public void Start_AsyncTask_GetFolder(final int task_id, final Activity context, final OnAsyncTaskCompletedListener listener); + public void Start_AsyncTask_GetFeeds(final int task_id, final Activity context, final OnAsyncTaskCompletedListener listener); + public void Start_AsyncTask_PerformTagAction(final int task_id, final Activity context, final OnAsyncTaskCompletedListener listener, List itemIds, FeedItemTags.TAGS tag); + public void Start_AsyncTask_Authenticate(final int task_id, final Activity context, final OnAsyncTaskCompletedListener listener); + + public abstract void onAsyncTaskCompleted(final int task_id, final Object task_result); +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/InsertIntoDatabase.java b/src/de/luhmer/owncloudnewsreader/reader/InsertIntoDatabase.java index caa01131..82a7831e 100644 --- a/src/de/luhmer/owncloudnewsreader/reader/InsertIntoDatabase.java +++ b/src/de/luhmer/owncloudnewsreader/reader/InsertIntoDatabase.java @@ -1,182 +1,181 @@ -package de.luhmer.owncloudnewsreader.reader; - -import java.util.ArrayList; -import java.util.List; - -import android.app.Activity; -import android.util.Log; -import de.luhmer.owncloudnewsreader.data.ConcreteSubscribtionItem; -import de.luhmer.owncloudnewsreader.data.RssFile; -import de.luhmer.owncloudnewsreader.database.DatabaseConnection; - -/** - * Created by David on 24.05.13. - */ -public class InsertIntoDatabase { - private static final String TAG = "InsertIntoDatabase"; - - public static void InsertFoldersIntoDatabase(List tags, Activity activity) - { - DatabaseConnection dbConn = new DatabaseConnection(activity); - - - //List tags = (List) task_result; - List tagsAvailable = dbConn.convertCursorToStringArray(dbConn.getAllTopSubscriptions(false), 1); - - //dbConn.getDatabase().beginTransaction(); - try - { - if(tags != null) - { - List tagsToAdd = new ArrayList(); - for(String[] t : tags) - { - String label = t[0]; - String label_path = t[1]; - if(!tagsAvailable.contains(label)) - { - tagsToAdd.add(label); - dbConn.insertNewFolder(label, label_path); - } - } - - List tagsToRemove = new ArrayList(); - - - List newLabelList = new ArrayList(); - for(String[] subTag : tags) - newLabelList.add(subTag[0]); - - for(String tag : tagsAvailable) - { - if(!newLabelList.contains(tag)) - { - tagsToRemove.add(tag); - int result = dbConn.removeFolderByFolderLabel(tag); - Log.d(TAG, "Result delete: " + result); - } - } - - Log.d("ADD", ""+ tagsToAdd.size()); - Log.d("REMOVE", ""+ tagsToRemove.size()); - } - //dbConn.getDatabase().setTransactionSuccessful(); - } finally { - //dbConn.getDatabase().endTransaction(); - } - - - dbConn.closeDatabase(); - } - - public static void InsertSubscriptionsIntoDatabase(ArrayList tags, Activity activity) - { - DatabaseConnection dbConn = new DatabaseConnection(activity); - - List tagsAvailable = dbConn.convertCursorToStringArray(dbConn.getAllSubSubscriptions(), 1); - - //dbConn.getDatabase().beginTransaction(); - try - { - if(tags != null) - { - for(ConcreteSubscribtionItem tag : tags) - { - if(!tagsAvailable.contains(tag.header)) - { - String folderID_db = dbConn.getIdOfFolderByLabelPath(String.valueOf(tag.folder_id)); - dbConn.insertNewFeed(tag.header, folderID_db, tag.subscription_id, tag.favIcon); - } else { - String folderID_db = dbConn.getIdOfFolderByLabelPath(String.valueOf(tag.folder_id)); - int result = dbConn.updateFeed(tag.header, folderID_db, tag.subscription_id, tag.favIcon); - Log.d(TAG, "Affected Rows: " + result); - } - } - - //tags.clear(); - - for(String tag : tagsAvailable) - { - boolean found = false; - for(int i = 0; i < tags.size(); i++) - { - if(tags.get(i).header.contains(tag)) - { - found = true; - break; - } - } - if(!found) - { - int result = dbConn.removeTopSubscriptionItemByTag(tag); - Log.d(TAG, "Remove Subscription: " + result); - } - } - - //lvAdapter.notifyDataSetChanged(); - - //lvAdapter = new SubscriptionExpandableListAdapter(getActivity(), dbConn); - } - //dbConn.getDatabase().setTransactionSuccessful(); - } finally { - //dbConn.getDatabase().endTransaction(); - } - dbConn.closeDatabase(); - } - - - public static void InsertFeedItemsIntoDatabase(List files, Activity activity) - { - DatabaseConnection dbConn = new DatabaseConnection(activity); - - //dbConn.getDatabase().beginTransaction(); - try - { - if(files != null) - { - for (RssFile rssFile : files) - InsertSingleFeedItemIntoDatabase(rssFile, dbConn); - } - //dbConn.getDatabase().setTransactionSuccessful(); - } finally { - //dbConn.getDatabase().endTransaction(); - } - - dbConn.closeDatabase(); - } - - public static void InsertSingleFeedItemIntoDatabase(RssFile rssFile, DatabaseConnection dbConn) - { - if(rssFile != null) - { - Boolean isFeedAlreadyInDatabase = dbConn.doesRssItemAlreadyExsists(rssFile.getItem_Id()); - - if(isFeedAlreadyInDatabase) - { - int result = dbConn.removeItemByItemId(rssFile.getItem_Id()); - Log.d(TAG, "Delete Item: " + result); - } - - String FeedId_Db = dbConn.getRowIdBySubscriptionID(String.valueOf(rssFile.getFeedID())); - //String IdSubscription = dbConn.getIdSubscriptionByStreamID(rssFile.getFeedID()); - if(FeedId_Db != null) - { - rssFile.setFeedID_Db(FeedId_Db); - //if(!dbConn.doesRssItemAlreadyExsists(rssFile.getFeedID())) - dbConn.insertNewItem(rssFile.getTitle(), - rssFile.getLink(), - rssFile.getDescription(), - rssFile.getRead(), - String.valueOf(rssFile.getFeedID_Db()), - rssFile.getItem_Id(), - rssFile.getDate(), - rssFile.getStarred(), - rssFile.getGuid(), - rssFile.getGuidHash(), - rssFile.getLastModified()); - - dbConn.clearDatabaseOverSize(); - } - } - } -} +package de.luhmer.owncloudnewsreader.reader; + +import java.util.ArrayList; +import java.util.List; + +import android.app.Activity; +import android.util.Log; +import de.luhmer.owncloudnewsreader.data.ConcreteFeedItem; +import de.luhmer.owncloudnewsreader.data.RssFile; +import de.luhmer.owncloudnewsreader.database.DatabaseConnection; + +/** + * Created by David on 24.05.13. + */ +public class InsertIntoDatabase { + private static final String TAG = "InsertIntoDatabase"; + + public static void InsertFoldersIntoDatabase(List tags, DatabaseConnection dbConn) + { + //DatabaseConnection dbConn = new DatabaseConnection(activity); + + //List tags = (List) task_result; + List tagsAvailable = dbConn.convertCursorToStringArray(dbConn.getAllTopSubscriptions(false), 1); + + //dbConn.getDatabase().beginTransaction(); + try + { + if(tags != null) + { + List tagsToAdd = new ArrayList(); + for(String[] t : tags) + { + String label = t[0]; + String label_path = t[1]; + if(!tagsAvailable.contains(label)) + { + tagsToAdd.add(label); + dbConn.insertNewFolder(label, label_path); + } + } + + List tagsToRemove = new ArrayList(); + + + List newLabelList = new ArrayList(); + for(String[] subTag : tags) + newLabelList.add(subTag[0]); + + for(String tag : tagsAvailable) + { + if(!newLabelList.contains(tag)) + { + tagsToRemove.add(tag); + int result = dbConn.removeFolderByFolderLabel(tag); + Log.d(TAG, "Result delete: " + result); + } + } + + Log.d("ADD", ""+ tagsToAdd.size()); + Log.d("REMOVE", ""+ tagsToRemove.size()); + } + //dbConn.getDatabase().setTransactionSuccessful(); + } finally { + //dbConn.getDatabase().endTransaction(); + } + + + //dbConn.closeDatabase(); + } + + public static void InsertSubscriptionsIntoDatabase(ArrayList tags, DatabaseConnection dbConn) + { + //DatabaseConnection dbConn = new DatabaseConnection(activity); + + List tagsAvailable = dbConn.convertCursorToStringArray(dbConn.getAllSubSubscriptions(), 1); + + //dbConn.getDatabase().beginTransaction(); + try + { + if(tags != null) + { + for(ConcreteFeedItem tag : tags) + { + if(!tagsAvailable.contains(tag.header)) + { + String folderID_db = dbConn.getIdOfFolderByLabelPath(String.valueOf(tag.folder_id)); + dbConn.insertNewFeed(tag.header, folderID_db, tag.subscription_id, tag.favIcon); + } else { + String folderID_db = dbConn.getIdOfFolderByLabelPath(String.valueOf(tag.folder_id)); + int result = dbConn.updateFeed(tag.header, folderID_db, tag.subscription_id, tag.favIcon); + Log.d(TAG, "Affected Rows: " + result); + } + } + + //tags.clear(); + + for(String tag : tagsAvailable) + { + boolean found = false; + for(int i = 0; i < tags.size(); i++) + { + if(tags.get(i).header.contains(tag)) + { + found = true; + break; + } + } + if(!found) + { + int result = dbConn.removeTopSubscriptionItemByTag(tag); + Log.d(TAG, "Remove Subscription: " + result); + } + } + + //lvAdapter.notifyDataSetChanged(); + + //lvAdapter = new SubscriptionExpandableListAdapter(getActivity(), dbConn); + } + //dbConn.getDatabase().setTransactionSuccessful(); + } finally { + //dbConn.getDatabase().endTransaction(); + } + //dbConn.closeDatabase(); + } + + + public static void InsertFeedItemsIntoDatabase(List files, Activity activity) + { + DatabaseConnection dbConn = new DatabaseConnection(activity); + + //dbConn.getDatabase().beginTransaction(); + try + { + if(files != null) + { + for (RssFile rssFile : files) + InsertSingleFeedItemIntoDatabase(rssFile, dbConn); + } + //dbConn.getDatabase().setTransactionSuccessful(); + } finally { + //dbConn.getDatabase().endTransaction(); + } + + dbConn.closeDatabase(); + } + + public static void InsertSingleFeedItemIntoDatabase(RssFile rssFile, DatabaseConnection dbConn) + { + if(rssFile != null) + { + Boolean isFeedAlreadyInDatabase = dbConn.doesRssItemAlreadyExsists(rssFile.getItem_Id()); + + if(isFeedAlreadyInDatabase) + { + int result = dbConn.removeItemByItemId(rssFile.getItem_Id()); + Log.d(TAG, "Delete Item: " + result); + } + + String FeedId_Db = dbConn.getRowIdBySubscriptionID(String.valueOf(rssFile.getFeedID())); + //String IdSubscription = dbConn.getIdSubscriptionByStreamID(rssFile.getFeedID()); + if(FeedId_Db != null) + { + rssFile.setFeedID_Db(FeedId_Db); + //if(!dbConn.doesRssItemAlreadyExsists(rssFile.getFeedID())) + dbConn.insertNewItem(rssFile.getTitle(), + rssFile.getLink(), + rssFile.getDescription(), + rssFile.getRead(), + String.valueOf(rssFile.getFeedID_Db()), + rssFile.getItem_Id(), + rssFile.getDate(), + rssFile.getStarred(), + rssFile.getGuid(), + rssFile.getGuidHash(), + rssFile.getLastModified()); + + dbConn.clearDatabaseOverSize(); + } + } + } +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/API.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/API.java new file mode 100644 index 00000000..4ae8cb6b --- /dev/null +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/API.java @@ -0,0 +1,58 @@ +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import java.util.List; + +import android.app.Activity; +import android.content.Context; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; +import de.luhmer.owncloudnewsreader.SettingsActivity; +import de.luhmer.owncloudnewsreader.reader.FeedItemTags; +import de.luhmer.owncloudnewsreader.reader.FeedItemTags.TAGS; + +public abstract class API { + protected SharedPreferences mPrefs; + + public API(Activity act) { + mPrefs = PreferenceManager.getDefaultSharedPreferences(act); + } + + protected abstract String getItemUrl(); + protected abstract String getItemUpdatedUrl(); + protected abstract String getFeedUrl(); + protected abstract String getFolderUrl(); + + protected abstract String getTagBaseUrl(); + + //public abstract void markSingleItemAsReadApiv1(); + + public String getUsername() { + return mPrefs.getString(SettingsActivity.EDT_USERNAME_STRING, null); + } + + public String getPassword() { + return mPrefs.getString(SettingsActivity.EDT_PASSWORD_STRING, null); + } + + public int GetFeeds(Activity act, API api) throws Exception { + return OwnCloudReaderMethods.GetFeeds(act, api); + } + + public int GetFolderTags(Activity act, API api) throws Exception { + return OwnCloudReaderMethods.GetFolderTags(act, api); + } + + public int GetItems(TAGS tag, Activity act, String offset, boolean getRead, String id, String type, API api) throws Exception { + return OwnCloudReaderMethods.GetItems(tag, act, offset, getRead, id, type, api); + } + + public int GetUpdatedItems(TAGS tag, Activity act, long lastSync, API api) throws Exception { + return OwnCloudReaderMethods.GetUpdatedItems(tag, act, lastSync, api); + } + + public abstract boolean PerformTagExecution(List itemIds, FeedItemTags.TAGS tag, Context context, API api); + /* + public boolean PerformTagExecution(List itemIds, FeedItemTags.TAGS tag, Context context, API api) { + return OwnCloudReaderMethods.PerformTagExecution(itemIds, tag, context, api); + }*/ +} \ No newline at end of file diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetApiVersion.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetApiVersion.java new file mode 100644 index 00000000..086309ea --- /dev/null +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetApiVersion.java @@ -0,0 +1,33 @@ +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import android.app.Activity; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; +import de.luhmer.owncloudnewsreader.SettingsActivity; +import de.luhmer.owncloudnewsreader.reader.AsyncTask_Reader; +import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; + +public class AsyncTask_GetApiVersion extends AsyncTask_Reader { + + private String username; + private String password; + + public AsyncTask_GetApiVersion(final int task_id, final Activity context, String username, String password, final OnAsyncTaskCompletedListener[] listener) { + super(task_id, context, listener); + + this.username = username; + this.password = password; + } + + @Override + protected Object doInBackground(Object... params) { + try { + SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context); + String oc_root_path = mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, ""); + return OwnCloudReaderMethods.GetVersionNumber(context, username, password, oc_root_path); + } catch (Exception ex) { + return ex; + } + } +} + diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetFeeds.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetFeeds.java index 0e8405ed..0db99e75 100644 --- a/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetFeeds.java +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetFeeds.java @@ -1,60 +1,26 @@ -package de.luhmer.owncloudnewsreader.reader.owncloud; - -import android.app.Activity; -import android.os.AsyncTask; -import de.luhmer.owncloudnewsreader.reader.AsyncTask_Reader; -import de.luhmer.owncloudnewsreader.reader.InsertIntoDatabase; -import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; - -public class AsyncTask_GetFeeds extends AsyncTask implements AsyncTask_Reader { - - private Activity context; - private int task_id; - private OnAsyncTaskCompletedListener[] listener; - - public AsyncTask_GetFeeds(final int task_id, final Activity context, final OnAsyncTaskCompletedListener[] listener) { - super(); - - this.context = context; - this.task_id = task_id; - this.listener = listener; - } - - //Activity meldet sich zurueck nach OrientationChange - public void attach(final Activity context, final OnAsyncTaskCompletedListener[] listener) { - this.context = context; - this.listener = listener; - } - - //Activity meldet sich ab - public void detach() { - if (context != null) { - context = null; - } - - if (listener != null) { - listener = null; - } - } - - - @Override - protected Exception doInBackground(Object... params) { - try { - InsertIntoDatabase.InsertSubscriptionsIntoDatabase(OwnCloudReaderMethods.GetSubscriptionTags(context), context); - } catch (Exception ex) { - return ex; - } - return null; - } - - @Override - protected void onPostExecute(Exception ex) { - for (OnAsyncTaskCompletedListener listenerInstance : listener) { - if(listenerInstance != null) - listenerInstance.onAsyncTaskCompleted(task_id, ex); - } - - detach(); - } -} +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import android.app.Activity; +import de.luhmer.owncloudnewsreader.reader.AsyncTask_Reader; +import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; +import de.luhmer.owncloudnewsreader.reader.owncloud.apiv2.APIv2; + +public class AsyncTask_GetFeeds extends AsyncTask_Reader { + + public AsyncTask_GetFeeds(final int task_id, final Activity context, final OnAsyncTaskCompletedListener[] listener) { + super(task_id, context, listener); + } + + @Override + protected Exception doInBackground(Object... params) { + API api = new APIv2(context); + + try { + api.GetFeeds(context, api); + //OwnCloudReaderMethods.GetFeeds(context, api); + } catch (Exception ex) { + return ex; + } + return null; + } +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetFolderTags.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetFolderTags.java index b3af5388..94b22cfb 100644 --- a/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetFolderTags.java +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetFolderTags.java @@ -1,65 +1,26 @@ -package de.luhmer.owncloudnewsreader.reader.owncloud; - -import android.app.Activity; -import android.os.AsyncTask; -import de.luhmer.owncloudnewsreader.reader.AsyncTask_Reader; -import de.luhmer.owncloudnewsreader.reader.InsertIntoDatabase; -import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; - -public class AsyncTask_GetFolderTags extends AsyncTask implements AsyncTask_Reader { - - private Activity context; - private int task_id; - private OnAsyncTaskCompletedListener[] listener; - - public AsyncTask_GetFolderTags(final int task_id, final Activity context, final OnAsyncTaskCompletedListener[] listener) { - super(); - - this.context = context; - this.task_id = task_id; - this.listener = listener; - } - - //Activity meldet sich zurueck nach OrientationChange - public void attach(final Activity context, final OnAsyncTaskCompletedListener[] listener) { - this.context = context; - this.listener = listener; - } - - //Activity meldet sich ab - public void detach() { - if (context != null) { - context = null; - } - - if (listener != null) { - listener = null; - } - } - - - @Override - protected Exception doInBackground(Object... params) { - /* - String username = (String) params[0]; - String password = (String) params[1]; - */ - - try { - InsertIntoDatabase.InsertFoldersIntoDatabase(OwnCloudReaderMethods.GetFolderTags(context), context); - } catch(Exception ex) { - return ex; - } - return null; - } - - @Override - protected void onPostExecute(Exception ex) { - for (OnAsyncTaskCompletedListener listenerInstance : listener) { - if(listenerInstance != null) - listenerInstance.onAsyncTaskCompleted(task_id, ex); - } - - detach(); - } -} +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import android.app.Activity; +import de.luhmer.owncloudnewsreader.reader.AsyncTask_Reader; +import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; +import de.luhmer.owncloudnewsreader.reader.owncloud.apiv2.APIv2; + +public class AsyncTask_GetFolderTags extends AsyncTask_Reader { + + public AsyncTask_GetFolderTags(final int task_id, final Activity context, final OnAsyncTaskCompletedListener[] listener) { + super(task_id, context, listener); + } + + @Override + protected Exception doInBackground(Object... params) { + API api = new APIv2(context); + + try { + //OwnCloudReaderMethods.GetFolderTags(context, api); + api.GetFolderTags(context, api); + } catch(Exception ex) { + return ex; + } + return null; + } +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetItems.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetItems.java index a115ad88..76b922d5 100644 --- a/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetItems.java +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetItems.java @@ -1,204 +1,133 @@ -package de.luhmer.owncloudnewsreader.reader.owncloud; - -import android.app.Activity; -import android.app.AlertDialog; -import android.content.DialogInterface; -import android.content.Intent; -import android.content.SharedPreferences; -import android.os.AsyncTask; -import android.preference.PreferenceManager; -import de.luhmer.owncloudnewsreader.R; -import de.luhmer.owncloudnewsreader.SettingsActivity; -import de.luhmer.owncloudnewsreader.database.DatabaseConnection; -import de.luhmer.owncloudnewsreader.helper.NetworkConnection; -import de.luhmer.owncloudnewsreader.reader.AsyncTask_Reader; -import de.luhmer.owncloudnewsreader.reader.FeedItemTags.TAGS; -import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; -import de.luhmer.owncloudnewsreader.services.DownloadImagesService; - -public class AsyncTask_GetItems extends AsyncTask implements AsyncTask_Reader { - - private Activity context; - private int task_id; - private OnAsyncTaskCompletedListener[] listener; - private long highestItemIdBeforeSync; - - public AsyncTask_GetItems(final int task_id, final Activity context, final OnAsyncTaskCompletedListener[] listener) { - super(); - - this.context = context; - this.task_id = task_id; - this.listener = listener; - } - - //Activity meldet sich zurueck nach OrientationChange - public void attach(final Activity context, final OnAsyncTaskCompletedListener[] listener) { - this.context = context; - this.listener = listener; - } - - //Activity meldet sich ab - public void detach() { - if (context != null) { - context = null; - } - - if (listener != null) { - listener = null; - } - } - - @Override - protected Exception doInBackground(Object... params) { - //FeedItemTags.TAGS tag = (TAGS) params[0]; - /* - String username = (String) params[0]; - String password = (String) params[1]; - String _TAG_LABEL = (String) params[2]; - */ - - DatabaseConnection dbConn = new DatabaseConnection(context); - try { - //String authKey = AuthenticationManager.getGoogleAuthKey(username, password); - //SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context); - //int maxItemsInDatabase = Integer.parseInt(mPrefs.getString(SettingsActivity.SP_MAX_ITEMS_SYNC, "200")); - - long lastModified = dbConn.getLastModfied(); - - //List files; - long offset = dbConn.getLowestItemId(false); - //int totalCount = 0; - int requestCount = 0; - int maxSyncSize = Integer.parseInt(OwnCloudReaderMethods.maxSizePerSync); - - highestItemIdBeforeSync = dbConn.getHighestItemId(); - - if(lastModified == 0) - { - //init startup - do { - requestCount = OwnCloudReaderMethods.GetItems(TAGS.ALL, context, String.valueOf(offset), false, "0", "3"); - if(requestCount > 0) - offset = dbConn.getLowestItemId(false); - //totalCount += requestCount; - } while(requestCount == maxSyncSize /*&& totalCount < maxItemsInDatabase*/); - - do { - offset = dbConn.getLowestItemId(true); - requestCount = OwnCloudReaderMethods.GetItems(TAGS.ALL_STARRED, context, String.valueOf(offset), true, "0", "2"); - if(requestCount > 0) - offset = dbConn.getLowestItemId(true); - } while(requestCount == maxSyncSize); - } - else - { - //OwnCloudReaderMethods.GetUpdatedItems(tag, context, lastModified, true); - OwnCloudReaderMethods.GetUpdatedItems(TAGS.ALL, context, lastModified); - //OwnCloudReaderMethods.GetUpdatedItems(TAGS.ALL_STARRED, context, lastModified); - } - - /* - //Get all unread items which are older then the latest item id in db - do { - requestCount = OwnCloudReaderMethods.GetItems(tag, context, String.valueOf(offset), false); - //InsertIntoDatabase.InsertFeedItemsIntoDatabase(files, context); - - if(requestCount > 0) - offset = dbConn.getLowestItemId(); - - totalCount += requestCount; - } while(requestCount == maxSyncSize && totalCount < maxItemsInDatabase); - - - if(lastModified == 0 && totalCount < maxItemsInDatabase)//If the app should sync all the items in past. - { - do { - requestCount = OwnCloudReaderMethods.GetItems(tag, context, String.valueOf(offset), true); - //InsertIntoDatabase.InsertFeedItemsIntoDatabase(files, context); - - if(requestCount > 0) - offset = dbConn.getLowestItemId(); - - totalCount += requestCount; - } while(requestCount == maxSyncSize && totalCount < maxItemsInDatabase); - } - else if(lastModified != 0) - { - OwnCloudReaderMethods.GetUpdatedItems(tag, context, lastModified, true); - //InsertIntoDatabase.InsertFeedItemsIntoDatabase(files, context); - } - - if(dbConn.getCountOfAllItems(true) > maxItemsInDatabase && !tag.equals(FeedItemTags.TAGS.ALL_STARRED))//Remove all old items which are over the limit of maxItemsInDatabase - { - String id_db = String.valueOf(dbConn.getItemDbIdAtPosition(maxItemsInDatabase)); - dbConn.removeAllItemsWithIdLowerThan(id_db); - }*/ - } catch (Exception ex) { - return ex; - } finally { - dbConn.closeDatabase(); - } - return null; - } - - @Override - protected void onPostExecute(Exception ex) { - for (OnAsyncTaskCompletedListener listenerInstance : listener) { - if(listenerInstance != null) - listenerInstance.onAsyncTaskCompleted(task_id, ex); - } - /* - if(task_id == 3)//All Starred Item request was performed - { - Intent service = new Intent(context, DownloadImagesService.class); - context.startService(service); - }*/ - - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context); - if(mPrefs.getBoolean(SettingsActivity.CB_CACHE_IMAGES_OFFLINE_STRING, false)) - { - if(!NetworkConnection.isWLANConnected(context) && NetworkConnection.isNetworkAvailable(context)) - ShowDownloadImageWithoutWifiQuestion(); - else if(NetworkConnection.isNetworkAvailable(context)) - StartDownloadingImages(); - } - - - detach(); - } - - private void StartDownloadingImages() - { - DatabaseConnection dbConn = new DatabaseConnection(context); - try { - Intent service = new Intent(context, DownloadImagesService.class); - service.putExtra(DownloadImagesService.LAST_ITEM_ID, highestItemIdBeforeSync); - context.startService(service); - } finally { - dbConn.closeDatabase(); - } - } - - - private void ShowDownloadImageWithoutWifiQuestion() - { - AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); - - // set title - alertDialogBuilder.setTitle(context.getString(R.string.no_wifi_available)); - - // set dialog message - alertDialogBuilder - .setMessage(context.getString(R.string.do_you_want_to_download_without_wifi)) - .setCancelable(true) - .setPositiveButton("Yes",new DialogInterface.OnClickListener() { - public void onClick(DialogInterface dialog,int id) { - StartDownloadingImages(); - } - }); - - AlertDialog alertDialog = alertDialogBuilder.create(); - - alertDialog.show(); - } -} +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import android.app.Activity; +import android.app.AlertDialog; +import android.content.DialogInterface; +import android.content.Intent; +import android.content.SharedPreferences; +import android.preference.PreferenceManager; +import de.luhmer.owncloudnewsreader.Constants; +import de.luhmer.owncloudnewsreader.R; +import de.luhmer.owncloudnewsreader.SettingsActivity; +import de.luhmer.owncloudnewsreader.database.DatabaseConnection; +import de.luhmer.owncloudnewsreader.helper.NetworkConnection; +import de.luhmer.owncloudnewsreader.reader.AsyncTask_Reader; +import de.luhmer.owncloudnewsreader.reader.FeedItemTags.TAGS; +import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; +import de.luhmer.owncloudnewsreader.reader.owncloud.apiv2.APIv2; +import de.luhmer.owncloudnewsreader.services.DownloadImagesService; + +public class AsyncTask_GetItems extends AsyncTask_Reader { + private long highestItemIdBeforeSync; + + public AsyncTask_GetItems(final int task_id, final Activity context, final OnAsyncTaskCompletedListener[] listener) { + super(task_id, context, listener); + } + + @Override + protected Exception doInBackground(Object... params) { + DatabaseConnection dbConn = new DatabaseConnection(context); + try { + //String authKey = AuthenticationManager.getGoogleAuthKey(username, password); + //SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context); + //int maxItemsInDatabase = Integer.parseInt(mPrefs.getString(SettingsActivity.SP_MAX_ITEMS_SYNC, "200")); + + long lastModified = dbConn.getLastModfied(); + + //List files; + long offset = dbConn.getLowestItemId(false); + int totalCount = 0; + int requestCount = 0; + int maxSyncSize = Integer.parseInt(OwnCloudReaderMethods.maxSizePerSync); + int maxItemsInDatabase = Constants.maxItemsCount; + + highestItemIdBeforeSync = dbConn.getHighestItemId(); + + API api = new APIv2(context); + + if(lastModified == 0) + { + do { + requestCount = api.GetItems(TAGS.ALL, context, String.valueOf(offset), false, "0", "3", api); + if(requestCount > 0) + offset = dbConn.getLowestItemId(false); + totalCount += requestCount; + } while(requestCount == maxSyncSize /* && totalCount < maxItemsInDatabase */); + + do { + offset = dbConn.getLowestItemId(true); + requestCount = api.GetItems(TAGS.ALL_STARRED, context, String.valueOf(offset), true, "0", "2", api); + if(requestCount > 0) + offset = dbConn.getLowestItemId(true); + totalCount += requestCount; + } while(requestCount == maxSyncSize && totalCount < maxItemsInDatabase); + } + else + { + api.GetUpdatedItems(TAGS.ALL, context, lastModified, api); + //OwnCloudReaderMethods.GetUpdatedItems(TAGS.ALL, context, lastModified, api); + + } + } catch (Exception ex) { + return ex; + } finally { + dbConn.closeDatabase(); + } + return null; + } + + @Override + protected void onPostExecute(Object ex) { + for (OnAsyncTaskCompletedListener listenerInstance : listener) { + if(listenerInstance != null) + listenerInstance.onAsyncTaskCompleted(task_id, ex); + } + + SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context); + if(mPrefs.getBoolean(SettingsActivity.CB_CACHE_IMAGES_OFFLINE_STRING, false)) + { + if(!NetworkConnection.isWLANConnected(context) && NetworkConnection.isNetworkAvailable(context)) + ShowDownloadImageWithoutWifiQuestion(); + else if(NetworkConnection.isNetworkAvailable(context)) + StartDownloadingImages(); + } + + + detach(); + } + + private void StartDownloadingImages() + { + DatabaseConnection dbConn = new DatabaseConnection(context); + try { + Intent service = new Intent(context, DownloadImagesService.class); + service.putExtra(DownloadImagesService.LAST_ITEM_ID, highestItemIdBeforeSync); + context.startService(service); + } finally { + dbConn.closeDatabase(); + } + } + + + private void ShowDownloadImageWithoutWifiQuestion() + { + AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context); + + // set title + alertDialogBuilder.setTitle(context.getString(R.string.no_wifi_available)); + + // set dialog message + alertDialogBuilder + .setMessage(context.getString(R.string.do_you_want_to_download_without_wifi)) + .setCancelable(true) + .setPositiveButton("Yes",new DialogInterface.OnClickListener() { + public void onClick(DialogInterface dialog,int id) { + StartDownloadingImages(); + } + }); + + AlertDialog alertDialog = alertDialogBuilder.create(); + + alertDialog.show(); + } +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetOldItems.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetOldItems.java index ea007cc6..a2791979 100644 --- a/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetOldItems.java +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_GetOldItems.java @@ -1,125 +1,103 @@ -package de.luhmer.owncloudnewsreader.reader.owncloud; - -import android.app.Activity; -import android.os.AsyncTask; -import android.widget.Toast; -import de.luhmer.owncloudnewsreader.R; -import de.luhmer.owncloudnewsreader.ListView.SubscriptionExpandableListAdapter; -import de.luhmer.owncloudnewsreader.database.DatabaseConnection; -import de.luhmer.owncloudnewsreader.reader.AsyncTask_Reader; -import de.luhmer.owncloudnewsreader.reader.FeedItemTags.TAGS; -import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; - -public class AsyncTask_GetOldItems extends AsyncTask implements AsyncTask_Reader { - - private Activity context; - private int task_id; - private OnAsyncTaskCompletedListener[] listener; - public String feed_id; - public String folder_id; - private int downloadedItemsCount = 0; - - public AsyncTask_GetOldItems(final int task_id, final Activity context, final OnAsyncTaskCompletedListener[] listener, String feed_id, String folder_id) { - super(); - - this.context = context; - this.task_id = task_id; - this.listener = listener; - this.feed_id = feed_id; - this.folder_id = folder_id; - } - - //Activity meldet sich zurueck nach OrientationChange - public void attach(final Activity context, final OnAsyncTaskCompletedListener[] listener) { - this.context = context; - this.listener = listener; - } - - //Activity meldet sich ab - public void detach() { - if (context != null) { - context = null; - } - - if (listener != null) { - listener = null; - } - } - - @Override - protected Exception doInBackground(Object... params) { - DatabaseConnection dbConn = new DatabaseConnection(context); - try { - long offset = 0; - //int requestCount = 0; - //int maxSyncSize = Integer.parseInt(OwnCloudReaderMethods.maxSizePerSync); - String id = null; - String type = null; - - if(feed_id != null) - { - offset = dbConn.getLowestItemIdByFeed(feed_id); - id = dbConn.getSubscriptionIdByRowID(feed_id); - type = "0"; - } - else if(folder_id != null) - { - if(folder_id.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS)) - { - offset = dbConn.getLowestItemIdStarred(); - id = "0"; - type = "2"; - } else { - offset = dbConn.getLowestItemIdByFolder(folder_id); - id = dbConn.getIdOfFolderByLabelPath(folder_id); - type = "1"; - } - } - - - downloadedItemsCount = OwnCloudReaderMethods.GetItems(TAGS.ALL, context, String.valueOf(offset), true, id, type); - - - //do { - //requestCount = OwnCloudReaderMethods.GetItems(TAGS.ALL, context, String.valueOf(offset), true, feed_id); - // if(requestCount > 0) - // offset = dbConn.getLowestItemIdByFeed(feed_id); - //} while(requestCount == maxSyncSize); - - } catch (Exception ex) { - return ex; - } finally { - dbConn.closeDatabase(); - } - return null; - } - - @Override - protected void onPostExecute(Exception ex) { - for (OnAsyncTaskCompletedListener listenerInstance : listener) { - if(listenerInstance != null) - listenerInstance.onAsyncTaskCompleted(task_id, ex); - } - - if(downloadedItemsCount == 0) - Toast.makeText(context, context.getString(R.string.toast_no_more_downloads_available), Toast.LENGTH_LONG).show(); - else - { - String text = context.getString(R.string.toast_downloaded_x_items).replace("X", String.valueOf(downloadedItemsCount)); - Toast.makeText(context, text, Toast.LENGTH_LONG).show(); - } - - /* - DatabaseConnection dbConn = new DatabaseConnection(context); - try { - Intent service = new Intent(context, DownloadImagesService.class); - service.putExtra(DownloadImagesService.LAST_ITEM_ID, highestItemIdBeforeSync); - context.startService(service); - } finally { - dbConn.closeDatabase(); - } - */ - - detach(); - } -} +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import android.app.Activity; +import android.widget.Toast; +import de.luhmer.owncloudnewsreader.R; +import de.luhmer.owncloudnewsreader.ListView.SubscriptionExpandableListAdapter; +import de.luhmer.owncloudnewsreader.database.DatabaseConnection; +import de.luhmer.owncloudnewsreader.reader.AsyncTask_Reader; +import de.luhmer.owncloudnewsreader.reader.FeedItemTags.TAGS; +import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; +import de.luhmer.owncloudnewsreader.reader.owncloud.apiv2.APIv2; + +public class AsyncTask_GetOldItems extends AsyncTask_Reader { + + public String feed_id; + public String folder_id; + private int downloadedItemsCount = 0; + + public AsyncTask_GetOldItems(final int task_id, final Activity context, final OnAsyncTaskCompletedListener[] listener, String feed_id, String folder_id) { + super(task_id, context, listener); + + this.feed_id = feed_id; + this.folder_id = folder_id; + } + + @Override + protected Exception doInBackground(Object... params) { + DatabaseConnection dbConn = new DatabaseConnection(context); + try { + long offset = 0; + //int requestCount = 0; + //int maxSyncSize = Integer.parseInt(OwnCloudReaderMethods.maxSizePerSync); + String id = null; + String type = null; + + if(feed_id != null) + { + offset = dbConn.getLowestItemIdByFeed(feed_id); + id = dbConn.getSubscriptionIdByRowID(feed_id); + type = "0"; + } + else if(folder_id != null) + { + if(folder_id.equals(SubscriptionExpandableListAdapter.ALL_STARRED_ITEMS)) + { + offset = dbConn.getLowestItemIdStarred(); + id = "0"; + type = "2"; + } else { + offset = dbConn.getLowestItemIdByFolder(folder_id); + id = dbConn.getIdOfFolderByLabelPath(folder_id); + type = "1"; + } + } + + API api = new APIv2(context); + downloadedItemsCount = api.GetItems(TAGS.ALL, context, String.valueOf(offset), true, id, type, api); + //downloadedItemsCount = OwnCloudReaderMethods.GetItems(TAGS.ALL, context, String.valueOf(offset), true, id, type, api); + + + //do { + //requestCount = OwnCloudReaderMethods.GetItems(TAGS.ALL, context, String.valueOf(offset), true, feed_id); + // if(requestCount > 0) + // offset = dbConn.getLowestItemIdByFeed(feed_id); + //} while(requestCount == maxSyncSize); + + } catch (Exception ex) { + return ex; + } finally { + dbConn.closeDatabase(); + } + return null; + } + + @Override + protected void onPostExecute(Object ex) { + for (OnAsyncTaskCompletedListener listenerInstance : listener) { + if(listenerInstance != null) + listenerInstance.onAsyncTaskCompleted(task_id, ex); + } + + if(downloadedItemsCount == 0) + Toast.makeText(context, context.getString(R.string.toast_no_more_downloads_available), Toast.LENGTH_LONG).show(); + else + { + String text = context.getString(R.string.toast_downloaded_x_items).replace("X", String.valueOf(downloadedItemsCount)); + Toast.makeText(context, text, Toast.LENGTH_LONG).show(); + } + + /* + DatabaseConnection dbConn = new DatabaseConnection(context); + try { + Intent service = new Intent(context, DownloadImagesService.class); + service.putExtra(DownloadImagesService.LAST_ITEM_ID, highestItemIdBeforeSync); + context.startService(service); + } finally { + dbConn.closeDatabase(); + } + */ + + detach(); + } +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_PerformTagAction.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_PerformTagAction.java index 79fe91bb..a81ebb6b 100644 --- a/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_PerformTagAction.java +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/AsyncTask_PerformTagAction.java @@ -1,71 +1,47 @@ -package de.luhmer.owncloudnewsreader.reader.owncloud; - -import java.util.List; - -import android.app.Activity; -import android.content.Context; -import android.os.AsyncTask; -import de.luhmer.owncloudnewsreader.reader.AsyncTask_Reader; -import de.luhmer.owncloudnewsreader.reader.FeedItemTags.TAGS; -import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; - -public class AsyncTask_PerformTagAction extends AsyncTask implements AsyncTask_Reader { - - private Context context; - private int task_id; - private OnAsyncTaskCompletedListener[] listener; - - public AsyncTask_PerformTagAction(final int task_id, final Context context, final OnAsyncTaskCompletedListener[] listener) { - super(); - - this.context = context; - this.task_id = task_id; - this.listener = listener; - } - - //Activity meldet sich zurueck nach OrientationChange - public void attach(final Activity context, final OnAsyncTaskCompletedListener[] listener) { - this.context = context; - this.listener = listener; - } - - //Activity meldet sich ab - public void detach() { - if (context != null) { - context = null; - } - - if (listener != null) { - listener = null; - } - } - - - @SuppressWarnings("unchecked") - @Override - protected Boolean doInBackground(Object... params) { - List itemIds = (List) params[0]; - TAGS tag = (TAGS) params[1]; - - try { - //String authKey = AuthenticationManager.getGoogleAuthKey(username, password); - if(itemIds.size() > 0) - return OwnCloudReaderMethods.PerformTagExecution(itemIds, tag, context); - else - return true; - } catch (Exception e) { - e.printStackTrace(); - } - return null; - } - - @Override - protected void onPostExecute(Boolean values) { - for (OnAsyncTaskCompletedListener listenerInstance : listener) { - if(listenerInstance != null) - listenerInstance.onAsyncTaskCompleted(task_id, values); - } - - detach(); - } -} +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import java.util.List; + +import android.app.Activity; +import android.os.AsyncTask; +import de.luhmer.owncloudnewsreader.reader.AsyncTask_Reader; +import de.luhmer.owncloudnewsreader.reader.FeedItemTags.TAGS; +import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; +import de.luhmer.owncloudnewsreader.reader.owncloud.apiv2.APIv2; + +public class AsyncTask_PerformTagAction extends AsyncTask_Reader { + + public AsyncTask_PerformTagAction(final int task_id, final Activity context, final OnAsyncTaskCompletedListener[] listener) { + super(task_id, context, listener); + } + + @SuppressWarnings("unchecked") + @Override + protected Boolean doInBackground(Object... params) { + List itemIds = (List) params[0]; + TAGS tag = (TAGS) params[1]; + + try { + //String authKey = AuthenticationManager.getGoogleAuthKey(username, password); + API api = new APIv2(context); + + if(itemIds.size() > 0) + return api.PerformTagExecution(itemIds, tag, context, api); + else + return true; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + @Override + protected void onPostExecute(Object values) { + for (OnAsyncTaskCompletedListener listenerInstance : listener) { + if(listenerInstance != null) + listenerInstance.onAsyncTaskCompleted(task_id, values); + } + + detach(); + } +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/GetVersion.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/GetVersion.java new file mode 100644 index 00000000..eb9c8233 --- /dev/null +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/GetVersion.java @@ -0,0 +1,21 @@ +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import org.json.JSONObject; + +public class GetVersion implements IHandleJsonObject{ + + String version; + + @Override + public void performAction(JSONObject jObj) { + this.version = jObj.optString("version"); + } + + /** + * @return the version + */ + public String getVersion() { + return version; + } + +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/IHandleJsonObject.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/IHandleJsonObject.java new file mode 100644 index 00000000..f4ad987c --- /dev/null +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/IHandleJsonObject.java @@ -0,0 +1,7 @@ +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import org.json.JSONObject; + +public interface IHandleJsonObject { + public void performAction(JSONObject jObj); +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/InsertFeedIntoDatabase.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/InsertFeedIntoDatabase.java new file mode 100644 index 00000000..4be98ea6 --- /dev/null +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/InsertFeedIntoDatabase.java @@ -0,0 +1,39 @@ +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import java.util.ArrayList; + +import org.json.JSONObject; + +import de.luhmer.owncloudnewsreader.data.ConcreteFeedItem; +import de.luhmer.owncloudnewsreader.database.DatabaseConnection; +import de.luhmer.owncloudnewsreader.reader.InsertIntoDatabase; + +public class InsertFeedIntoDatabase implements IHandleJsonObject{ + + DatabaseConnection dbConn; + ArrayList feeds = new ArrayList(); + + public InsertFeedIntoDatabase(DatabaseConnection dbConn) { + this.dbConn = dbConn; + } + + private static ConcreteFeedItem parseFeed(JSONObject e) + { + String faviconLink = e.optString("faviconLink"); + if(faviconLink != null) + if(faviconLink.equals("null") || faviconLink.trim().equals("")) + faviconLink = null; + + return new ConcreteFeedItem(e.optString("title"), e.optString("folderId"), e.optString("id"), faviconLink, -1); + } + + @Override + public void performAction(JSONObject jObj) { + ConcreteFeedItem rssFeed = parseFeed(jObj); + feeds.add(rssFeed); + } + + public void WriteAllToDatabaseNow() { + InsertIntoDatabase.InsertSubscriptionsIntoDatabase(feeds, dbConn); + } +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/InsertFolderIntoDatabase.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/InsertFolderIntoDatabase.java new file mode 100644 index 00000000..d6885084 --- /dev/null +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/InsertFolderIntoDatabase.java @@ -0,0 +1,32 @@ +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import java.util.ArrayList; + +import org.json.JSONObject; + +import de.luhmer.owncloudnewsreader.database.DatabaseConnection; +import de.luhmer.owncloudnewsreader.reader.InsertIntoDatabase; + +public class InsertFolderIntoDatabase implements IHandleJsonObject{ + + DatabaseConnection dbConn; + ArrayList folders = new ArrayList(); + + public InsertFolderIntoDatabase(DatabaseConnection dbConn) { + this.dbConn = dbConn; + } + + private static String[] parseFolder(JSONObject e) + { + return new String[] { e.optString("name"), e.optString("id") }; + } + + @Override + public void performAction(JSONObject jObj) { + folders.add(parseFolder(jObj)); + } + + public void WriteAllToDatabaseNow() { + InsertIntoDatabase.InsertFoldersIntoDatabase(folders, dbConn); + } +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/InsertItemIntoDatabase.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/InsertItemIntoDatabase.java new file mode 100644 index 00000000..83f3d58e --- /dev/null +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/InsertItemIntoDatabase.java @@ -0,0 +1,44 @@ +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import java.util.Date; + +import org.json.JSONObject; + +import de.luhmer.owncloudnewsreader.data.RssFile; +import de.luhmer.owncloudnewsreader.database.DatabaseConnection; +import de.luhmer.owncloudnewsreader.reader.InsertIntoDatabase; + +public class InsertItemIntoDatabase implements IHandleJsonObject { + + DatabaseConnection dbConn; + + public InsertItemIntoDatabase(DatabaseConnection dbConn) { + this.dbConn = dbConn; + } + + private static RssFile parseItem(JSONObject e) + { + Date date = new Date(e.optLong("pubDate") * 1000); + + String content = e.optString("body"); + content = content.replaceAll("]*feedsportal.com.*>", ""); + content = content.replaceAll("]*statisches.auslieferung.commindo-media-ressourcen.de.*>", ""); + content = content.replaceAll("]*auslieferung.commindo-media-ressourcen.de.*>", ""); + content = content.replaceAll("]*rss.buysellads.com.*>", ""); + + return new RssFile(0, e.optString("id"), + e.optString("title"), + e.optString("url"), content, + !e.optBoolean("unread"), null, + e.optString("feedId"), null, + date, e.optBoolean("starred"), + e.optString("guid"), e.optString("guidHash"), + e.optString("lastModified")); + } + + @Override + public void performAction(JSONObject jObj) { + RssFile rssFile = parseItem(jObj); + InsertIntoDatabase.InsertSingleFeedItemIntoDatabase(rssFile, dbConn); + } +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/OwnCloudReaderMethods.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/OwnCloudReaderMethods.java index e3d1f17d..686986c1 100644 --- a/src/de/luhmer/owncloudnewsreader/reader/owncloud/OwnCloudReaderMethods.java +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/OwnCloudReaderMethods.java @@ -1,370 +1,401 @@ -package de.luhmer.owncloudnewsreader.reader.owncloud; - -import java.util.ArrayList; -import java.util.Date; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import org.apache.http.NameValuePair; -import org.apache.http.message.BasicNameValuePair; -import org.json.JSONArray; -import org.json.JSONObject; - -import android.app.Activity; -import android.content.Context; -import android.content.SharedPreferences; -import android.database.Cursor; -import android.preference.PreferenceManager; -import de.luhmer.owncloudnewsreader.SettingsActivity; -import de.luhmer.owncloudnewsreader.data.ConcreteSubscribtionItem; -import de.luhmer.owncloudnewsreader.data.RssFile; -import de.luhmer.owncloudnewsreader.database.DatabaseConnection; -import de.luhmer.owncloudnewsreader.reader.FeedItemTags; -import de.luhmer.owncloudnewsreader.reader.FeedItemTags.TAGS; -import de.luhmer.owncloudnewsreader.reader.HttpJsonRequest; -import de.luhmer.owncloudnewsreader.reader.InsertIntoDatabase; - -public class OwnCloudReaderMethods { - public static String maxSizePerSync = "200"; - - public static int GetUpdatedItems(TAGS tag, Activity act, long lastSync) throws Exception - { - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(act); - //ArrayList rssFiles = new ArrayList(); - - List nVPairs = new ArrayList(); - nVPairs.add(new BasicNameValuePair("batchSize", maxSizePerSync)); - if(tag.equals(TAGS.ALL_STARRED)) - { - nVPairs.add(new BasicNameValuePair("type", "2")); - nVPairs.add(new BasicNameValuePair("id", "0")); - } - else if(tag.equals(TAGS.ALL)) - { - nVPairs.add(new BasicNameValuePair("type", "3")); - nVPairs.add(new BasicNameValuePair("id", "0")); - } - nVPairs.add(new BasicNameValuePair("lastModified", String.valueOf(lastSync))); - - String username = mPrefs.getString(SettingsActivity.EDT_USERNAME_STRING, null); - String password = mPrefs.getString(SettingsActivity.EDT_PASSWORD_STRING, null); - String oc_root_path = mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, ""); - - - String requestURL = oc_root_path + OwnCloudConstants.FEED_PATH_UPDATED_ITEMS + OwnCloudConstants.JSON_FORMAT; - - JSONObject jsonObj = HttpJsonRequest.PerformJsonRequest(requestURL, nVPairs, username, password, act); - - DatabaseConnection dbConn = new DatabaseConnection(act); - try - { - return parseItems(jsonObj, dbConn, act); - } finally { - dbConn.closeDatabase(); - } - //return rssFiles; - } - - //"type": 1, // the type of the query (Feed: 0, Folder: 1, Starred: 2, All: 3) - public static int GetItems(TAGS tag, Activity act, String offset, boolean getRead, String id, String type) throws Exception - { - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(act); - //ArrayList rssFiles = new ArrayList(); - - List nVPairs = new ArrayList(); - nVPairs.add(new BasicNameValuePair("batchSize", maxSizePerSync)); - if(tag.equals(TAGS.ALL_STARRED)) - { - nVPairs.add(new BasicNameValuePair("type", type)); - nVPairs.add(new BasicNameValuePair("id", id)); - } - else if(tag.equals(TAGS.ALL)) - { - nVPairs.add(new BasicNameValuePair("type", type)); - nVPairs.add(new BasicNameValuePair("id", id)); - } - nVPairs.add(new BasicNameValuePair("offset", offset)); - if(getRead) - nVPairs.add(new BasicNameValuePair("getRead", "true")); - else - nVPairs.add(new BasicNameValuePair("getRead", "false")); - - - String username = mPrefs.getString(SettingsActivity.EDT_USERNAME_STRING, null); - String password = mPrefs.getString(SettingsActivity.EDT_PASSWORD_STRING, null); - String oc_root_path = mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, ""); - - String requestURL = oc_root_path + OwnCloudConstants.FEED_PATH + OwnCloudConstants.JSON_FORMAT; - - JSONObject jsonObj = HttpJsonRequest.PerformJsonRequest(requestURL, nVPairs, username, password, act); - - DatabaseConnection dbConn = new DatabaseConnection(act); - try - { - return parseItems(jsonObj, dbConn, act); - } finally { - dbConn.closeDatabase(); - } - //return rssFiles; - } - - private static int parseItems(JSONObject jsonObj, DatabaseConnection dbConn, Context context) - { - //ArrayList rssFiles = new ArrayList(); - int count = 0; - - //jsonObj = jsonObj.optJSONObject("ocs"); - //jsonObj = jsonObj.optJSONObject("data"); - JSONArray jsonArr = jsonObj.optJSONArray("items"); - - if(jsonArr != null) - { - for (int i = 0; i < jsonArr.length(); i++) { - JSONObject e = jsonArr.optJSONObject(i); - - //rssFiles.add(parseItem(e)); - - RssFile rssFile = parseItem(e); - InsertIntoDatabase.InsertSingleFeedItemIntoDatabase(rssFile, dbConn); - - //new AsyncTask_DownloadImages(rssFile.getDescription(), context).execute(); - - count++; - } - } - - return count; - //return rssFiles; - } - - private static RssFile parseItem(JSONObject e) - { - Date date = new Date(e.optLong("pubDate") * 1000); - - String content = e.optString("body"); - content = content.replaceAll("]*feedsportal.com.*>", ""); - content = content.replaceAll("]*statisches.auslieferung.commindo-media-ressourcen.de.*>", ""); - content = content.replaceAll("]*auslieferung.commindo-media-ressourcen.de.*>", ""); - content = content.replaceAll("]*rss.buysellads.com.*>", ""); - - return new RssFile(0, e.optString("id"), - e.optString("title"), - e.optString("url"), content, - !e.optBoolean("unread"), null, - e.optString("feedId"), null, - date, e.optBoolean("starred"), - e.optString("guid"), e.optString("guidHash"), - e.optString("lastModified")); - } - - - public static ArrayList GetFolderTags(Activity act) throws Exception - { - ArrayList folderTags = null; - - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(act); - String username = mPrefs.getString(SettingsActivity.EDT_USERNAME_STRING, null); - String password = mPrefs.getString(SettingsActivity.EDT_PASSWORD_STRING, null); - String oc_root_path = mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, ""); - - if(oc_root_path.endsWith("/")) - oc_root_path = oc_root_path.substring(0, oc_root_path.length() - 1); - - String requestUrl = oc_root_path + OwnCloudConstants.FOLDER_PATH + OwnCloudConstants.JSON_FORMAT; - JSONObject jsonObj = HttpJsonRequest.PerformJsonRequest(requestUrl, null, username, password, act); - - //jsonObj = jsonObj.optJSONObject("ocs"); - //jsonObj = jsonObj.optJSONObject("data"); - JSONArray jsonArr = jsonObj.optJSONArray("folders"); - - folderTags = new ArrayList(); - for (int i = 0; i < jsonArr.length(); i++) { - JSONObject e = jsonArr.optJSONObject(i); - folderTags.add(new String[] { e.optString("name"), e.optString("id") }); - } - - return folderTags; - } - - public static ArrayList GetSubscriptionTags(Activity act) throws Exception - { - ArrayList subscriptionTags = new ArrayList(); - - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(act); - String username = mPrefs.getString(SettingsActivity.EDT_USERNAME_STRING, null); - String password = mPrefs.getString(SettingsActivity.EDT_PASSWORD_STRING, null); - String oc_root_path = mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, ""); - - JSONObject jsonObj = HttpJsonRequest.PerformJsonRequest(oc_root_path + OwnCloudConstants.SUBSCRIPTION_PATH + OwnCloudConstants.JSON_FORMAT, null, username, password, act); - - //jsonObj = jsonObj.optJSONObject("ocs"); - //jsonObj = jsonObj.optJSONObject("data"); - JSONArray jsonArr = jsonObj.optJSONArray("feeds"); - - for (int i = 0; i < jsonArr.length(); i++) { - JSONObject e = jsonArr.optJSONObject(i); - String faviconLink = e.optString("faviconLink"); - if(faviconLink != null) - if(faviconLink.equals("null") || faviconLink.trim().equals("")) - faviconLink = null; - subscriptionTags.add(new ConcreteSubscribtionItem(e.optString("title"), e.optString("folderId"), e.optString("id"), faviconLink, -1)); - } - - return subscriptionTags; - } - - public static boolean PerformTagExecution(List itemIds, FeedItemTags.TAGS tag, Context context) - { - SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(context); - String username = mPrefs.getString(SettingsActivity.EDT_USERNAME_STRING, null); - String password = mPrefs.getString(SettingsActivity.EDT_PASSWORD_STRING, null); - String oc_root_path = mPrefs.getString(SettingsActivity.EDT_OWNCLOUDROOTPATH_STRING, ""); - - - //List nameValuePairs = null; - String jsonIds = null; - - - String url = oc_root_path + OwnCloudConstants.FEED_PATH + "/"; - if(tag.equals(TAGS.MARK_ITEM_AS_READ) || tag.equals(TAGS.MARK_ITEM_AS_UNREAD)) - { - jsonIds = buildIdsToJSONArray(itemIds); - /* - if(jsonIds != null) - { - nameValuePairs = new ArrayList(); - nameValuePairs.add(new BasicNameValuePair("itemIds", jsonIds)); - }*/ - //url += itemIds.get(0) + "/read"; - - if(tag.equals(TAGS.MARK_ITEM_AS_READ)) - url += "read/multiple"; - else - url += "unread/multiple"; - } - //else if(tag.equals(TAGS.MARK_ITEM_AS_UNREAD)) - // url += itemIds.get(0) + "/unread";//TODO HERE... - else - { - DatabaseConnection dbConn = new DatabaseConnection(context); - - HashMap items = new HashMap(); - for(String idItem : itemIds) - { - Cursor cursor = dbConn.getArticleByID(dbConn.getRowIdOfFeedByItemID(idItem)); - //Cursor cursor = dbConn.getFeedByID itemID); - cursor.moveToFirst(); - - String idSubscription = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_SUBSCRIPTION_ID)); - String guidHash = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_GUIDHASH)); - - cursor.close(); - - String subscription_id = dbConn.getSubscriptionIdByRowID(idSubscription); - //url += subscription_id; - - items.put(guidHash, subscription_id); - } - dbConn.closeDatabase(); - - jsonIds = buildIdsToJSONArrayWithGuid(items); - /* - if(jsonIds != null) - { - nameValuePairs = new ArrayList(); - nameValuePairs.add(new BasicNameValuePair("itemIds", jsonIds)); - }*/ - - if(tag.equals(TAGS.MARK_ITEM_AS_STARRED)) - url += "star/multiple"; - else if(tag.equals(TAGS.MARK_ITEM_AS_UNSTARRED)) - url += "unstar/multiple"; - - - /* - url += "/" + guidHash; - - if(tag.equals(TAGS.MARK_ITEM_AS_STARRED)) - url += "/star"; - else if(tag.equals(TAGS.MARK_ITEM_AS_UNSTARRED)) - url += "/unstar"; - */ - - } - try - { - int result = HttpJsonRequest.performTagChangeRequest(url, username, password, context, jsonIds); - //if(result != -1 || result != 405) - if(result == 200) - return true; - else - return false; - } - catch (Exception ex) - { - ex.printStackTrace(); - return false; - } - } - - - public static String GetVersionNumber(Activity act, String username, String password, String oc_root_path) throws Exception - { - if(oc_root_path.endsWith("/")) - oc_root_path = oc_root_path.substring(0, oc_root_path.length() - 1); - - String requestUrl = oc_root_path + OwnCloudConstants.VERSION_PATH; - JSONObject jsonObj = HttpJsonRequest.PerformJsonRequest(requestUrl, null, username, password, act); - - return jsonObj.optString("version"); - } - - - private static String buildIdsToJSONArray(List ids) - { - try - { - JSONArray jArr = new JSONArray(); - for(String id : ids) - jArr.put(Integer.parseInt(id)); - - - JSONObject jObj = new JSONObject(); - jObj.put("items", jArr); - - return jObj.toString(); - } - catch(Exception ex) - { - ex.printStackTrace(); - } - return null; - } - - private static String buildIdsToJSONArrayWithGuid(HashMap items) - { - try - { - JSONArray jArr = new JSONArray(); - for(Map.Entry entry : items.entrySet()) - { - JSONObject jOb = new JSONObject(); - jOb.put("feedId", Integer.parseInt(entry.getValue())); - jOb.put("guidHash", entry.getKey()); - jArr.put(jOb); - } - - - JSONObject jObj = new JSONObject(); - jObj.put("items", jArr); - - return jObj.toString(); - } - catch(Exception ex) - { - ex.printStackTrace(); - } - return null; - } -} +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import org.apache.http.NameValuePair; +import org.apache.http.message.BasicNameValuePair; +import org.json.JSONArray; +import org.json.JSONException; +import org.json.JSONObject; + +import android.app.Activity; +import android.content.Context; +import android.database.Cursor; + +import com.google.gson.stream.JsonReader; + +import de.luhmer.owncloudnewsreader.database.DatabaseConnection; +import de.luhmer.owncloudnewsreader.reader.FeedItemTags; +import de.luhmer.owncloudnewsreader.reader.FeedItemTags.TAGS; +import de.luhmer.owncloudnewsreader.reader.HttpJsonRequest; + +public class OwnCloudReaderMethods { + public static String maxSizePerSync = "200"; + + public static int GetUpdatedItems(TAGS tag, Activity act, long lastSync, API api) throws Exception + { + List nVPairs = new ArrayList(); + //nVPairs.add(new BasicNameValuePair("batchSize", maxSizePerSync)); + if(tag.equals(TAGS.ALL_STARRED)) + { + nVPairs.add(new BasicNameValuePair("type", "2")); + nVPairs.add(new BasicNameValuePair("id", "0")); + } + else if(tag.equals(TAGS.ALL)) + { + nVPairs.add(new BasicNameValuePair("type", "3")); + nVPairs.add(new BasicNameValuePair("id", "0")); + } + nVPairs.add(new BasicNameValuePair("lastModified", String.valueOf(lastSync))); + + + InputStream is = HttpJsonRequest.PerformJsonRequest(api.getItemUpdatedUrl(), nVPairs, api.getUsername(), api.getPassword(), act); + + DatabaseConnection dbConn = new DatabaseConnection(act); + try + { + return readJsonStream(is, new InsertItemIntoDatabase(dbConn)); + } finally { + dbConn.closeDatabase(); + is.close(); + } + } + + //"type": 1, // the type of the query (Feed: 0, Folder: 1, Starred: 2, All: 3) + public static int GetItems(TAGS tag, Activity act, String offset, boolean getRead, String id, String type, API api) throws Exception + { + List nVPairs = new ArrayList(); + nVPairs.add(new BasicNameValuePair("batchSize", maxSizePerSync)); + if(tag.equals(TAGS.ALL_STARRED)) + { + nVPairs.add(new BasicNameValuePair("type", type)); + nVPairs.add(new BasicNameValuePair("id", id)); + } + else if(tag.equals(TAGS.ALL)) + { + nVPairs.add(new BasicNameValuePair("type", type)); + nVPairs.add(new BasicNameValuePair("id", id)); + } + nVPairs.add(new BasicNameValuePair("offset", offset)); + if(getRead) + nVPairs.add(new BasicNameValuePair("getRead", "true")); + else + nVPairs.add(new BasicNameValuePair("getRead", "false")); + + + InputStream is = HttpJsonRequest.PerformJsonRequest(api.getItemUrl(), nVPairs, api.getUsername(), api.getPassword(), act); + + DatabaseConnection dbConn = new DatabaseConnection(act); + try + { + return readJsonStream(is, new InsertItemIntoDatabase(dbConn)); + } finally { + dbConn.closeDatabase(); + is.close(); + } + } + + + public static int GetFolderTags(Activity act, API api) throws Exception + { + InputStream is = HttpJsonRequest.PerformJsonRequest(api.getFolderUrl(), null, api.getUsername(), api.getPassword(), act); + DatabaseConnection dbConn = new DatabaseConnection(act); + int result = 0; + try + { + InsertFolderIntoDatabase ifid = new InsertFolderIntoDatabase(dbConn); + result = readJsonStream(is, ifid); + ifid.WriteAllToDatabaseNow(); + } finally { + dbConn.closeDatabase(); + is.close(); + } + + return result; + } + + public static int GetFeeds(Activity act, API api) throws Exception + { + InputStream inputStream = HttpJsonRequest.PerformJsonRequest(api.getFeedUrl() , null, api.getUsername(), api.getPassword(), act); + + DatabaseConnection dbConn = new DatabaseConnection(act); + int result = 0; + try { + InsertFeedIntoDatabase ifid = new InsertFeedIntoDatabase(dbConn); + result = readJsonStream(inputStream, ifid); + ifid.WriteAllToDatabaseNow(); + } finally { + dbConn.closeDatabase(); + inputStream.close(); + } + return result; + } + + /** + * can parse json like {"items":[{"id":6782}]} + * @param in + * @param iJoBj + * @return + * @throws IOException + * @throws JSONException + */ + public static int readJsonStream(InputStream in, IHandleJsonObject iJoBj) throws IOException, JSONException { + int count = 0; + JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); + reader.beginObject(); + reader.nextName(); + reader.beginArray(); + while (reader.hasNext()) { + reader.beginObject(); + + JSONObject e = getJSONObjectFromReader(reader); + + iJoBj.performAction(e); + + reader.endObject(); + count++; + } + reader.endArray(); + reader.close(); + + return count; + } + + /** + * can read json like {"version":"1.101"} + * @param in + * @param iJoBj + * @return + * @throws IOException + * @throws JSONException + */ + private static int readJsonStreamSimple(InputStream in, IHandleJsonObject iJoBj) throws IOException, JSONException { + int count = 0; + JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); + reader.beginObject(); + + JSONObject e = getJSONObjectFromReader(reader); + + iJoBj.performAction(e); + + reader.endObject(); + reader.close(); + + return count; + } + + private static JSONObject getJSONObjectFromReader(JsonReader jsonReader) { + JSONObject jObj = new JSONObject(); + try { + while(jsonReader.hasNext()) { + try { + jObj.put(jsonReader.nextName(), jsonReader.nextString()); + } catch(Exception ex) { + //ex.printStackTrace(); + jsonReader.skipValue(); + } + } + return jObj; + } catch (Exception e) { + e.printStackTrace(); + } + return null; + } + + + + public static boolean PerformTagExecutionAPIv2(List itemIds, FeedItemTags.TAGS tag, Context context, API api) + { + String jsonIds = null; + + + String url = api.getTagBaseUrl(); + if(tag.equals(TAGS.MARK_ITEM_AS_READ) || tag.equals(TAGS.MARK_ITEM_AS_UNREAD)) + { + jsonIds = buildIdsToJSONArray(itemIds); + + if(tag.equals(TAGS.MARK_ITEM_AS_READ)) + url += "read/multiple"; + else + url += "unread/multiple"; + } else { + DatabaseConnection dbConn = new DatabaseConnection(context); + + HashMap items = new HashMap(); + for(String idItem : itemIds) + { + Cursor cursor = dbConn.getArticleByID(dbConn.getRowIdOfFeedByItemID(idItem)); + //Cursor cursor = dbConn.getFeedByID itemID); + cursor.moveToFirst(); + + String idSubscription = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_SUBSCRIPTION_ID)); + String guidHash = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_GUIDHASH)); + + cursor.close(); + + String subscription_id = dbConn.getSubscriptionIdByRowID(idSubscription); + //url += subscription_id; + + items.put(guidHash, subscription_id); + } + dbConn.closeDatabase(); + + jsonIds = buildIdsToJSONArrayWithGuid(items); + /* + if(jsonIds != null) + { + nameValuePairs = new ArrayList(); + nameValuePairs.add(new BasicNameValuePair("itemIds", jsonIds)); + }*/ + + if(tag.equals(TAGS.MARK_ITEM_AS_STARRED)) + url += "star/multiple"; + else if(tag.equals(TAGS.MARK_ITEM_AS_UNSTARRED)) + url += "unstar/multiple"; + + + /* + url += "/" + guidHash; + + if(tag.equals(TAGS.MARK_ITEM_AS_STARRED)) + url += "/star"; + else if(tag.equals(TAGS.MARK_ITEM_AS_UNSTARRED)) + url += "/unstar"; + */ + + } + try + { + int result = HttpJsonRequest.performTagChangeRequest(url, api.getUsername(), api.getPassword(), context, jsonIds); + //if(result != -1 || result != 405) + if(result == 200) + return true; + else + return false; + } + catch (Exception ex) + { + ex.printStackTrace(); + return false; + } + } + + public static boolean PerformTagExecutionAPIv1(String itemId, FeedItemTags.TAGS tag, Context context, API api) + { + String url = api.getTagBaseUrl(); + if(tag.equals(TAGS.MARK_ITEM_AS_READ) || tag.equals(TAGS.MARK_ITEM_AS_UNREAD)) + { + if(tag.equals(TAGS.MARK_ITEM_AS_READ)) + url += itemId + "/read"; + else + url += itemId + "/unread"; + } else { + DatabaseConnection dbConn = new DatabaseConnection(context); + + Cursor cursor = dbConn.getArticleByID(dbConn.getRowIdOfFeedByItemID(itemId)); + cursor.moveToFirst(); + + String idSubscription = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_SUBSCRIPTION_ID)); + String guidHash = cursor.getString(cursor.getColumnIndex(DatabaseConnection.RSS_ITEM_GUIDHASH)); + cursor.close(); + + String subscription_id = dbConn.getSubscriptionIdByRowID(idSubscription); + url += subscription_id; + + dbConn.closeDatabase(); + + url += "/" + guidHash; + if(tag.equals(TAGS.MARK_ITEM_AS_STARRED)) + url += "/star"; + else if(tag.equals(TAGS.MARK_ITEM_AS_UNSTARRED)) + url += "/unstar"; + } + try + { + int result = HttpJsonRequest.performTagChangeRequest(url, api.getUsername(), api.getPassword(), context, null); + if(result == 200) + return true; + else + return false; + } + catch (Exception ex) + { + ex.printStackTrace(); + return false; + } + } + + + public static String GetVersionNumber(Activity act, String username, String password, String oc_root_path) throws Exception + { + if(oc_root_path.endsWith("/")) + oc_root_path = oc_root_path.substring(0, oc_root_path.length() - 1); + + //Try APIv2 + try { + String requestUrl = oc_root_path + OwnCloudConstants.ROOT_PATH_APIv2 + OwnCloudConstants.VERSION_PATH; + InputStream is = HttpJsonRequest.PerformJsonRequest(requestUrl, null, username, password, act); + try { + GetVersion gv = new GetVersion(); + readJsonStreamSimple(is, gv); + return gv.getVersion(); + } finally { + is.close(); + } + } catch(Exception ex) { //TODO GET HERE THE RIGHT EXCEPTION + String requestUrl = oc_root_path + OwnCloudConstants.ROOT_PATH_APIv1 + OwnCloudConstants.VERSION_PATH; + InputStream is = HttpJsonRequest.PerformJsonRequest(requestUrl, null, username, password, act); + try { + GetVersion gv = new GetVersion(); + readJsonStreamSimple(is, gv); + return gv.getVersion(); + } finally { + is.close(); + } + } + } + + + + private static String buildIdsToJSONArray(List ids) + { + try + { + JSONArray jArr = new JSONArray(); + for(String id : ids) + jArr.put(Integer.parseInt(id)); + + + JSONObject jObj = new JSONObject(); + jObj.put("items", jArr); + + return jObj.toString(); + } + catch(Exception ex) + { + ex.printStackTrace(); + } + return null; + } + + private static String buildIdsToJSONArrayWithGuid(HashMap items) + { + try + { + JSONArray jArr = new JSONArray(); + for(Map.Entry entry : items.entrySet()) + { + JSONObject jOb = new JSONObject(); + jOb.put("feedId", Integer.parseInt(entry.getValue())); + jOb.put("guidHash", entry.getKey()); + jArr.put(jOb); + } + + JSONObject jObj = new JSONObject(); + jObj.put("items", jArr); + + return jObj.toString(); + } + catch(Exception ex) + { + ex.printStackTrace(); + } + return null; + } +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/OwnCloud_Reader.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/OwnCloud_Reader.java index 4db25848..e799f780 100644 --- a/src/de/luhmer/owncloudnewsreader/reader/owncloud/OwnCloud_Reader.java +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/OwnCloud_Reader.java @@ -1,102 +1,115 @@ -package de.luhmer.owncloudnewsreader.reader.owncloud; - -import java.util.List; - -import android.app.Activity; -import android.content.Context; -import android.util.SparseArray; -import de.luhmer.owncloudnewsreader.reader.AsyncTask_Reader; -import de.luhmer.owncloudnewsreader.reader.FeedItemTags; -import de.luhmer.owncloudnewsreader.reader.IReader; -import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; - -public class OwnCloud_Reader implements IReader { - boolean isSyncRunning = false; - - SparseArray AsyncTasksRunning; - - public OwnCloud_Reader() { - AsyncTasksRunning = new SparseArray(); - } - - @Override - public void Start_AsyncTask_GetItems(int task_id, - Activity context, OnAsyncTaskCompletedListener listener, FeedItemTags.TAGS tag) { - setSyncRunning(true); - AsyncTasksRunning.append(task_id, (AsyncTask_Reader) new AsyncTask_GetItems(task_id, context, new OnAsyncTaskCompletedListener[] { AsyncTask_finished, listener } ).execute(tag)); - } - - @Override - public void Start_AsyncTask_GetOldItems(int task_id, - Activity context, OnAsyncTaskCompletedListener listener, String feed_id, String folder_id) { - setSyncRunning(true); - AsyncTasksRunning.append(task_id, (AsyncTask_Reader) new AsyncTask_GetOldItems(task_id, context, new OnAsyncTaskCompletedListener[] { AsyncTask_finished, listener }, feed_id, folder_id).execute()); - } - - @Override - public void Start_AsyncTask_GetFolder(int task_id, - Activity context, OnAsyncTaskCompletedListener listener) { - setSyncRunning(true); - AsyncTasksRunning.append(task_id, (AsyncTask_Reader) new AsyncTask_GetFolderTags(task_id, context, new OnAsyncTaskCompletedListener[] { AsyncTask_finished, listener } ).execute()); - } - - @Override - public void Start_AsyncTask_GetFeeds(int task_id, - Activity context, OnAsyncTaskCompletedListener listener) { - setSyncRunning(true); - AsyncTasksRunning.append(task_id, (AsyncTask_Reader) new AsyncTask_GetFeeds(task_id, context, new OnAsyncTaskCompletedListener[] { AsyncTask_finished, listener } ).execute()); - } - - @Override - public void Start_AsyncTask_PerformTagAction(int task_id, - Context context, OnAsyncTaskCompletedListener listener, - List itemIds, FeedItemTags.TAGS tag) { - setSyncRunning(true); - AsyncTasksRunning.append(task_id, (AsyncTask_Reader) new AsyncTask_PerformTagAction(task_id, context, new OnAsyncTaskCompletedListener[] { AsyncTask_finished, listener } ).execute(itemIds, tag)); - } - - @Override - public void Start_AsyncTask_Authenticate(int task_id, Activity context, - OnAsyncTaskCompletedListener listener) { - // TODO Auto-generated method stub - - } - - @Override - public void onAsyncTaskCompleted(int task_id, Object task_result) { - // TODO Auto-generated method stub - - } - - @Override - public boolean isSyncRunning() { - return isSyncRunning; - } - - @Override - public void setSyncRunning(boolean isSyncRunning) { - this.isSyncRunning = isSyncRunning; - } - - OnAsyncTaskCompletedListener AsyncTask_finished = new OnAsyncTaskCompletedListener() { - - @Override - public void onAsyncTaskCompleted(int task_id, Object task_result) { - setSyncRunning(false); - AsyncTasksRunning.remove(task_id); - } - }; - - @Override - public SparseArray getRunningAsyncTasks() { - return AsyncTasksRunning; - } - - @Override - public void attachToRunningTask(int task_id, Activity activity, OnAsyncTaskCompletedListener listener) { - if(AsyncTasksRunning.get(task_id) != null) - AsyncTasksRunning.get(task_id).attach(activity, new OnAsyncTaskCompletedListener[] { listener, AsyncTask_finished }); - } - - -} +package de.luhmer.owncloudnewsreader.reader.owncloud; + +import java.util.List; + +import android.app.Activity; +import android.util.SparseArray; +import de.luhmer.owncloudnewsreader.reader.AsyncTask_Reader; +import de.luhmer.owncloudnewsreader.reader.FeedItemTags; +import de.luhmer.owncloudnewsreader.reader.IReader; +import de.luhmer.owncloudnewsreader.reader.OnAsyncTaskCompletedListener; + +public class OwnCloud_Reader implements IReader { + boolean isSyncRunning = false; + private API api = null; + + SparseArray AsyncTasksRunning; + + public OwnCloud_Reader() { + AsyncTasksRunning = new SparseArray(); + } + + @Override + public void Start_AsyncTask_GetItems(int task_id, + Activity context, OnAsyncTaskCompletedListener listener, FeedItemTags.TAGS tag) { + setSyncRunning(true); + AsyncTasksRunning.append(task_id, (AsyncTask_Reader) new AsyncTask_GetItems(task_id, context, new OnAsyncTaskCompletedListener[] { AsyncTask_finished, listener } ).execute(tag)); + } + + @Override + public void Start_AsyncTask_GetOldItems(int task_id, + Activity context, OnAsyncTaskCompletedListener listener, String feed_id, String folder_id) { + setSyncRunning(true); + AsyncTasksRunning.append(task_id, (AsyncTask_Reader) new AsyncTask_GetOldItems(task_id, context, new OnAsyncTaskCompletedListener[] { AsyncTask_finished, listener }, feed_id, folder_id).execute()); + } + + @Override + public void Start_AsyncTask_GetFolder(int task_id, + Activity context, OnAsyncTaskCompletedListener listener) { + setSyncRunning(true); + AsyncTasksRunning.append(task_id, (AsyncTask_Reader) new AsyncTask_GetFolderTags(task_id, context, new OnAsyncTaskCompletedListener[] { AsyncTask_finished, listener } ).execute()); + } + + @Override + public void Start_AsyncTask_GetFeeds(int task_id, + Activity context, OnAsyncTaskCompletedListener listener) { + setSyncRunning(true); + AsyncTasksRunning.append(task_id, (AsyncTask_Reader) new AsyncTask_GetFeeds(task_id, context, new OnAsyncTaskCompletedListener[] { AsyncTask_finished, listener } ).execute()); + } + + @Override + public void Start_AsyncTask_PerformTagAction(int task_id, + Activity context, OnAsyncTaskCompletedListener listener, + List itemIds, FeedItemTags.TAGS tag) { + setSyncRunning(true); + AsyncTasksRunning.append(task_id, (AsyncTask_Reader) new AsyncTask_PerformTagAction(task_id, context, new OnAsyncTaskCompletedListener[] { AsyncTask_finished, listener } ).execute(itemIds, tag)); + } + + + public void Start_AsyncTask_GetVersion(int task_id, + Activity context, OnAsyncTaskCompletedListener listener, String username, String password) { + setSyncRunning(true); + AsyncTasksRunning.append(task_id, (AsyncTask_Reader) new AsyncTask_GetApiVersion(task_id, context, username, password, new OnAsyncTaskCompletedListener[] { AsyncTask_finished, listener } ).execute()); + } + + @Override + public void Start_AsyncTask_Authenticate(int task_id, Activity context, + OnAsyncTaskCompletedListener listener) { + // TODO Auto-generated method stub + + } + + + @Override + public void onAsyncTaskCompleted(int task_id, Object task_result) { + + } + + @Override + public boolean isSyncRunning() { + return isSyncRunning; + } + + @Override + public void setSyncRunning(boolean isSyncRunning) { + this.isSyncRunning = isSyncRunning; + } + + OnAsyncTaskCompletedListener AsyncTask_finished = new OnAsyncTaskCompletedListener() { + + @Override + public void onAsyncTaskCompleted(int task_id, Object task_result) { + setSyncRunning(false); + AsyncTasksRunning.remove(task_id); + } + }; + + @Override + public SparseArray getRunningAsyncTasks() { + return AsyncTasksRunning; + } + + @Override + public void attachToRunningTask(int task_id, Activity activity, OnAsyncTaskCompletedListener listener) { + if(AsyncTasksRunning.get(task_id) != null) + AsyncTasksRunning.get(task_id).attach(activity, new OnAsyncTaskCompletedListener[] { listener, AsyncTask_finished }); + } + + public API getApi() { + return api; + } + + public void setApi(API api) { + this.api = api; + } +} diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/apiv1/APIv1.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/apiv1/APIv1.java index c0c154e5..8fba40ee 100644 --- a/src/de/luhmer/owncloudnewsreader/reader/owncloud/apiv1/APIv1.java +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/apiv1/APIv1.java @@ -1,9 +1,15 @@ package de.luhmer.owncloudnewsreader.reader.owncloud.apiv1; +import java.util.ArrayList; +import java.util.List; + import android.app.Activity; +import android.content.Context; import de.luhmer.owncloudnewsreader.SettingsActivity; +import de.luhmer.owncloudnewsreader.reader.FeedItemTags.TAGS; import de.luhmer.owncloudnewsreader.reader.owncloud.API; import de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloudConstants; +import de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloudReaderMethods; public class APIv1 extends API { @@ -46,7 +52,17 @@ public class APIv1 extends API { } @Override - public void markSingleItemAsReadApiv1() { + public boolean PerformTagExecution(List itemIds, TAGS tag, + Context context, API api) { + List succeeded = new ArrayList(); + for(String item : itemIds) { + succeeded.add(OwnCloudReaderMethods.PerformTagExecutionAPIv1(item, tag, context, api)); + } + + if(succeeded.contains(false)) + return false; + else + return true; } } diff --git a/src/de/luhmer/owncloudnewsreader/reader/owncloud/apiv2/APIv2.java b/src/de/luhmer/owncloudnewsreader/reader/owncloud/apiv2/APIv2.java index 76f4a504..b68a9cd0 100644 --- a/src/de/luhmer/owncloudnewsreader/reader/owncloud/apiv2/APIv2.java +++ b/src/de/luhmer/owncloudnewsreader/reader/owncloud/apiv2/APIv2.java @@ -1,9 +1,14 @@ package de.luhmer.owncloudnewsreader.reader.owncloud.apiv2; +import java.util.List; + import android.app.Activity; +import android.content.Context; import de.luhmer.owncloudnewsreader.SettingsActivity; +import de.luhmer.owncloudnewsreader.reader.FeedItemTags.TAGS; import de.luhmer.owncloudnewsreader.reader.owncloud.API; import de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloudConstants; +import de.luhmer.owncloudnewsreader.reader.owncloud.OwnCloudReaderMethods; public class APIv2 extends API { @@ -46,6 +51,8 @@ public class APIv2 extends API { } @Override - public void markSingleItemAsReadApiv1() { - } + public boolean PerformTagExecution(List itemIds, TAGS tag, + Context context, API api) { + return OwnCloudReaderMethods.PerformTagExecutionAPIv2(itemIds, tag, context, api); + } } diff --git a/src/de/luhmer/owncloudnewsreader/services/SyncService.java b/src/de/luhmer/owncloudnewsreader/services/SyncService.java index 347b8f5e..e044c752 100644 --- a/src/de/luhmer/owncloudnewsreader/services/SyncService.java +++ b/src/de/luhmer/owncloudnewsreader/services/SyncService.java @@ -1,27 +1,27 @@ -package de.luhmer.owncloudnewsreader.services; - -import android.app.Service; -import android.content.Intent; -import android.os.Binder; -import android.os.IBinder; - -public class SyncService extends Service { - // Binder given to clients - private final IBinder mBinder = new LocalBinder(); - - /** - * Class used for the client Binder. Because we know this service always - * runs in the same process as its clients, we don't need to deal with IPC. - */ - public class LocalBinder extends Binder { - public SyncService getService() { - // Return this instance of LocalService so clients can call public methods - return SyncService.this; - } - } - - @Override - public IBinder onBind(Intent intent) { - return mBinder; - } -} +package de.luhmer.owncloudnewsreader.services; + +import android.app.Service; +import android.content.Intent; +import android.os.Binder; +import android.os.IBinder; + +public class SyncService extends Service { + // Binder given to clients + private final IBinder mBinder = new LocalBinder(); + + /** + * Class used for the client Binder. Because we know this service always + * runs in the same process as its clients, we don't need to deal with IPC. + */ + public class LocalBinder extends Binder { + public SyncService getService() { + // Return this instance of LocalService so clients can call public methods + return SyncService.this; + } + } + + @Override + public IBinder onBind(Intent intent) { + return mBinder; + } +}