rework authentication

base feedlist adapter on sqlite
This commit is contained in:
Andrew Dolgov 2011-09-08 20:05:00 +04:00
parent 2e2b5e5a11
commit f976b25c1e
11 changed files with 268 additions and 436 deletions

View File

@ -10,13 +10,14 @@
<application android:icon="@drawable/icon" android:label="@string/app_name"> <application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".LoginActivity" <activity android:name=".LoginActivity"
android:label="@string/app_name"> android:label="@string/app_name">
</activity>
<activity android:name=".MainActivity"
android:label="@string/app_name">
<intent-filter> <intent-filter>
<action android:name="android.intent.action.MAIN" /> <action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" /> <category android:name="android.intent.category.LAUNCHER" />
</intent-filter> </intent-filter>
</activity>
<activity android:name=".MainActivity"
android:label="@string/app_name">
</activity> </activity>
<activity android:name=".PreferencesActivity" <activity android:name=".PreferencesActivity"
android:label="@string/preferences"> android:label="@string/preferences">

View File

@ -8,6 +8,6 @@
android:layout_width="match_parent" android:id="@+id/feeds" android:layout_height="match_parent"></ListView> android:layout_width="match_parent" android:id="@+id/feeds" android:layout_height="match_parent"></ListView>
</LinearLayout> </LinearLayout>
<ProgressBar android:layout_height="wrap_content" <ProgressBar android:layout_height="wrap_content"
android:layout_width="wrap_content" android:layout_width="wrap_content" android:visibility="invisible"
android:layout_gravity="center" android:id="@+id/loading_progress"/> android:layout_gravity="center" android:id="@+id/loading_progress"/>
</FrameLayout> </FrameLayout>

View File

@ -4,20 +4,21 @@
android:layout_height="?android:attr/listPreferredItemHeight" android:layout_height="?android:attr/listPreferredItemHeight"
android:orientation="horizontal" android:orientation="horizontal"
android:gravity="center_vertical" android:gravity="center_vertical"
android:padding="6dip" android:id="@+id/feeds_row"> android:padding="3dip" android:id="@+id/feeds_row">
<TextView <TextView
android:id="@+id/title" android:id="@+id/title"
android:layout_width="wrap_content" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:layout_height="wrap_content"
android:layout_weight="1" android:layout_weight="1"
android:layout_gravity="center_vertical" android:layout_gravity="center_vertical"
android:paddingLeft="16dp" android:paddingLeft="6dip"
android:text="{FEED}" android:textSize="16sp"/> android:text="{FEED}" android:textSize="16sp"/>
<TextView <TextView
android:id="@+id/unread_counter" android:id="@+id/unread_counter"
android:gravity="right" android:gravity="right"
android:textSize="12sp" android:textSize="12sp"
android:textStyle="bold" android:textStyle="bold"
android:paddingRight="6dip"
android:textColor="?unreadCounterColor" android:textColor="?unreadCounterColor"
android:layout_gravity="center_vertical" android:layout_gravity="center_vertical"
android:layout_width="wrap_content" android:layout_width="wrap_content"

View File

@ -5,9 +5,9 @@
android:title="@string/preferences" android:title="@string/preferences"
android:showAsAction="ifRoom|withText"/> android:showAsAction="ifRoom|withText"/>
<item android:id="@+id/logout" <!-- <item android:id="@+id/logout"
android:title="@string/logout" android:title="@string/logout"
android:icon="@android:drawable/presence_offline" android:icon="@android:drawable/presence_offline"
android:showAsAction="ifRoom|withText"/> android:showAsAction="ifRoom|withText"/> -->
</menu> </menu>

View File

