diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..de7495b --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +# ignore all .swp files +*.swp \ No newline at end of file diff --git a/addSkill.java b/addSkill.java index 346af43..0896fae 100644 --- a/addSkill.java +++ b/addSkill.java @@ -20,7 +20,7 @@ public class addSkill extends Activity { protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.addrss); - +// setTitle("Add RSS window"); btnAdd = (Button) findViewById(R.id.btnAdd); diff --git a/src/CustomAdapter.java b/src/CustomAdapter.java new file mode 100644 index 0000000..c616b77 --- /dev/null +++ b/src/CustomAdapter.java @@ -0,0 +1,82 @@ +package com.example.lirurssreader_v4; + +import java.util.ArrayList; + +import org.jsoup.Jsoup; + +import android.content.Context; +import android.view.LayoutInflater; +import android.view.View; +import android.view.ViewGroup; +import android.widget.BaseAdapter; +import android.widget.TextView; + + +public class CustomAdapter extends BaseAdapter { + + private LayoutInflater inflater; + private ArrayList objects; + + + public CustomAdapter(Context context, ArrayList objects) { + inflater = LayoutInflater.from(context); + this.objects = objects; + } + + private class ViewHolder { + TextView tvTitle; + TextView tvDesc; + TextView tvLink; + TextView tvPubDate; + } + + @Override + public int getCount() { + // TODO Auto-generated method stub + return objects.size(); + } + + + + @Override + public long getItemId(int position) { + // TODO Auto-generated method stub + return position; + } + + public static String html2text(String html) { + return Jsoup.parse(html).text(); + } + + + @Override + public View getView(int position, View convertView, ViewGroup parent) { + // TODO Auto-generated method stub + ViewHolder holder = null; + if(convertView == null) { + holder = new ViewHolder(); + convertView = inflater.inflate(R.layout.item, null); + holder.tvTitle = (TextView) convertView.findViewById(R.id.tvTitle); + holder.tvDesc = (TextView) convertView.findViewById(R.id.tvDescription); + holder.tvLink = (TextView) convertView.findViewById(R.id.tvLink); + holder.tvPubDate = (TextView) convertView.findViewById(R.id.tvPubDate); + convertView.setTag(holder); + } else { + holder = (ViewHolder) convertView.getTag(); + } + holder.tvTitle.setText(objects.get(position).getTitle()); + // SpannedString Desc =new SpannedString(objects.get(position).getDescr()); + // holder.tvDesc.setText(Html.toHtml(Desc)); + holder.tvDesc.setText(html2text(objects.get(position).getDescr())); + holder.tvLink.setText(objects.get(position).getPdaUrl()); + holder.tvPubDate.setText(objects.get(position).getpubDate()); + return convertView; + } + + @Override + public post getItem(int position) { + return objects.get(position); + } + + +} diff --git a/src/CustomApplication.java b/src/CustomApplication.java new file mode 100644 index 0000000..3a2fbde --- /dev/null +++ b/src/CustomApplication.java @@ -0,0 +1,68 @@ +package com.example.lirurssreader_v4; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import android.app.Activity; +import android.app.Application; + +public class CustomApplication extends Application { + /** + * Maps between an activity class name and the list of currently running + * AsyncTasks that were spawned while it was active. + */ + private Map>> mActivityTaskMap; + + public CustomApplication() { + mActivityTaskMap = new HashMap>>(); + } + + public void removeTask(CustomAsyncTask task) { + for (Entry>> entry : mActivityTaskMap.entrySet()) { + List> tasks = entry.getValue(); + for (int i = 0; i < tasks.size(); i++) { + if (tasks.get(i) == task) { + tasks.remove(i); + break; + } + } + + if (tasks.size() == 0) { + mActivityTaskMap.remove(entry.getKey()); + return; + } + } + } + + public void addTask(Activity activity, CustomAsyncTask task) { + String key = activity.getClass().getCanonicalName(); + List> tasks = mActivityTaskMap.get(key); + if (tasks == null) { + tasks = new ArrayList>(); + mActivityTaskMap.put(key, tasks); + } + + tasks.add(task); + } + + public void detach(Activity activity) { + List> tasks = mActivityTaskMap.get(activity.getClass().getCanonicalName()); + if (tasks != null) { + for (CustomAsyncTask task : tasks) { + task.setActivity(null); + } + } + } + + public void attach(Activity activity) { + List> tasks = mActivityTaskMap.get(activity.getClass().getCanonicalName()); + if (tasks != null) { + for (CustomAsyncTask task : tasks) { + task.setActivity(activity); + } + } + } +} diff --git a/src/CustomAsyncTask.java b/src/CustomAsyncTask.java new file mode 100644 index 0000000..49d9b07 --- /dev/null +++ b/src/CustomAsyncTask.java @@ -0,0 +1,43 @@ +package com.example.lirurssreader_v4; + +import android.app.Activity; +import android.os.AsyncTask; + +public abstract class CustomAsyncTask extends AsyncTask { + protected CustomApplication mApp; + protected Activity mActivity; + + public CustomAsyncTask(Activity activity) { + mActivity = activity; + mApp = (CustomApplication) mActivity.getApplication(); + } + + public void setActivity(Activity activity) { + mActivity = activity; + if (mActivity == null) { + onActivityDetached(); + } + else { + onActivityAttached(); + } + } + + protected void onActivityAttached() {} + + protected void onActivityDetached() {} + + @Override + protected void onPreExecute() { + mApp.addTask(mActivity, this); + } + + @Override + protected void onPostExecute(TResult result) { + mApp.removeTask(this); + } + + @Override + protected void onCancelled() { + mApp.removeTask(this); + } +} diff --git a/src/DataBaseHelper.java b/src/DataBaseHelper.java new file mode 100644 index 0000000..068f77c --- /dev/null +++ b/src/DataBaseHelper.java @@ -0,0 +1,48 @@ +package com.example.lirurssreader_v4; + +import android.content.Context; +import android.database.sqlite.SQLiteDatabase; +import android.database.sqlite.SQLiteDatabase.CursorFactory; +import android.database.sqlite.SQLiteOpenHelper; +import android.util.Log; + +public class DataBaseHelper extends SQLiteOpenHelper { + + public DataBaseHelper(Context context, String name,CursorFactory factory, int version) + { + super(context, name, factory, version); + } + + @Override + public void onCreate(SQLiteDatabase _db) { + // TODO Auto-generated method stub + _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE); + _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE_USERS); + _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE_RSS_FEEDS); + _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE_OPTIONS); + _db.execSQL(LoginDataBaseAdapter.DATABASE_CREATE_FEEDS); + } + + @Override + public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion) { + // TODO Auto-generated method stub + + // Log the version upgrade. + Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data"); + + + // Upgrade the existing database to conform to the new version. Multiple + // previous versions can be handled by comparing _oldVersion and _newVersion + // values. + // The simplest case is to drop the old table and create a new one. + _db.execSQL("DROP TABLE IF EXISTS " + "LOGIN"); + _db.execSQL("DROP TABLE IF EXISTS " + "USERS"); + _db.execSQL("DROP TABLE IF EXISTS " + "RSS"); + _db.execSQL("DROP TABLE IF EXISTS " + "FEEDS"); + _db.execSQL("DROP TABLE IF EXISTS " + "OPTIONS"); + // Create a new one. + onCreate(_db); + + } + +} diff --git a/src/LoginDataBaseAdapter.java b/src/LoginDataBaseAdapter.java new file mode 100644 index 0000000..6c212d5 --- /dev/null +++ b/src/LoginDataBaseAdapter.java @@ -0,0 +1,399 @@ +package com.example.lirurssreader_v4; + +import android.content.ContentValues; +import android.content.Context; +import android.database.Cursor; +import android.database.SQLException; +import android.database.sqlite.SQLiteDatabase; +import android.widget.Toast; + +public class LoginDataBaseAdapter +{ + static final String DATABASE_NAME = "loginRss.db"; + + static final int DATABASE_VERSION = 1; + + public static final int NAME_COLUMN = 1; + // TODO: Create public field for each column in your table. + // SQL Statement to create a new database. + static final String DATABASE_CREATE = "create table "+"LOGIN"+ + "( " +"_id"+" integer primary key autoincrement,"+ "USERNAME text,PASSWORD text); "; + static final String DATABASE_CREATE_USERS = "create table "+"USERS"+ + "( " +"_id"+" integer primary key autoincrement,"+ "USERNAME text,LASTIN text); "; + static final String DATABASE_CREATE_RSS_FEEDS = "create table "+"RSS"+ + "( " +"_id"+" integer primary key autoincrement,"+ "URL text,NAME text, USER text, NAMEOUT text); "; + static final String DATABASE_CREATE_OPTIONS = "create table OPTIONS"+ + "( " +"_id"+" integer primary key autoincrement,"+ "NUMLOAD text, USER text, FASTLOAD text); "; + static final String DATABASE_CREATE_FEEDS = "create table FEEDS"+ + "( " +"_id"+" integer primary key autoincrement,"+ "DATEPOST text, TITLE text,URL text UNIQUE ON CONFLICT REPLACE, USER text ); "; + + // Variable to hold the database instance + public SQLiteDatabase db; + // Context of the application using the database. + private final Context context; + // Database open/upgrade helper + private DataBaseHelper dbHelper; + public LoginDataBaseAdapter(Context _context) + { + context = _context; + dbHelper = new DataBaseHelper(context, DATABASE_NAME, null, DATABASE_VERSION); + } + + // Method to openthe Database + public LoginDataBaseAdapter open() throws SQLException + { + db = dbHelper.getWritableDatabase(); + return this; + } + + // Method to close the Database + public void close() + { + db.close(); + } + + // method returns an Instance of the Database + public SQLiteDatabase getDatabaseInstance() + { + return db; + } + + // method to insert a record in Table FEEDS + public void insertEntryFeed(String userName,String title, String datepost, String URL) + { + + + ContentValues newValues = new ContentValues(); + // Assign values for each column. + newValues.put("USER", userName); + newValues.put("TITLE", title); + newValues.put("URL", URL); + newValues.put("DATEPOST", datepost); + + // Insert the row into your table + db.insert("FEEDS", null, newValues); + // Toast.makeText(context, "User Info Saved", Toast.LENGTH_LONG).show(); + + + } + + // method to insert a record in Table + public void insertEntry(String userName,String password) + { + + + ContentValues newValues = new ContentValues(); + // Assign values for each column. + newValues.put("USERNAME", userName); + newValues.put("PASSWORD",password); + + + + // Insert the row into your table + db.insert("LOGIN", null, newValues); + // Toast.makeText(context, "User Info Saved", Toast.LENGTH_LONG).show(); + + + } + + // method to insert a record in Table + public void insertEntryOptions(String userName,String NUMLOAD, String load) + { + + + ContentValues newValues = new ContentValues(); + // Assign values for each column. + newValues.put("USER", userName); + newValues.put("NUMLOAD",NUMLOAD); + newValues.put("FASTLOAD",load); + + + + // Insert the row into your table + db.insert("OPTIONS", null, newValues); + // Toast.makeText(context, "User Info Saved", Toast.LENGTH_LONG).show(); + + + } + + // Method to Update an Existing Record + public void updateEntryOptions(String userName,String NUMLOAD, String fastload) + { + // create object of ContentValues + ContentValues updatedValues = new ContentValues(); + // Assign values for each Column. + updatedValues.put("USER", userName); + updatedValues.put("NUMLOAD",NUMLOAD); + updatedValues.put("FASTLOAD", fastload); + + String where="USER = ?"; + db.update("OPTIONS",updatedValues, where, new String[]{userName}); + + } + + // method to insert a record in Table + public void insertEntryRSS(String URL,String NAME, String USER) + { + + + ContentValues newValues = new ContentValues(); + // Assign values for each column. + newValues.put("URL", URL); + newValues.put("NAME",NAME); + newValues.put("USER",USER); + newValues.put("NAMEOUT",NAME); + + + + // Insert the row into your table + db.insert("RSS", null, newValues); + // Toast.makeText(context, "RSS Info Saved", Toast.LENGTH_LONG).show(); + + + } + + // method to insert a record in Table + public void insertEntryUsers(String userName,String lastin) + { + + + ContentValues newValues = new ContentValues(); + // Assign values for each column. + newValues.put("USERNAME", userName); + newValues.put("LASTIN",lastin); + + + + // Insert the row into your table + db.insert("USERS", null, newValues); + // Toast.makeText(context, "User Info Saved in USERS", Toast.LENGTH_LONG).show(); + + + } + + // method to delete a Record of UserName + public int deleteEntry(String UserName) + { + + String where="USERNAME=?"; + int numberOFEntriesDeleted= db.delete("LOGIN", where, new String[]{UserName}) ; + Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show(); + return numberOFEntriesDeleted; + + } + + // method to delete a Record of UserName + public int deleteEntryUSERS(String UserName) + { + + String where="USERNAME=?"; + int numberOFEntriesDeleted= db.delete("USERS", where, new String[]{UserName}) ; + Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show(); + return numberOFEntriesDeleted; + + } + + // method to delete a Record of UserName + public int deleteEntryRSS(String NAME) + { + + String where="NAME=? or NAMEOUT=?"; + int numberOFEntriesDeleted= db.delete("RSS", where, new String[]{NAME, NAME}) ; + Toast.makeText(context, "Number fo Entry Deleted Successfully : "+numberOFEntriesDeleted, Toast.LENGTH_LONG).show(); + return numberOFEntriesDeleted; + + } + + // method to get the password of userName + public String getSinlgeEntry(String userName) + { + + + Cursor cursor=db.query("LOGIN", null, " USERNAME=?", new String[]{userName}, null, null, null); + if(cursor.getCount()<1) // UserName Not Exist + return "NOT EXIST"; + cursor.moveToFirst(); + String password= cursor.getString(cursor.getColumnIndex("PASSWORD")); + return password; + + + } + + // method to get the password of userName + public String getSinlgeEntryURLF(String url) + { + + + Cursor cursor=db.query("FEEDS", null, " URL=?", new String[]{url}, null, null, null); + if(cursor.getCount()<1) // URL Not Exist + return "NOT EXIST"; + cursor.moveToFirst(); + String password= cursor.getString(cursor.getColumnIndex("URL")); + return password; + + + } + + // получить все данные из таблицы DB_TABLE + public Cursor getAlldata() { + return db.query("RSS", null, null, null, null, null, null); + } + + // получить все данные из таблицы DB_TABLE + public Cursor getAlldata(String tbl) { + return db.query(tbl, null, null, null, null, null, null); + } + + public Cursor getRSSNames(String user) { + String strSQL = "SELECT NAMEOUT as mname , * FROM RSS" + + " WHERE USER = '"+user+"'"; + try + { + Cursor cursor = db.rawQuery(strSQL, null); + return cursor; + + } catch (Exception e) { + + return null; + + } + } + + public Cursor getRSSbyName(String name) { + String strSQL = "SELECT URL as mUrl , * FROM RSS" + + " WHERE NAMEOUT = '"+name+"'"; + try + { + Cursor cursor = db.rawQuery(strSQL, null); + return cursor; + + } catch (Exception e) { + + return null; + + } + } + + // method to get the password of userName + public String getNUMLOAD(String userName) + { + + + Cursor cursor=db.query("OPTIONS", null, " USER=?", new String[]{userName}, null, null, null); + if(cursor.getCount()<1) // UserName Not Exist + return "NOT EXIST"; + cursor.moveToFirst(); + String numload= cursor.getString(cursor.getColumnIndex("NUMLOAD")); + return numload; + + + } + + // method to get the password of userName + public String getFastLoad(String userName) + { + + + Cursor cursor=db.query("OPTIONS", null, " USER=?", new String[]{userName}, null, null, null); + if(cursor.getCount()<1) // UserName Not Exist + return "true"; + cursor.moveToFirst(); + String fastload= cursor.getString(cursor.getColumnIndex("FASTLOAD")); + //cursor.getInt(cursor.getColumnIndex("FASTLOAD")); + return fastload; + + + } + + + // method to get the password of userName + public String getLastIn(String Lastin) + { + + + Cursor cursor=db.query("USERS", null, " LASTIN=?", new String[]{Lastin}, null, null, null); + if(cursor.getCount()<1) // UserName Not Exist + return "NOT EXIST"; + cursor.moveToFirst(); + String password= cursor.getString(cursor.getColumnIndex("USERNAME")); + return password; + + + } + + + + // Method to Update an Existing Record + public void updateEntry(String userName,String password) + { + // create object of ContentValues + ContentValues updatedValues = new ContentValues(); + // Assign values for each Column. + updatedValues.put("USERNAME", userName); + updatedValues.put("PASSWORD",password); + + String where="USERNAME = ?"; + db.update("LOGIN",updatedValues, where, new String[]{userName}); + + } + + // Method to Update an Existing Record + public void updateEntryRSS(String URL, String count) + { + String strSQL = "UPDATE RSS SET NAMEOUT = NAME || ' Новых: "+count+"' WHERE URL='"+URL+"'"; + try + { + db.execSQL(strSQL); + //Cursor cursor = db.rawQuery(strSQL, null); + + + } catch (Exception e) { + + + + } + + } + + // Method to Update an Existing Record + public void updateEntryLastin(String userName) + { + // create object of ContentValues + ContentValues updatedValues = new ContentValues(); + // Assign values for each Column. + // updatedValues.put("USERNAME", userName); + updatedValues.put("LASTIN","1"); + + String where="USERNAME <> ?"; + db.update("USERS",updatedValues, where, new String[]{userName}); + + + // updatedValues.put("USERNAME", userName); + updatedValues.put("LASTIN","0"); + + where="USERNAME = ?"; + db.update("USERS",updatedValues, where, new String[]{userName}); + + } + + // Method to Update an Existing Record + public void updateEntryLogin(String userName, String password) + { + + + // create object of ContentValues + ContentValues updatedValues = new ContentValues(); + // Assign values for each Column. + updatedValues.put("USERNAME", userName); + updatedValues.put("PASSWORD",password); + + + + String where="USERNAME = ?"; + db.update("LOGIN",updatedValues, where, new String[]{userName}); + + } + + + +} diff --git a/src/MainActivity.java b/src/MainActivity.java new file mode 100644 index 0000000..89c48f5 --- /dev/null +++ b/src/MainActivity.java @@ -0,0 +1,651 @@ +package com.example.lirurssreader_v4; + + +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.ArrayList; +import java.util.List; + +import android.app.Activity; +import android.app.Dialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnCancelListener; +import android.content.Intent; +import android.net.ConnectivityManager; +import android.net.NetworkInfo; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.view.Menu; +import android.view.View; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Toast; +import ch.boye.httpclientandroidlib.HttpEntity; +import ch.boye.httpclientandroidlib.NameValuePair; +import ch.boye.httpclientandroidlib.client.ClientProtocolException; +import ch.boye.httpclientandroidlib.client.entity.UrlEncodedFormEntity; +import ch.boye.httpclientandroidlib.client.methods.HttpGet; +import ch.boye.httpclientandroidlib.client.methods.HttpPost; +import ch.boye.httpclientandroidlib.client.params.ClientPNames; +import ch.boye.httpclientandroidlib.client.params.CookiePolicy; +import ch.boye.httpclientandroidlib.cookie.Cookie; +import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient; +import ch.boye.httpclientandroidlib.message.BasicNameValuePair; + + +public class MainActivity extends Activity { + + ProgressDialog progress; + HttpPost httppost; + + + + //MyAsyncTask mt; + + LoginDataBaseAdapter loginDataBaseAdapter; + + final int PROGRESS_DLG_ID = 6; + + /*@Override + protected Dialog onCreateDialog(int dialogId){ + ProgressDialog progress = null; + switch (dialogId) { + case PROGRESS_DLG_ID: + progress = new ProgressDialog(this); + progress.setMessage("Loading..."); + + break; + } + return progress; + } + */ + + + + static void isNetworkAvailable(final Handler handler, final int timeout) { + + // ask fo message '0' (not connected) or '1' (connected) on 'handler' + // the answer must be send before before within the 'timeout' (in milliseconds) + + new Thread() { + + private boolean responded = false; + + @Override + public void run() { + + // set 'responded' to TRUE if is able to connect with google mobile (responds fast) + + new Thread() { + + @Override + public void run() { + HttpGet requestForTest = new HttpGet("http://chizzx.p.ht/"); + try { + new DefaultHttpClient().execute(requestForTest); // can last... + responded = true; + } catch (Exception e) {} + } + + }.start(); + + try { + int waited = 0; + while(!responded && (waited < timeout)) { + sleep(100); + if(!responded ) { + waited += 100; + } + } + } + catch(InterruptedException e) {} // do nothing + finally { + if (!responded) { handler.sendEmptyMessage(0); } + else { handler.sendEmptyMessage(1); } + } + + } + + }.start(); + } + + + public boolean isOnline(){ + ConnectivityManager cm =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo netInfo = cm.getActiveNetworkInfo(); + if(netInfo !=null&& netInfo.isConnectedOrConnecting()) + { + return true;} + return false; + } + + private boolean haveNetworkConnection() { + boolean haveConnectedWifi = false; + boolean haveConnectedMobile = false; + + ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); + NetworkInfo[] netInfo = cm.getAllNetworkInfo(); + for (NetworkInfo ni : netInfo) { + if (ni.getTypeName().equalsIgnoreCase("WIFI")) + if (ni.isConnected()) + haveConnectedWifi = true; + if (ni.getTypeName().equalsIgnoreCase("MOBILE")) + if (ni.isConnected()) + haveConnectedMobile = true; + } + + return haveConnectedWifi || haveConnectedMobile ; +/* if (haveConnectedWifi || haveConnectedMobile) + { + try { + InetAddress addr = InetAddress.getByName(URL); + if(addr!=null){ + return true; + } + } + catch (UnknownHostException e) { + Log.d("RemoteDnsCheck", "UnknownHostException"); + }*/ + + } + + public static class MyAsyncTask extends CustomAsyncTask> { + + + LoginDataBaseAdapter loginDataBaseAdapterAT; + private String userName,password; + List cookies ; + + private ProgressDialog mProgress; + private int mCurrProgress; + + + public MyAsyncTask(MainActivity activity) { + super(activity); + } + + @Override + protected void onActivityDetached() { + if (mProgress != null) { + mProgress.dismiss(); + mProgress = null; + } + } + + @Override + protected void onActivityAttached() { + showProgressDialog(); + } + + @Override + protected void onPreExecute() { + super.onPreExecute(); + showProgressDialog(); + } + + private void showProgressDialog() { + // if (mProgress == null) + mProgress = new ProgressDialog(mActivity); + mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER); + mProgress.setMessage("Авторизация на liveinternet..."); + mProgress.setCancelable(true); + mProgress.setOnCancelListener(new OnCancelListener() { + @Override + public void onCancel(DialogInterface dialog) { + cancel(true); + } + }); + + mProgress.show(); + mProgress.setProgress(mCurrProgress); + } + + + + protected void onPostExecute(List cookies) { + + + if (mActivity != null) { + mProgress.dismiss(); + if (cookies.isEmpty()) { + //for (Cookie a : cookies) + // cookieStore.addCookie(a); + Toast.makeText(mActivity, "Error register. Username or password incorrect.", Toast.LENGTH_LONG).show(); + } else { + Intent intent = new Intent(mActivity,rssFeeds.class); + loginDataBaseAdapterAT=new LoginDataBaseAdapter(mActivity); + loginDataBaseAdapterAT=loginDataBaseAdapterAT.open(); + if (loginDataBaseAdapterAT.getSinlgeEntry(userName).equals("NOT EXIST")) + { loginDataBaseAdapterAT.insertEntry(userName, password); + loginDataBaseAdapterAT.insertEntryUsers(userName, "0");} + else + loginDataBaseAdapterAT.updateEntryLogin(userName,password); + + + loginDataBaseAdapterAT.updateEntryLastin(userName); + + loginDataBaseAdapterAT.close(); + for (Cookie a : cookies) { + // cookieStore.addCookie(a); + // Log.w("MyLog","- " + a.getName().toString()); + // Log.w("MyLog","- " + a.getValue().toString()); + + intent.putExtra(a.getName().toString(), a.getValue().toString()); + + } + + // + // loginDataBaseAdapterAT.updateEntryLogin(userName,password); + // + mActivity.startActivity(intent); + // Toast.makeText(MainActivity.this, "Login Successfull", Toast.LENGTH_LONG).show(); + // dialog.dismiss(); + + + } + // Toast.makeText(mActivity, "Авторизация ", Toast.LENGTH_LONG).show(); + } + else { + // Log.d(TAG, "AsyncTask finished while no Activity was attached."); + } + + + + + } + + + @Override + protected List doInBackground(String... params) { + + + DefaultHttpClient client; + + // publishProgress(new Void[]{}); //or null + userName = params[0]; + password = params[1]; + + // fetch the Password form database for respective user name + // loginDataBaseAdapterAT=new LoginDataBaseAdapter(MainActivity.this); + // loginDataBaseAdapterAT=loginDataBaseAdapterAT.open(); + + try + { + client = new DefaultHttpClient(); + + client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); + //mt = new MyTask(); + // mt.execute(userName,storedPassword); + List formparams = new ArrayList(); + formparams.add(new BasicNameValuePair("username", userName)); + formparams.add(new BasicNameValuePair("password", password)); + // formparams.add(new BasicNameValuePair("username", params[0])); + // formparams.add(new BasicNameValuePair("password", params[1])); + formparams.add(new BasicNameValuePair("action", "login")); + HttpEntity entity; + + entity = new UrlEncodedFormEntity(formparams, "UTF-8"); + HttpPost httppost = new HttpPost("https://www.liveinternet.ru/member.php?rndm=1234567890"); + httppost.setEntity(entity); + client.execute(httppost); + cookies = client.getCookieStore().getCookies(); + //loginDataBaseAdapterAT.close(); + return cookies; + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + catch (ClientProtocolException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + /* String storedPassword=loginDataBaseAdapterAT.getSinlgeEntry(userName); + if (!storedPassword.equals("NOT EXIST")) + { + try { + // create the instance of Databse + // loginDataBaseAdapter=new LoginDataBaseAdapter(MainActivity.this); + + loginDataBaseAdapterAT.updateEntryLastin(userName); + // соединиться + // достать куки и сохранить их. + // TODO открыть другой активити, передать ему куки. + + client = new DefaultHttpClient(); + + client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); + //mt = new MyTask(); + // mt.execute(userName,storedPassword); + List formparams = new ArrayList(); + formparams.add(new BasicNameValuePair("username", userName)); + formparams.add(new BasicNameValuePair("password", storedPassword)); + // formparams.add(new BasicNameValuePair("username", params[0])); + // formparams.add(new BasicNameValuePair("password", params[1])); + formparams.add(new BasicNameValuePair("action", "login")); + HttpEntity entity; + + entity = new UrlEncodedFormEntity(formparams, "UTF-8"); + HttpPost httppost = new HttpPost("https://www.liveinternet.ru/member.php?rndm=1234567890"); + httppost.setEntity(entity); + client.execute(httppost); + cookies = client.getCookieStore().getCookies(); + loginDataBaseAdapterAT.close(); + return cookies; + + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + catch (ClientProtocolException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + + + + +} + else + { + // сохранить пароль и соедининиться. + try + { + // create the instance of Databse + // loginDataBaseAdapter=new LoginDataBaseAdapter(MainActivity.this); + // loginDataBaseAdapter=loginDataBaseAdapter.open(); + loginDataBaseAdapterAT.insertEntry(userName, password); + loginDataBaseAdapterAT.insertEntryUsers(userName, "0"); + loginDataBaseAdapterAT.updateEntryLastin(userName); + + client = new DefaultHttpClient(); + + client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); + //mt = new MyTask(); + // mt.execute(userName,storedPassword); + List formparams = new ArrayList(); + formparams.add(new BasicNameValuePair("username", userName)); + formparams.add(new BasicNameValuePair("password", password)); + // formparams.add(new BasicNameValuePair("username", params[0])); + // formparams.add(new BasicNameValuePair("password", params[1])); + formparams.add(new BasicNameValuePair("action", "login")); + HttpEntity entity; + + entity = new UrlEncodedFormEntity(formparams, "UTF-8"); + HttpPost httppost = new HttpPost("https://www.liveinternet.ru/member.php?rndm=1234567890"); + httppost.setEntity(entity); + client.execute(httppost); + cookies = client.getCookieStore().getCookies(); + loginDataBaseAdapterAT.close(); + return cookies; + + } catch (UnsupportedEncodingException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + + catch (ClientProtocolException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } catch (IOException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + }*/ + return cookies; + } + + + + protected void onProgressUpdate(Integer... progress) { + mCurrProgress = progress[0]; + if (mActivity != null) { + mProgress.setProgress(mCurrProgress); + } + else { + // Log.d(TAG, "Progress updated while no Activity was attached."); + } + } + + /* *//** {@inheritDoc} *//* + @Override + protected final void onPreExecute() { + final List target = mTarget.get(); + if (target != null) { + this.onPreExecute(target); + } + }*/ + + + + } + + + @Override + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.activity_main); + + //signIn(); + } + + @Override + protected void onResume() + { + super.onResume(); + signIn(); + } + + + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.main, menu); + return true; + } + + public String getCookie(String inputstr,String cookie) + { + int index; + String result = ""; + index = inputstr.indexOf(cookie); + if (index!=-1) + { + result = inputstr.substring(index+cookie.length()+1, inputstr.indexOf(";",index)); + } + else + { + result = "NoCookie"; + } + return result; + } + // Methos to handleClick Event of Sign In Button + public void signIn() + { + + final Dialog dialog = new Dialog(MainActivity.this); + + dialog.setContentView(R.layout.login); + dialog.setTitle("Login"); + + // create the instance of Databse + loginDataBaseAdapter=new LoginDataBaseAdapter(MainActivity.this); + loginDataBaseAdapter=loginDataBaseAdapter.open(); + + // get the Refferences of views + final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin); + final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin); + + String LastUser=loginDataBaseAdapter.getLastIn("0"); + if (!LastUser.equals("NOT EXIST")) + { + editTextUserName.setText(LastUser); + editTextPassword.setText(loginDataBaseAdapter.getSinlgeEntry(LastUser)); + } + /* else + { + loginDataBaseAdapter.insertEntry( editTextUserName.getText().toString(), editTextPassword.getText().toString()); + loginDataBaseAdapter.insertEntryUsers(editTextUserName.getText().toString(), "0"); + loginDataBaseAdapter.updateEntryLastin(editTextUserName.getText().toString()); + }*/ + + + + + + + + Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn); + dialog.show(); + // Set On ClickListener + btnSignIn.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + + // mt = new MyAsyncTask(); + // mt.execute(editTextUserName.getText().toString(),editTextPassword.getText().toString()); + if (haveNetworkConnection()) + { + + Handler h = new Handler() { + + @Override + public void handleMessage(Message msg) { + + if (msg.what != 1) { Toast.makeText(MainActivity.this, "No internet connection. Try again.", Toast.LENGTH_LONG).show(); + + } else { new MyAsyncTask(MainActivity.this).execute(editTextUserName.getText().toString(),editTextPassword.getText().toString()); + dialog.dismiss(); + + } + + } + }; + + isNetworkAvailable(h,5000); + + } + else + { + Toast.makeText(MainActivity.this, "No internet connection. Try again.", Toast.LENGTH_LONG).show(); + } + } + }); + + loginDataBaseAdapter.close(); + + + + + } + + @Override + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + + ((CustomApplication) getApplication()).detach(this); + } + + @Override + public void onRestoreInstanceState(Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + + ((CustomApplication) getApplication()).attach(this); + } + + // Methos to handleClick Event of Sign In Button + public void signIn(View V) + { + + final Dialog dialog = new Dialog(MainActivity.this); + + dialog.setContentView(R.layout.login); + dialog.setTitle("Login"); + + // create the instance of Databse + loginDataBaseAdapter=new LoginDataBaseAdapter(MainActivity.this); + loginDataBaseAdapter=loginDataBaseAdapter.open(); + + // get the Refferences of views + final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin); + final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin); + + String LastUser=loginDataBaseAdapter.getLastIn("0"); + if (!LastUser.equals("NOT EXIST")) + { + editTextUserName.setText(LastUser); + editTextPassword.setText(loginDataBaseAdapter.getSinlgeEntry(LastUser)); + } + /* else + { + loginDataBaseAdapter.insertEntry( editTextUserName.getText().toString(), editTextPassword.getText().toString()); + loginDataBaseAdapter.insertEntryUsers(editTextUserName.getText().toString(), "0"); + loginDataBaseAdapter.updateEntryLastin(editTextUserName.getText().toString()); + }*/ + + + + + + + + Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn); + dialog.show(); + // Set On ClickListener + btnSignIn.setOnClickListener(new View.OnClickListener() { + + public void onClick(View v) { + + // mt = new MyAsyncTask(); + // mt.execute(editTextUserName.getText().toString(),editTextPassword.getText().toString()); + if (haveNetworkConnection()) + { + Handler h = new Handler() { + + @Override + public void handleMessage(Message msg) { + + if (msg.what != 1) { Toast.makeText(MainActivity.this, "No internet connection. Try again.", Toast.LENGTH_LONG).show(); + + } else { new MyAsyncTask(MainActivity.this).execute(editTextUserName.getText().toString(),editTextPassword.getText().toString()); + dialog.dismiss(); + + } + + } + }; + + isNetworkAvailable(h,5000); + + } + else + { + Toast.makeText(MainActivity.this, "No internet connection. Try again.", Toast.LENGTH_LONG).show(); + } + } + }); + + loginDataBaseAdapter.close(); + + + + + } + + + +} diff --git a/src/ViewActivity.java b/src/ViewActivity.java new file mode 100644 index 0000000..6967dfe --- /dev/null +++ b/src/ViewActivity.java @@ -0,0 +1,523 @@ +package com.example.lirurssreader_v4; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; +import org.xmlpull.v1.XmlPullParserFactory; + +import com.example.lirurssreader_v4.rssFeeds.MyAsyncTask; + +import android.app.Activity; +import android.app.ProgressDialog; +import android.content.DialogInterface; +import android.content.DialogInterface.OnCancelListener; +import android.content.Intent; +import android.net.Uri; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.util.Log; +import android.view.View; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.ListView; +import android.widget.TextView; +import android.widget.Toast; +import ch.boye.httpclientandroidlib.HeaderElement; +import ch.boye.httpclientandroidlib.HttpEntity; +import ch.boye.httpclientandroidlib.HttpResponse; +import ch.boye.httpclientandroidlib.NameValuePair; +import ch.boye.httpclientandroidlib.ParseException; +import ch.boye.httpclientandroidlib.client.ClientProtocolException; +import ch.boye.httpclientandroidlib.client.entity.UrlEncodedFormEntity; +import ch.boye.httpclientandroidlib.client.methods.HttpGet; +import ch.boye.httpclientandroidlib.client.methods.HttpPost; +import ch.boye.httpclientandroidlib.client.params.ClientPNames; +import ch.boye.httpclientandroidlib.client.params.CookiePolicy; +import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient; +import ch.boye.httpclientandroidlib.message.BasicNameValuePair; +import ch.boye.httpclientandroidlib.protocol.HTTP; + +public class ViewActivity extends Activity { + + final String LOG_TAG = "MyLog"; + String currentTag = ""; + static String jidStr,postLink; + private static ListView listview; + private static TextView cAdName; + //MyAsyncTask mt; + //final int PROGRESS_DLG_ID = 6; + + static void isNetworkAvailable(final Handler handler, final int timeout) { + + // ask fo message '0' (not connected) or '1' (connected) on 'handler' + // the answer must be send before before within the 'timeout' (in milliseconds) + + new Thread() { + + private boolean responded = false; + + @Override + public void run() { + + // set 'responded' to TRUE if is able to connect with google mobile (responds fast) + + new Thread() { + + @Override + public void run() { + HttpGet requestForTest = new HttpGet("http://chizzx.p.ht/"); + try { + new DefaultHttpClient().execute(requestForTest); // can last... + responded = true; + } catch (Exception e) {} + } + + }.start(); + + try { + int waited = 0; + while(!responded && (waited < timeout)) { + sleep(100); + if(!responded ) { + waited += 100; + } + } + } + catch(InterruptedException e) {} // do nothing + finally { + if (!responded) { handler.sendEmptyMessage(0); } + else { handler.sendEmptyMessage(1); } + } + + } + + }.start(); + } + + + public static class MyAsyncTask extends CustomAsyncTask> { + + ArrayList objects; + LoginDataBaseAdapter loginDataBaseAdapter; + + private ProgressDialog mProgress; + private int mCurrProgress; + + public MyAsyncTask(ViewActivity activity) { + super(activity); + } + + @Override + protected void onPreExecute() { + super.onPreExecute(); + showProgressDialog(); + } + + @Override + protected void onActivityDetached() { + if (mProgress != null) { + mProgress.dismiss(); + mProgress = null; + } + } + + @Override + protected void onActivityAttached() { + showProgressDialog(); + } + + private void showProgressDialog() { + // if (mProgress == null) + mProgress = new ProgressDialog(mActivity); + mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER); + mProgress.setMessage("Загрузка RSS ленты..."); + mProgress.setCancelable(true); + mProgress.setOnCancelListener(new OnCancelListener() { + @Override + public void onCancel(DialogInterface dialog) { + cancel(true); + } + }); + + mProgress.show(); + mProgress.setProgress(mCurrProgress); + } + + protected void onPostExecute(ArrayList objects) { + if (mActivity != null) { + mProgress.dismiss(); + CustomAdapter customAdapter = new CustomAdapter(mActivity, objects); + listview = (ListView) mActivity.findViewById(R.id.lView); + listview.setAdapter(customAdapter); + listview.setOnItemClickListener(new OnItemClickListener() { + public void onItemClick(AdapterView parent, View view, + int position, long id) { + + // final String user = (String) ((Cursor) listview + // .getItemAtPosition(position)).getString(1); + + cAdName = (TextView) view.findViewById(R.id.tvLink); + String goTo = cAdName.getText().toString(); + if (!goTo.startsWith("http://") && !goTo.startsWith("https://")) + goTo = "http://" + goTo; + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(goTo)); + mActivity.startActivity(browserIntent); + // Toast.makeText(ViewActivity.this, "URLtoGO:" + cAdName.getText().toString(), Toast.LENGTH_LONG).show(); + + + } + }); + Toast.makeText(mActivity, "Загрузка RSS ленты завершена", Toast.LENGTH_LONG).show(); + } + else { + //Log.d(TAG, "AsyncTask finished while no Activity was attached."); + } + // dismissDialog(PROGRESS_DLG_ID); + // add objects to CustomAdapter + + // bind adapter to ListView + + } + + + protected void onProgressUpdate(Integer... progress) { + // super.onProgressUpdate(values); + mCurrProgress = progress[0]; + if (mActivity != null) { + mProgress.setProgress(mCurrProgress); + } + else { + //Log.d(TAG, "Progress updated while no Activity was attached."); + } + // showDialog(PROGRESS_DLG_ID); + } + + + @Override + protected ArrayList doInBackground(String... params) { + //publishProgress(new Void[]{}); + try { + + loginDataBaseAdapter=new LoginDataBaseAdapter(mActivity); + loginDataBaseAdapter=loginDataBaseAdapter.open(); + DefaultHttpClient client = new DefaultHttpClient(); + client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); + String mUrl = params[0]; + String jurl = params[1]; + String bbuserid = params[2]; + String bbpassword = params[3]; + String bbusername = params[4]; + String numload = params[5]; + String fastload = params[6]; + + // boolean howToLoad = true; + HttpResponse response; +// если мы делаем через лиру, то это + if (fastload.equals("false")) + { + HttpGet httpGet = new HttpGet(mUrl); + httpGet.addHeader("Cookie", "chbx=guest; jurl="+jurl+"; ucss=normal; bbuserid="+bbuserid+"; bbpassword="+bbpassword+"; bbusername="+bbusername); + response = client.execute(httpGet); + } + else + { + // mUrl = "http://liveinternet.ru/users/chert/rss/"; + // client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); + List formparams = new ArrayList(6); + // bbusername = "Chizz_TecTeP"; + formparams.add(new BasicNameValuePair("jurl", jurl)); + formparams.add(new BasicNameValuePair("bbuserid", bbuserid)); + formparams.add(new BasicNameValuePair("bbpassword", bbpassword)); + formparams.add(new BasicNameValuePair("bbusername", bbusername)); + formparams.add(new BasicNameValuePair("url", mUrl)); + formparams.add(new BasicNameValuePair("count", numload)); + + /* Log.d("myLogs", jurl ); + Log.d("myLogs", bbuserid ); + Log.d("myLogs", bbpassword ); + Log.d("myLogs", bbusername ); + Log.d("myLogs", mUrl ); + */ + + + + + // formparams.add(new BasicNameValuePair("username", params[0])); + // formparams.add(new BasicNameValuePair("password", params[1])); + //formparams.add(new BasicNameValuePair("action", "http://chizzx.p.ht/rss/rss.php")); + HttpEntity entity; + + entity = new UrlEncodedFormEntity(formparams); // , "UTF-8" + HttpPost httppost = new HttpPost("http://chizzx.p.ht/rss/rss.php"); + httppost.setEntity(entity); + response = client.execute(httppost); + } + // если через chizzx.p.ht, то это + + + + objects = new ArrayList(); + String mTitle = ""; + String mDescr = ""; + String pdaUrl = ""; + String mpubDate = ""; + + /* String charset = getContentCharSet(response.getEntity()); + + if (charset == null) { + + charset = HTTP.DEFAULT_CONTENT_CHARSET; + + }*/ + + + + BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));//,charset + /* String sCurrentLine; + while ((sCurrentLine = rd.readLine()) != null) { + //System.out.println(sCurrentLine); + Log.d("myLogs", sCurrentLine ); + }*/ + + XmlPullParser xpp = prepareXpp(rd); + boolean itemStart = false; + int i = 0; + while ((xpp.getEventType() != XmlPullParser.END_DOCUMENT) && (i 0) { + + NameValuePair param = values[0].getParameterByName("charset"); + + if (param != null) { + + charset = param.getValue(); + + } + + } + + } + + return charset; + + } + + + + + + + + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.viewactivity); + + Intent intent = getIntent(); + + + String bbuserid = intent.getStringExtra("bbuserid"); + String bbpassword = intent.getStringExtra("bbpassword"); + String bbusername = intent.getStringExtra("bbusername"); + // String bbredirect = intent.getStringExtra("bbredirect"); + String jurl = intent.getStringExtra("jurl"); + String mUrl = intent.getStringExtra("url"); + String mNumload = intent.getStringExtra("numload"); + String fastload = intent.getStringExtra("fastload"); + + // String mUrl = params[0]; + // String jurl = params[1]; + // String bbuserid = params[2]; + // String bbpassword = params[3]; + // String bbusername = params[4]; + + // mt = new MyAsyncTask(); + // mt.execute(mUrl,jurl,bbuserid,bbpassword,bbusername,mNumload); + + + new MyAsyncTask(ViewActivity.this).execute(mUrl,jurl,bbuserid,bbpassword,bbusername,mNumload,fastload); + + + + + + + + //Toast.makeText(ViewActivity.this, "bbuserid:" + fName + " bbpassword: " + lName, Toast.LENGTH_LONG).show(); + + + } + +/* @Override + protected Dialog onCreateDialog(int dialogId){ + ProgressDialog progress = null; + switch (dialogId) { + case PROGRESS_DLG_ID: + progress = new ProgressDialog(this); + progress.setMessage("Loading..."); + + break; + } + return progress; + }*/ + + @Override + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + + ((CustomApplication) getApplication()).detach(this); + } + + @Override + public void onRestoreInstanceState(Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + + ((CustomApplication) getApplication()).attach(this); + } + + +} diff --git a/src/addSkill.java b/src/addSkill.java new file mode 100644 index 0000000..346af43 --- /dev/null +++ b/src/addSkill.java @@ -0,0 +1,68 @@ +package com.example.lirurssreader_v4; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.EditText; +import android.widget.Toast; + +public class addSkill extends Activity { + + final String LOG_TAG = "myLogs"; + Button btnAdd; + + LoginDataBaseAdapter loginDataBaseAdapter; + EditText etURL, etName; + + protected void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.addrss); + + setTitle("Add RSS window"); + + btnAdd = (Button) findViewById(R.id.btnAdd); + etURL = (EditText) findViewById(R.id.etURL); + etName = (EditText) findViewById(R.id.etName); + + loginDataBaseAdapter=new LoginDataBaseAdapter(this); + loginDataBaseAdapter=loginDataBaseAdapter.open(); + + OnClickListener oclBtnAdd = new OnClickListener() { + @Override + public void onClick(View v) { + // TODO add record to skill table + // создаем объект для данных + // ContentValues cv = new ContentValues(); + + // подключаемся к БД + // SQLiteDatabase db = dbHelper.getWritableDatabase(); + + String URL = etURL.getText().toString(); + String Name = etName.getText().toString(); + Intent intent = getIntent(); + + loginDataBaseAdapter.insertEntryRSS(URL, Name,intent.getStringExtra("USER")); + // cv.put("skill", skill); + // cv.put("value",value); + // long rowID = db.insert("TSkill", null, cv); + // Log.d(LOG_TAG, "row inserted, ID = " + rowID); + + Toast.makeText(getApplicationContext(), "row inserted, ID=", + Toast.LENGTH_LONG).show(); + } + }; + + btnAdd.setOnClickListener(oclBtnAdd); + + } + + protected void onDestroy() { + super.onDestroy(); + // закрываем подключение при выходе + loginDataBaseAdapter.close(); + } + +} diff --git a/src/options.java b/src/options.java new file mode 100644 index 0000000..fabedf9 --- /dev/null +++ b/src/options.java @@ -0,0 +1,175 @@ +package com.example.lirurssreader_v4; + +import android.app.Activity; +import android.content.Intent; +import android.os.Bundle; +import android.view.View; +import android.view.View.OnClickListener; +import android.widget.Button; +import android.widget.CheckBox; +import android.widget.EditText; +import android.widget.RadioGroup; +import android.widget.Toast; + +public class options extends Activity { + LoginDataBaseAdapter loginDataBaseAdapter; + EditText etNumLoad; + + private CheckBox chkIos; + private Button btnDisplay; + + + private String username; + @Override + public void onCreate(Bundle savedInstanceState) { + super.onCreate(savedInstanceState); + setContentView(R.layout.options); + + Intent intent = getIntent(); + username = intent.getStringExtra("USER"); + + // прочитать Options из базы, если есть. + + loginDataBaseAdapter=new LoginDataBaseAdapter(this); + loginDataBaseAdapter=loginDataBaseAdapter.open(); + + String numLoad = loginDataBaseAdapter.getNUMLOAD(username); + etNumLoad = (EditText) findViewById(R.id.etNumLoad); + chkIos = (CheckBox) findViewById(R.id.cbLoad); + + + + + + if (!numLoad.equals("NOT EXIST")) + { + if (numLoad.equals("1000")) + { + etNumLoad.setText("10"); + etNumLoad.setEnabled(false); + chkIos.setChecked(true); + } + else + { + etNumLoad.setText(numLoad); + etNumLoad.setEnabled(true); + chkIos.setChecked(false); + } + } + else + { + etNumLoad.setText("10"); + etNumLoad.setEnabled(false); + chkIos.setChecked(true); + } + + addListenerOnChkIos(); + addListenerOnButton(); + } + + protected void onDestroy() { + // закрываем подключение при выходе + // cursor_rep.close(); + // loginDataBaseAdapter.close(); + super.onDestroy(); + loginDataBaseAdapter.close(); + } + + public void addListenerOnChkIos() { + + //chkIos = (CheckBox) findViewById(R.id.cbLoad); + + chkIos.setOnClickListener(new OnClickListener() { + + @Override + public void onClick(View v) { + //is chkIos checked? + if (((CheckBox) v).isChecked()) { + etNumLoad.setEnabled(false); + } + else + { + etNumLoad.setEnabled(true); + } + + } + }); + + } + + public void addListenerOnButton() { + + chkIos = (CheckBox) findViewById(R.id.cbLoad); + + btnDisplay = (Button) findViewById(R.id.btnOK); + + btnDisplay.setOnClickListener(new OnClickListener() { + + //Run when button is clicked + @Override + public void onClick(View v) { + + String numLoad = loginDataBaseAdapter.getNUMLOAD(username); + RadioGroup radioGroup = (RadioGroup) findViewById(R.id.radiogroup); + int checkedRadioButton = radioGroup.getCheckedRadioButtonId(); + String fastload = "true"; + switch (checkedRadioButton) { + case R.id.radiobutton1 : fastload = "false" ; + break; + case R.id.radiobutton2 : fastload = "true"; + break; + + } + if (chkIos.isChecked()) + { + + if (!numLoad.equals("NOT EXIST")) + { + + loginDataBaseAdapter.updateEntryOptions(username, "1000",fastload); + Toast.makeText(options.this, "Options updated.", + Toast.LENGTH_LONG).show(); + } + else + { + + loginDataBaseAdapter.insertEntryOptions(username, "1000",fastload); + Toast.makeText(options.this, "Options saved.", + Toast.LENGTH_LONG).show(); + } + + } + else + { + + if (!numLoad.equals("NOT EXIST")) + { + loginDataBaseAdapter.updateEntryOptions(username, etNumLoad.getText().toString(),fastload); + Toast.makeText(options.this, "Options updated", + Toast.LENGTH_LONG).show(); + } + else + { + loginDataBaseAdapter.insertEntryOptions(username, etNumLoad.getText().toString(),fastload); + Toast.makeText(options.this, "Options saved.", + Toast.LENGTH_LONG).show(); + } + + } + + //StringBuffer result = new StringBuffer(); + // result.append("IPhone check : ").append(chkIos.isChecked()); + // result.append("\nAndroid check : ").append(chkAndroid.isChecked()); + // result.append("\nWindows Mobile check :").append(chkWindows.isChecked()); + + // Toast.makeText(MyAndroidAppActivity.this, result.toString(), + // Toast.LENGTH_LONG).show(); + + } + }); + + } + +} + + diff --git a/src/post.java b/src/post.java new file mode 100644 index 0000000..8f71e5e --- /dev/null +++ b/src/post.java @@ -0,0 +1,33 @@ +package com.example.lirurssreader_v4; + +//change git test + +public class post { +private String title; +private String descr; +private String pdaUrl; +private String pubDate; + +public post(String title, String descr, String pdaUrl, String pubDate) { + this.title = title; + this.descr = descr; + this.pdaUrl = pdaUrl; + this.pubDate = pubDate; + +} + +public String getTitle(){ + return title; +} + +public String getDescr() { + return descr; +} + +public String getPdaUrl() { + return pdaUrl; +} +public String getpubDate() { + return pubDate; +} +} diff --git a/src/rssFeeds.java b/src/rssFeeds.java new file mode 100644 index 0000000..5869e17 --- /dev/null +++ b/src/rssFeeds.java @@ -0,0 +1,733 @@ +package com.example.lirurssreader_v4; + + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.xmlpull.v1.XmlPullParser; +import org.xmlpull.v1.XmlPullParserException; +import org.xmlpull.v1.XmlPullParserFactory; + +import com.example.lirurssreader_v4.MainActivity.MyAsyncTask; + +import android.app.Activity; +import android.app.AlertDialog; +import android.app.ProgressDialog; +import android.content.Context; +import android.content.DialogInterface; +import android.content.DialogInterface.OnCancelListener; +import android.content.DialogInterface.OnClickListener; +import android.content.Intent; +import android.database.Cursor; +import android.os.Bundle; +import android.os.Handler; +import android.os.Message; +import android.view.Menu; +import android.view.MenuItem; +import android.view.View; +import android.widget.AdapterView; +import android.widget.AdapterView.OnItemClickListener; +import android.widget.AdapterView.OnItemLongClickListener; +import android.widget.ListView; +import android.widget.SimpleCursorAdapter; +import android.widget.Toast; +import ch.boye.httpclientandroidlib.HeaderElement; +import ch.boye.httpclientandroidlib.HttpEntity; +import ch.boye.httpclientandroidlib.HttpResponse; +import ch.boye.httpclientandroidlib.NameValuePair; +import ch.boye.httpclientandroidlib.ParseException; +import ch.boye.httpclientandroidlib.client.ClientProtocolException; +import ch.boye.httpclientandroidlib.client.methods.HttpGet; +import ch.boye.httpclientandroidlib.client.params.ClientPNames; +import ch.boye.httpclientandroidlib.client.params.CookiePolicy; +import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient; +import ch.boye.httpclientandroidlib.protocol.HTTP; + +public class rssFeeds extends Activity { + + final String LOG_TAG = "MyLog"; + + private ListView lvMain; + LoginDataBaseAdapter loginDataBaseAdapter,loginDataBaseAdapterAT; + + String current_task = ""; + + + String bbusername,bbuserid,bbpassword,jurl,url; + // final int PROGRESS_DLG_ID = 6; + String currentTag = ""; + static Cursor cursor_rep; + static SimpleCursorAdapter scAdapter; + + + static void isNetworkAvailable(final Handler handler, final int timeout) { + + // ask fo message '0' (not connected) or '1' (connected) on 'handler' + // the answer must be send before before within the 'timeout' (in milliseconds) + + new Thread() { + + private boolean responded = false; + + @Override + public void run() { + + // set 'responded' to TRUE if is able to connect with google mobile (responds fast) + + new Thread() { + + @Override + public void run() { + HttpGet requestForTest = new HttpGet("http://chizzx.p.ht/"); + try { + new DefaultHttpClient().execute(requestForTest); // can last... + responded = true; + } catch (Exception e) {} + } + + }.start(); + + try { + int waited = 0; + while(!responded && (waited < timeout)) { + sleep(100); + if(!responded ) { + waited += 100; + } + } + } + catch(InterruptedException e) {} // do nothing + finally { + if (!responded) { handler.sendEmptyMessage(0); } + else { handler.sendEmptyMessage(1); } + } + + } + + }.start(); + } + + + + public static XmlPullParser prepareXpp(BufferedReader rd) throws XmlPullParserException { + // получаем фабрику + XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); + // включаем поддержку namespace (по умолчанию выключена) + factory.setNamespaceAware(true); + // создаем парсер + XmlPullParser xpp = factory.newPullParser(); + // даем парсеру на вход Reader + xpp.setInput(rd); + return xpp; + } + + + public String DescrPrepare(String desc) { + String result = ""; + return result; + } + + // For the tags title and summary, extracts their text values. + private static String readText(XmlPullParser parser) throws IOException, XmlPullParserException { + String result = ""; + if (parser.next() == XmlPullParser.TEXT) { + result = parser.getText(); + parser.nextTag(); + } + return result; + } + + + public static String getContentCharSet(final HttpEntity entity) throws ParseException { + + if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } + + String charset = null; + + if (entity.getContentType() != null) { + + HeaderElement values[] = entity.getContentType().getElements(); + + if (values.length > 0) { + + NameValuePair param = values[0].getParameterByName("charset"); + + if (param != null) { + + charset = param.getValue(); + + } + + } + + } + + return charset; + + } + + public static class MyAsyncTask extends CustomAsyncTask { + static ArrayList objects; + LoginDataBaseAdapter loginDataBaseAdapterMT; + String position; + String jidStr,postLink; + + + + + + private static ProgressDialog mProgress; + private int mCurrProgress; + + public MyAsyncTask(rssFeeds activity) { + super(activity); + } + + @Override + protected void onPreExecute() { + super.onPreExecute(); + //if (mProgress==null) + showProgressDialog(); + } + + @Override + protected void onActivityDetached() { + if (mProgress != null) { + mProgress.dismiss(); + mProgress = null; + } + } + + @Override + protected void onActivityAttached() { + // if (mProgress == null) + showProgressDialog(); + } + + private void showProgressDialog() { + //if (mProgress == null) + mProgress = new ProgressDialog(mActivity); + mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER); + mProgress.setMessage("Обновление RSS лент..."); + mProgress.setCancelable(true); + + mProgress.setOnCancelListener(new OnCancelListener() { + @Override + public void onCancel(DialogInterface dialog) { + cancel(true); + } + }); + + mProgress.show(); + mProgress.setProgress(mCurrProgress); + } + + + + protected void onPostExecute(String name) { + //super.onPostExecute(params); + + if (mActivity != null) { + mProgress.dismiss(); + loginDataBaseAdapterMT=new LoginDataBaseAdapter(mActivity); + loginDataBaseAdapterMT=loginDataBaseAdapterMT.open(); + // loginDataBaseAdapterMT.updateEntryRSS(params.get(1), params.get(0)); + cursor_rep = loginDataBaseAdapterMT.getRSSNames(name); + scAdapter.changeCursor(cursor_rep); + loginDataBaseAdapterMT.close(); + + //Toast.makeText(mActivity, "Обновление завершено", Toast.LENGTH_LONG).show(); + } + else { + //Log.d(TAG, "AsyncTask finished while no Activity was attached."); + } + //Toast.makeText(rssFeeds.this, "Count:" + params.get(0) +"URL:" + params.get(1), Toast.LENGTH_LONG).show(); + // изменить соответствующий textView + // dismissDialog(PROGRESS_DLG_ID); + + + // lvMain.setAdapter(scAdapter); + // update table RSS + + // View convertedView = (View) lvMain.getAdapter().getItem(Integer.parseInt(position)); + + // TextView Text1 = (TextView)convertedView.findViewById(R.id.tvNew); + // Text1.setText("йохоу мазафака"); + //listview.getItemAtPosition(position).getString(0); + + + /* + // add objects to CustomAdapter + CustomAdapter customAdapter = new CustomAdapter(ViewActivity.this, objects); + // bind adapter to ListView + listview = (ListView) findViewById(R.id.lView); + listview.setAdapter(customAdapter); + listview.setOnItemClickListener(new OnItemClickListener() { + public void onItemClick(AdapterView parent, View view, + int position, long id) { + + // final String user = (String) ((Cursor) listview + // .getItemAtPosition(position)).getString(1); + + cAdName = (TextView) view.findViewById(R.id.tvLink); + String goTo = cAdName.getText().toString(); + if (!goTo.startsWith("http://") && !goTo.startsWith("https://")) + goTo = "http://" + goTo; + Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(goTo)); + startActivity(browserIntent); + // Toast.makeText(ViewActivity.this, "URLtoGO:" + cAdName.getText().toString(), Toast.LENGTH_LONG).show(); + + + } + });*/ + } + + protected void onProgressUpdate(Integer... progress) { + mCurrProgress = progress[0]; + if (mActivity != null) { + mProgress.setProgress(mCurrProgress); + } + else { + //Log.d(TAG, "Progress updated while no Activity was attached."); + } + } + + + + + @Override + protected String doInBackground(String... params) { + // publishProgress(new Void[]{}); + + + + + // int position = 1; + + + // + + + try { + + // String mUrl = params[0]; + String jurl = params[0]; + String bbuserid = params[1]; + String bbpassword = params[2]; + String bbusername = params[3]; + // String numload = params[4]; + + loginDataBaseAdapterMT=new LoginDataBaseAdapter(mActivity); + loginDataBaseAdapterMT=loginDataBaseAdapterMT.open(); + String numl = loginDataBaseAdapterMT.getNUMLOAD(bbusername); + if (numl.equals("NOT EXIST")) + numl="1000"; + + + Cursor cursor_all = loginDataBaseAdapterMT.getAlldata(); + + while (cursor_all.moveToNext()) { + + // определяем номера столбцов по имени в выборке + // int idColIndex = cursor_all.getColumnIndex("USER"); + // получаем значения по номерам столбцов + // String USER = cursor_all.getString(idColIndex); + + // определяем номера столбцов по имени в выборке + int idColIndex = cursor_all.getColumnIndex("URL"); + // получаем значения по номерам столбцов + String mUrl = cursor_all.getString(idColIndex); + // MyAsyncTask mt = new MyAsyncTask(); + // mt.execute(URL,jurl,bbuserid,bbpassword,bbusername,numl); + + // new MyAsyncTask(rssFeeds.this).execute(URL,jurl,bbuserid,bbpassword,bbusername,numl); + DefaultHttpClient client = new DefaultHttpClient(); + client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BROWSER_COMPATIBILITY); + + + // position = params[6]; + + + HttpGet httpGet = new HttpGet(mUrl); + httpGet.addHeader("Cookie", "chbx=guest; jurl="+jurl+"; ucss=normal; bbuserid="+bbuserid+"; bbpassword="+bbpassword+"; bbusername="+bbusername); + HttpResponse response = client.execute(httpGet); + + + + objects = new ArrayList(); + // String mTitle = ""; + // String mDescr = ""; + String pdaUrl = ""; + // String mpubDate = ""; + + String charset = getContentCharSet(response.getEntity()); + + if (charset == null) { + + charset = HTTP.DEFAULT_CONTENT_CHARSET; + + } + + BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(),charset)); + XmlPullParser xpp = prepareXpp(rd); + boolean itemStart = false; + int i = 0; + int countNew = 0; + while ((xpp.getEventType() != XmlPullParser.END_DOCUMENT) && (i parent, View view, int position, long id) { + //Log.e("MyApp", "get onItem Click position= " + position); + final String user = (String) ((Cursor) lvMain + .getItemAtPosition(position)).getString(0); + + AlertDialog.Builder ad; + Context context; + context = rssFeeds.this; + String title = "Удалить RSS: "+user+"?"; + ad = new AlertDialog.Builder(context); + ad.setTitle(title); // заголовок + String button1String = "Да"; + String button2String = "Нет"; + + ad.setPositiveButton(button1String, new OnClickListener() { + public void onClick(DialogInterface dialog, int arg1) { + // Toast.makeText(context, "Вы сделали правильный выбор", + // Toast.LENGTH_LONG).show(); + loginDataBaseAdapter.deleteEntryRSS(user); + cursor_rep = loginDataBaseAdapter.getRSSNames(bbusername); + scAdapter.changeCursor(cursor_rep); + + } + }); + ad.setNegativeButton(button2String, new OnClickListener() { + public void onClick(DialogInterface dialog, int arg1) { + // Toast.makeText(context, "Возможно вы правы", Toast.LENGTH_LONG) + // .show(); + } + }); + + ad.show(); + return true; + } + }); + + + lvMain.setOnItemClickListener(new OnItemClickListener() { + public void onItemClick(AdapterView parent, View view, + int position, long id) { + final String user = (String) ((Cursor) lvMain + .getItemAtPosition(position)).getString(0); + + Cursor cursor_name = loginDataBaseAdapter.getRSSbyName(user); + if (cursor_name.moveToFirst()) { + // определяем номера столбцов по имени в выборке + int idColIndex = cursor_name.getColumnIndex("mUrl"); + // получаем значения по номерам столбцов + String URL = cursor_name.getString(idColIndex); + // вызываем Intent, передавая URL + Intent intent = new Intent(rssFeeds.this, ViewActivity.class); + intent.putExtra("bbusername", bbusername); + intent.putExtra("bbuserid", bbuserid); + intent.putExtra("bbpassword", bbpassword); + intent.putExtra("jurl", jurl); + intent.putExtra("url", URL); + String numl = loginDataBaseAdapter.getNUMLOAD(bbusername); + if (!numl.equals("NOT EXIST")) + intent.putExtra("numload", numl); + else intent.putExtra("numload", "1000"); + String fastload = loginDataBaseAdapter.getFastLoad(bbusername); + intent.putExtra("fastload", fastload); + startActivity(intent); + } + cursor_name.close(); + // Toast.makeText( + // rssFeeds.this, + // "Single tap on item position " + position + " Selected Item:" + // + user, Toast.LENGTH_SHORT).show(); + + } + }); + + + } + + protected void onDestroy() { + // закрываем подключение при выходе + + // loginDataBaseAdapter.close(); + super.onDestroy(); + loginDataBaseAdapter.close(); + cursor_rep.close(); + } + + @Override + public boolean onCreateOptionsMenu(Menu menu) { + // Inflate the menu; this adds items to the action bar if it is present. + getMenuInflater().inflate(R.menu.main, menu); + + //menu.add(0, 1, 0, "addRssFeed"); + return true; + } + + public boolean onOptionsItemSelected(MenuItem item) { + // TODO Auto-generated method stub + // StringBuilder sb = new StringBuilder(); + + // Выведем в TextView информацию о нажатом пункте меню + // sb.append("Item Menu"); + // sb.append("\r\n groupId: " + String.valueOf(item.getGroupId())); + // sb.append("\r\n itemId: " + String.valueOf(item.getItemId())); + // sb.append("\r\n order: " + String.valueOf(item.getOrder())); + // sb.append("\r\n title: " + item.getTitle()); + // tv.setText(sb.toString()); + Toast.makeText(rssFeeds.this, "Menu title:" + item.getTitle().toString(), Toast.LENGTH_LONG).show(); + + if (item.getTitle().toString().equals(getString(R.string.menuAdd))) { + Intent intent = new Intent(rssFeeds.this, addSkill.class); + intent.putExtra("USER", bbusername); + startActivity(intent); + } + if (item.getTitle().toString().equals(getString(R.string.action_settings))) { + Intent intent = new Intent(rssFeeds.this, options.class); + intent.putExtra("USER", bbusername); + startActivity(intent); + } + if (item.getTitle().toString().equals(getString(R.string.reload))) { + //Intent intent = new Intent(rssFeeds.this, options.class); + //intent.putExtra("USER", bbusername); + //startActivity(intent); + + Handler h = new Handler() { + + @Override + public void handleMessage(Message msg) { + + if (msg.what != 1) { Toast.makeText(rssFeeds.this, "No internet connection. Try again.", Toast.LENGTH_LONG).show(); + + } else { new MyAsyncTask(rssFeeds.this).execute(jurl,bbuserid,bbpassword,bbusername); + + + } + + } + }; + + isNetworkAvailable(h,5000); + + + + + // cursor_rep = loginDataBaseAdapter.getRSSNames(bbusername); + // scAdapter.changeCursor(cursor_rep); + + // cursor_rep.close(); + + + // прочитать все + } + + + return super.onOptionsItemSelected(item); + } + + @Override + public void onSaveInstanceState(Bundle outState) { + super.onSaveInstanceState(outState); + + ((CustomApplication) getApplication()).detach(this); + } + + @Override + public void onRestoreInstanceState(Bundle savedInstanceState) { + super.onRestoreInstanceState(savedInstanceState); + + ((CustomApplication) getApplication()).attach(this); + } + + + +/* @Override + protected Dialog onCreateDialog(int dialogId){ + ProgressDialog progress = null; + switch (dialogId) { + case PROGRESS_DLG_ID: + progress = new ProgressDialog(this); + progress.setMessage("Loading..."); + + break; + } + return progress; + }*/ + + + +}