@ -8,7 +8,7 @@
<EditTextPreference android:title="@string/login" android:key="login" android:singleLine="true"></EditTextPreference> <EditTextPreference android:title="@string/login" android:key="login" android:singleLine="true"></EditTextPreference>
<EditTextPreference android:title="@string/password" android:key="password" android:singleLine="true" android:password="true"></EditTextPreference> <EditTextPreference android:title="@string/password" android:key="password" android:singleLine="true" android:password="true"></EditTextPreference>
<EditTextPreference android:key="ttrss_url" android:title="@string/ttrss_url" android:singleLine="true" textUri="true" android:hint="@string/default_url"></EditTextPreference> <EditTextPreference android:key="ttrss_url" android:title="@string/ttrss_url" android:singleLine="true" textUri="true" android:hint="@string/default_url"></EditTextPreference>
<CheckBoxPreference android:defaultValue="true" android:title="@string/auto_login" android:key="auto_login" /> <!-- <CheckBoxPreference android:defaultValue="true" android:title="@string/auto_login" android:key="auto_login" /> -->
</PreferenceCategory> </PreferenceCategory>

View File

@ -4,6 +4,8 @@ import java.io.BufferedReader;
import java.io.InputStream; import java.io.InputStream;
import java.io.InputStreamReader; import java.io.InputStreamReader;
import java.util.HashMap; import java.util.HashMap;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.http.HttpResponse; import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPost;
@ -15,6 +17,7 @@ import android.util.Log;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser; import com.google.gson.JsonParser;
public class ApiRequest extends AsyncTask<HashMap<String,String>, Integer, JsonElement> { public class ApiRequest extends AsyncTask<HashMap<String,String>, Integer, JsonElement> {
@ -22,24 +25,92 @@ public class ApiRequest extends AsyncTask<HashMap<String,String>, Integer, JsonE
protected String m_sessionId; protected String m_sessionId;
protected String m_apiEndpoint; protected String m_apiEndpoint;
protected String m_login;
protected String m_password;
protected int m_authStatus;
protected Gson m_gson = new Gson();
protected static final int STATUS_LOGIN_FAILED = 0;
protected static final int STATUS_OK = 1;
protected static final int STATUS_API_DISABLED = 2;
protected static final int STATUS_OTHER_ERROR = 3;
protected ApiRequest(String sessionId, String apiEndpoint) { protected ApiRequest(String sessionId, String apiEndpoint, String login, String password) {
super(); super();
m_sessionId = sessionId; m_sessionId = sessionId;
m_apiEndpoint = apiEndpoint; m_apiEndpoint = apiEndpoint;
m_authStatus = STATUS_OK;
m_login = login;
m_password = password;
Log.d(TAG, "initial SID=" + sessionId);
} }
@Override protected int tryAuthenticate() {
protected JsonElement doInBackground(HashMap<String,String>... params) { JsonElement result = sendRequest(new HashMap<String,String>() {
{
put("op", "login");
put("user", m_login);
put("password", m_password);
}
});
if (result != null) {
try {
JsonObject rv = result.getAsJsonObject();
Gson gson = new Gson(); int status = rv.get("status").getAsInt();
if (status == 0) {
JsonObject content = rv.get("content").getAsJsonObject();
if (content != null) {
m_sessionId = content.get("session_id").getAsString();
Log.d(TAG, "<<< Authentified, sessionId=" + m_sessionId);
return STATUS_OK;
}
} else {
JsonObject content = rv.get("content").getAsJsonObject();
if (content != null) {
String error = content.get("error").getAsString();
if (error.equals("LOGIN_ERROR")) {
m_sessionId = null;
return STATUS_LOGIN_FAILED;
} else if (error.equals("API_DISABLED")) {
m_sessionId = null;
return STATUS_API_DISABLED;
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
m_sessionId = null;
return STATUS_OTHER_ERROR;
}
protected String getSessionId() {
return m_sessionId;
}
protected int getAuthStatus() {
return m_authStatus;
}
protected JsonElement sendRequest(HashMap<String,String> param) {
HashMap<String,String> tmp = new HashMap<String,String>(param);
if (m_sessionId != null)
tmp.put("sid", m_sessionId);
String requestStr = m_gson.toJson(tmp);
String requestStr = gson.toJson(params); Log.d(TAG, ">>> (" + requestStr + ") " + m_apiEndpoint);
// FIXME ugly hack
requestStr = requestStr.substring(1).substring(0, requestStr.length()-2);
Log.d(TAG, "executing API request...: " + requestStr + " " + m_apiEndpoint);
DefaultHttpClient client = new DefaultHttpClient(); DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(m_apiEndpoint + "/api/"); HttpPost httpPost = new HttpPost(m_apiEndpoint + "/api/");
@ -60,7 +131,7 @@ public class ApiRequest extends AsyncTask<HashMap<String,String>, Integer, JsonE
response += s; response += s;
} }
Log.d(TAG, "Server returned: " + response); Log.d(TAG, "<<< " + response);
JsonParser parser = new JsonParser(); JsonParser parser = new JsonParser();
@ -72,4 +143,39 @@ public class ApiRequest extends AsyncTask<HashMap<String,String>, Integer, JsonE
return null; return null;
} }
@Override
protected JsonElement doInBackground(HashMap<String, String>... params) {
JsonElement result = sendRequest(params[0]);
try {
JsonElement content = result.getAsJsonObject().get("content");
int status = result.getAsJsonObject().get("status").getAsInt();
if (status == 1) {
String error = content.getAsJsonObject().get("error").getAsString();
if (error.equals("NOT_LOGGED_IN")) {
Log.d(TAG, "<<< Session invalid, trying to authenticate...");
m_sessionId = null;
m_authStatus = tryAuthenticate();
if (m_authStatus == STATUS_OK) {
result = sendRequest(params[0]);
return result.getAsJsonObject().get("content");
}
}
} else {
return content;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
} }

View File

@ -0,0 +1,39 @@
package org.fox.ttrss;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.provider.BaseColumns;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private final String TAG = this.getClass().getSimpleName();
public static final String DATABASE_NAME = "LocalStorage";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "onCreate");
db.execSQL("CREATE TABLE IF NOT EXISTS feeds (" +
BaseColumns._ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
"feed_url TEXT, " +
"title TEXT, " +
"unread INTEGER, " +
"has_icon BOOLEAN, " +
"cat_id INTEGER, " +
"last_updated INTEGER)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
}

View File

@ -0,0 +1,19 @@
package org.fox.ttrss;
public class Feed implements Comparable<Feed> {
String feed_url;
String title;
int id;
int unread;
boolean has_icon;
int cat_id;
int last_updated;
@Override
public int compareTo(Feed feed) {
if (feed.unread != this.unread)
return feed.unread - this.unread;
else
return this.title.compareTo(feed.title);
}
}

View File

@ -1,9 +1,6 @@
package org.fox.ttrss; package org.fox.ttrss;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
@ -14,29 +11,28 @@ import android.content.Context;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.database.Cursor; import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteStatement;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Bundle; import android.os.Bundle;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.provider.BaseColumns;
import android.util.Log; import android.util.Log;
import android.view.LayoutInflater; import android.view.LayoutInflater;
import android.view.View; import android.view.View;
import android.view.ViewGroup; import android.view.ViewGroup;
import android.widget.AdapterView; import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener; import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView; import android.widget.ListView;
import android.widget.TextView; import android.widget.SimpleCursorAdapter;
import com.google.gson.Gson; import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement; import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.reflect.TypeToken; import com.google.gson.reflect.TypeToken;
public class FeedsFragment extends Fragment implements OnItemClickListener { public class FeedsFragment extends Fragment implements OnItemClickListener {
private final String TAG = this.getClass().getSimpleName(); private final String TAG = this.getClass().getSimpleName();
protected ArrayList<Feed> m_feeds = new ArrayList<Feed>(); // protected ArrayList<Feed> m_feeds = new ArrayList<Feed>();
protected FeedsListAdapter m_adapter; protected FeedsListAdapter m_adapter;
protected SharedPreferences m_prefs; protected SharedPreferences m_prefs;
protected String m_sessionId; protected String m_sessionId;
@ -47,8 +43,9 @@ public class FeedsFragment extends Fragment implements OnItemClickListener {
@Override @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
m_sessionId = m_prefs.getString("last_session_id", null);
if (savedInstanceState != null) { if (savedInstanceState != null) {
m_sessionId = savedInstanceState.getString("sessionId");
m_sessionId = savedInstanceState.getString("sessionId"); m_sessionId = savedInstanceState.getString("sessionId");
m_activeFeedId = savedInstanceState.getInt("activeFeedId"); m_activeFeedId = savedInstanceState.getInt("activeFeedId");
m_lastUpdate = savedInstanceState.getLong("lastUpdate"); m_lastUpdate = savedInstanceState.getLong("lastUpdate");
@ -56,7 +53,11 @@ public class FeedsFragment extends Fragment implements OnItemClickListener {
View view = inflater.inflate(R.layout.feeds_fragment, container, false); View view = inflater.inflate(R.layout.feeds_fragment, container, false);
m_adapter = new FeedsListAdapter(getActivity(), R.id.feeds_row, m_feeds); DatabaseHelper helper = new DatabaseHelper(getActivity());
Cursor cursor = helper.getReadableDatabase().query("feeds", null, null, null, null, null, "unread DESC");
m_adapter = new FeedsListAdapter(getActivity(), R.layout.feeds_row, cursor,
new String[] { "title", "unread" }, new int[] { R.id.title, R.id.unread_counter }, 0);
ListView list = (ListView) view.findViewById(R.id.feeds); ListView list = (ListView) view.findViewById(R.id.feeds);
@ -65,29 +66,22 @@ public class FeedsFragment extends Fragment implements OnItemClickListener {
list.setOnItemClickListener(this); list.setOnItemClickListener(this);
} }
updateSelf();
return view; return view;
} }
@Override protected void updateSessionId(String sessionId) {
public void onStart() { m_sessionId = sessionId;
super.onStart();
SharedPreferences.Editor editor = m_prefs.edit();
if (new Date().getTime() - m_lastUpdate > 30*1000) { editor.putString("last_session_id", m_sessionId);
refresh(); editor.commit();
} else {
//
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
} }
@Override @Override
public void onAttach(Activity activity) { public void onAttach(Activity activity) {
super.onAttach(activity); super.onAttach(activity);
m_prefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext()); m_prefs = PreferenceManager.getDefaultSharedPreferences(getActivity().getApplicationContext());
} }
@ -95,82 +89,62 @@ public class FeedsFragment extends Fragment implements OnItemClickListener {
m_sessionId = sessionId; m_sessionId = sessionId;
} }
@SuppressWarnings("unchecked") private void updateSelf() {
private void refresh() { ApiRequest task = new ApiRequest(m_sessionId,
ApiRequest task = new ApiRequest(null, m_prefs.getString("ttrss_url", null)) { m_prefs.getString("ttrss_url", null),
m_prefs.getString("login", null),
m_prefs.getString("password", null)) {
@Override @Override
protected void onPostExecute(JsonElement result) { protected void onPostExecute(JsonElement result) {
if (result != null) { if (result != null && getAuthStatus() == STATUS_OK) {
try { try {
m_lastUpdate = new Date().getTime(); JsonArray feeds_object = (JsonArray) result.getAsJsonArray();
JsonObject rv = result.getAsJsonObject();
int status = rv.get("status").getAsInt();
if (status == 0) { Type listType = new TypeToken<List<Feed>>() {}.getType();
Type listType = new TypeToken<List<Feed>>() {}.getType(); List<Feed> feeds = m_gson.fromJson(feeds_object, listType);
List<Feed> feeds = m_gson.fromJson(rv.get("content"), listType);
Collections.sort(feeds);
if (feeds != null) {
m_feeds.clear();
for (Feed feed : feeds) {
if (feed.id == -4 || feed.id > 0)
m_feeds.add(feed);
}
m_adapter.notifyDataSetChanged();
/* if (getView() != null) {
View v = getView().findViewById(R.id.loading_progress);
if (v != null) v.setVisibility(View.GONE);
v = getView().findViewById(R.id.no_unread_feeds);
if (v != null) {
if (m_feeds.size() > 0)
v.setVisibility(View.INVISIBLE);
else
v.setVisibility(View.VISIBLE);
}
} */
return;
}
} else {
JsonObject content = rv.get("content").getAsJsonObject();
if (content != null) {
String error = content.get("error").getAsString();
if (error.equals("NOT_LOGGED_IN")) { DatabaseHelper dh = new DatabaseHelper(getActivity());
MainActivity ma = (MainActivity)getActivity(); SQLiteDatabase db = dh.getWritableDatabase();
if (ma != null) ma.logout(); db.execSQL("DELETE FROM FEEDS");
}
} SQLiteStatement stmt = db.compileStatement("INSERT INTO feeds " +
"("+BaseColumns._ID+", title, feed_url, unread, has_icon, cat_id, last_updated) " +
"VALUES (?, ?, ?, ?, ?, ?, ?);");
for (Feed feed : feeds) {
stmt.bindLong(1, feed.id);
stmt.bindString(2, feed.title);
stmt.bindString(3, feed.feed_url);
stmt.bindLong(4, feed.unread);
stmt.bindLong(5, 1);
stmt.bindLong(6, feed.cat_id);
stmt.bindLong(7, feed.last_updated);
stmt.execute();
} }
db.close();
m_adapter.notifyDataSetChanged();
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
}
}
}; };
task.execute(new HashMap<String,String>() { task.execute(new HashMap<String,String>() {
{ {
put("sid", m_sessionId); put("sid", m_sessionId);
put("op", "getFeeds"); put("op", "getFeeds");
put("cat_id", "-4"); put("cat_id", "-3");
put("unread_only", "true"); put("unread_only", "true");
} }
}); });
} }
@Override @Override
public void onSaveInstanceState (Bundle out) { public void onSaveInstanceState (Bundle out) {
@ -181,64 +155,20 @@ public class FeedsFragment extends Fragment implements OnItemClickListener {
out.putLong("lastUpdate", m_lastUpdate); out.putLong("lastUpdate", m_lastUpdate);
} }
private class FeedsListAdapter extends ArrayAdapter<Feed> { private class FeedsListAdapter extends SimpleCursorAdapter {
private ArrayList<Feed> items;
public FeedsListAdapter(Context context, int textViewResourceId, ArrayList<Feed> items) {
super(context, textViewResourceId, items);
this.items = items;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView; private Context context;
private int layout;
Feed feed = items.get(position);
if (v == null) {
LayoutInflater vi = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.feeds_row, null);
}
TextView title = (TextView) v.findViewById(R.id.title);
if (title != null) {
title.setText(feed.title);
if (feed.id == m_activeFeedId) {
title.setTextAppearance(getContext(), R.style.SelectedFeed);
} else {
title.setTextAppearance(getContext(), R.style.Feed);
}
}
TextView unread = (TextView) v.findViewById(R.id.unread_counter);
if (unread != null) {
unread.setText(String.valueOf(feed.unread));
}
return v;
}
}
private class Feed implements Comparable<Feed> {
String feed_url;
String title;
int id;
int unread;
boolean has_icon;
int cat_id;
int last_updated;
@Override public FeedsListAdapter(Context context, int layout, Cursor c,
public int compareTo(Feed feed) { String[] from, int[] to, int flags) {
if (feed.unread != this.unread) super(context, layout, c, from, to, flags);
return feed.unread - this.unread;
else this.context = context;
return this.title.compareTo(feed.title); this.layout = layout;
} }
} }
@Override @Override
@ -246,16 +176,17 @@ public class FeedsFragment extends Fragment implements OnItemClickListener {
ListView list = (ListView)getActivity().findViewById(R.id.feeds); ListView list = (ListView)getActivity().findViewById(R.id.feeds);
if (list != null) { if (list != null) {
Feed feed = (Feed) list.getItemAtPosition(position); Cursor cursor = (Cursor) list.getItemAtPosition(position);
if (feed != null) { if (cursor != null) {
Log.d(TAG, "clicked on feed " + feed.id); int feedId = (int) cursor.getLong(0);
viewFeed(feed.id); Log.d(TAG, "clicked on feed " + feedId);
viewFeed(feedId);
} }
} }
} }
private void viewFeed(int feedId) { private void viewFeed(int feedId) {
m_activeFeedId = feedId; m_activeFeedId = feedId;
@ -271,77 +202,6 @@ public class FeedsFragment extends Fragment implements OnItemClickListener {
m_adapter.notifyDataSetChanged(); m_adapter.notifyDataSetChanged();
} }
private class FeedsDBHelper extends SQLiteOpenHelper {
private SQLiteDatabase db;
private static final int DATABASE_VERSION = 1;
private static final String DB_NAME = "feeds.db";
private static final String TABLE_NAME = "feeds";
public FeedsDBHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
db = getWritableDatabase();
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE feeds (id INTEGER PRIMARY KEY,"+
"title TEXT,"+
"feed_url TEXT,"+
"unread INTEGER,"+
"has_icon INTEGER,"+
"cat_id INTEGER,"+
"last_updated INTEGER);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE feeds");
onCreate(db);
}
public void clearAll() {
db.delete("feeds", null, null);
}
public Cursor cursorSelectAll() {
Cursor cursor = this.db.query(
"feeds", // Table Name
new String[] { "id", "title", "feed_url", "unread", "has_icon", "cat_id", "last_updated" }, // Columns to return
null, // SQL WHERE
null, // Selection Args
null, // SQL GROUP BY
null, // SQL HAVING
"unread DESC"); // SQL ORDER BY
return cursor;
}
public ArrayList<Friend> listSelectAll() {
ArrayList<Friend> list = new ArrayList<Friend>();
Cursor cursor = this.db.query(TABLE_NAME, new String[] { "id", "title", "feed_url", "unread", "has_icon", "cat_id", "last_updated" },
null, null, null, null, "unread DESC");
if (cursor.moveToFirst()) {
do {
Feed f = new Feed();
f.id = cursor.getInt(0);
f.title = cursor.getString(1);
f.feed_url = cursor.getString(2);
f.unread = cursor.getInt(3);
f.has_icon = cursor.getInt(4) == 1;
f.cat_id = cursor.getInt(5);
f.last_updated = cursor.getInt(6);
list.add(f);
} while (cursor.moveToNext());
}
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
return list;
}
}
} }

View File

@ -1,173 +0,0 @@
package org.fox.ttrss;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
public class LoginActivity extends Activity {
private final String TAG = this.getClass().getSimpleName();
private SharedPreferences m_prefs;
private String m_themeName = "";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
m_prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if (m_prefs.getString("theme", "THEME_DARK").equals("THEME_DARK")) {
setTheme(R.style.DarkTheme);
} else {
setTheme(R.style.LightTheme);
}
m_themeName = m_prefs.getString("theme", "THEME_DARK");
setContentView(R.layout.login);
performLogin();
}
protected void updateLoginStatus(int id) {
TextView tv = (TextView) findViewById(R.id.login_status_text);
if (tv != null) {
tv.setText(id);
}
}
protected void showLoginProgress(boolean show) {
View v = findViewById(R.id.login_progress);
v.setVisibility((show) ? View.VISIBLE : View.GONE);
}
@Override
public void onResume() {
super.onResume();
if (!m_prefs.getString("theme", "THEME_DARK").equals(m_themeName)) {
Intent refresh = new Intent(this, LoginActivity.class);
startActivity(refresh);
finish();
}
showLoginProgress(false);
if (isConfigured()) {
updateLoginStatus(R.string.login_ready);
} else {
updateLoginStatus(R.string.login_need_configure);
}
}
public boolean isConfigured() {
String login = m_prefs.getString("login", "");
String password = m_prefs.getString("password", "");
String ttrssUrl = m_prefs.getString("ttrss_url", "");
return !(login.equals("") || password.equals("") || ttrssUrl.equals(""));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.login_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.preferences:
Intent intent = new Intent(this, PreferencesActivity.class);
startActivityForResult(intent, 0);
return true;
case R.id.login:
performLogin();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@SuppressWarnings({ "serial", "unchecked" })
private void performLogin() {
ApiRequest task = new ApiRequest(null, m_prefs.getString("ttrss_url", null)) {
@Override
protected void onPostExecute(JsonElement result) {
if (result != null) {
try {
JsonObject rv = result.getAsJsonObject();
int status = rv.get("status").getAsInt();
if (status == 0) {
JsonObject content = rv.get("content").getAsJsonObject();
if (content != null) {
m_sessionId = content.get("session_id").getAsString();
showLoginProgress(false);
updateLoginStatus(R.string.login_success);
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("sessionId", m_sessionId);
startActivityForResult(intent, 0);
finish();
return;
}
} else {
JsonObject content = rv.get("content").getAsJsonObject();
if (content != null) {
String error = content.get("error").getAsString();
if (error.equals("LOGIN_ERROR")) {
updateLoginStatus(R.string.login_wrong_password);
} else if (error.equals("API_DISABLED")) {
updateLoginStatus(R.string.login_api_disabled);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
showLoginProgress(false);
updateLoginStatus(R.string.login_failed);
}
};
updateLoginStatus(R.string.login_in_progress);
showLoginProgress(true);
task.execute(new HashMap<String,String>() {
{
put("op", "login");
put("user", m_prefs.getString("login", null));
put("password", m_prefs.getString("password", null));
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}

View File

@ -4,6 +4,7 @@ import android.app.Activity;
import android.app.FragmentTransaction; import android.app.FragmentTransaction;
import android.content.Intent; import android.content.Intent;
import android.content.SharedPreferences; import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle; import android.os.Bundle;
import android.preference.PreferenceManager; import android.preference.PreferenceManager;
import android.util.Log; import android.util.Log;
@ -16,7 +17,6 @@ public class MainActivity extends Activity {
private SharedPreferences m_prefs; private SharedPreferences m_prefs;
private String m_themeName = ""; private String m_themeName = "";
private String m_sessionId;
private boolean m_feedsOpened = false; private boolean m_feedsOpened = false;
/** Called when the activity is first created. */ /** Called when the activity is first created. */
@ -34,16 +34,8 @@ public class MainActivity extends Activity {
m_themeName = m_prefs.getString("theme", "THEME_DARK"); m_themeName = m_prefs.getString("theme", "THEME_DARK");
Bundle extras = getIntent().getExtras();
if (extras != null) {
m_sessionId = extras.getString("sessionId");
}
if (savedInstanceState != null) { if (savedInstanceState != null) {
m_sessionId = savedInstanceState.getString("sessionId");
m_feedsOpened = savedInstanceState.getBoolean("feedsOpened"); m_feedsOpened = savedInstanceState.getBoolean("feedsOpened");
Log.d(TAG, "FU: " + m_feedsOpened);
} }
setContentView(R.layout.main); setContentView(R.layout.main);
@ -54,8 +46,6 @@ public class MainActivity extends Activity {
FragmentTransaction ft = getFragmentManager().beginTransaction(); FragmentTransaction ft = getFragmentManager().beginTransaction();
FeedsFragment frag = new FeedsFragment(); FeedsFragment frag = new FeedsFragment();
frag.initialize(m_sessionId);
ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out); ft.setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out);
ft.replace(R.id.feeds_container, frag); ft.replace(R.id.feeds_container, frag);
ft.commit(); ft.commit();
@ -69,7 +59,6 @@ public class MainActivity extends Activity {
public void onSaveInstanceState (Bundle out) { public void onSaveInstanceState (Bundle out) {
super.onSaveInstanceState(out); super.onSaveInstanceState(out);
out.putString("sessionId", m_sessionId);
out.putBoolean("feedsOpened", m_feedsOpened); out.putBoolean("feedsOpened", m_feedsOpened);
} }
@ -78,7 +67,7 @@ public class MainActivity extends Activity {
super.onResume(); super.onResume();
if (!m_prefs.getString("theme", "THEME_DARK").equals(m_themeName)) { if (!m_prefs.getString("theme", "THEME_DARK").equals(m_themeName)) {
Intent refresh = new Intent(this, LoginActivity.class); Intent refresh = new Intent(this, MainActivity.class);
startActivity(refresh); startActivity(refresh);
finish(); finish();
} }
@ -98,19 +87,9 @@ public class MainActivity extends Activity {
Intent intent = new Intent(this, PreferencesActivity.class); Intent intent = new Intent(this, PreferencesActivity.class);
startActivityForResult(intent, 0); startActivityForResult(intent, 0);
return true; return true;
case R.id.logout:
logout();
return true;
default: default:
return super.onOptionsItemSelected(item); return super.onOptionsItemSelected(item);
} }
} }
protected void logout() {
Intent intent = new Intent(this, LoginActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
startActivityForResult(intent, 0);
finish();
}
} }