parse.com query to sqlite query - java

I am trying to develop a crossword puzzle with parse.com backend to sqlite backed. I have difficulty in converting the code.
Following code is the database table i had created.
public class puzzle extends SQLiteOpenHelper {
public static final String db_name = "crossword.db";
public static final String Table1_name = "puz";
public static final String Table2_name = "item";
public static final String Table3_name = "clue";
public puzzle(final Context context){
super(context, db_name, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS" + Table1_name + "hash INTEGER, title TEXT, author TEXT,copyright TEXT,height INTEGER ,width INTEGER");
db.execSQL("CREATE TABLE IF NOT EXISTS"+ Table2_name + "hash INTEGER, x INTEGER ,y INTEGER, cell position INTEGER , black BOOLEAN , letter TEXT");
db.execSQL("CREATE TABLE IF NOT EXISTS" + Table3_name + "hash INTEGER, x INTEGER ,y INTEGER, cellposition INTEGER, cluenumber INTEGER, position INTEGER,clue TEXT");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + Table1_name);
db.execSQL("DROP TABLE IF EXISTS" + Table2_name);
db.execSQL("DROP TABLE IF EXISTS" + Table3_name);
onCreate(db);
}
public boolean insertitem(int hash, int x, int y, int cellposition, boolean black, String letter) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues itemvalues = new ContentValues();
itemvalues.put("hash", hash);
itemvalues.put("X", x);
itemvalues.put("Y", y);
itemvalues.put("CellPosition", cellposition);
itemvalues.put("Black", black);
itemvalues.put("Letter", letter);
long itemresult = db.insert(Table2_name, null, itemvalues);
if (itemresult == -1)
return false;
else
return true;
}
public boolean isinsertpuz(int hash,String title,String author,String copyright,int height,int width)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues puzvalues = new ContentValues();
puzvalues.put("hash",hash);
puzvalues.put("Title",title);
puzvalues.put("author",author);
puzvalues.put("copyright",copyright);
puzvalues.put("Height",height);
puzvalues.put("Width",width);
long puzresult = db.insert(Table1_name, null, puzvalues);
if (puzresult == -1)
return false;
else
return true;
}
public boolean isinsertclue(int hash,int x,int y,int cellposition,int cluenumber,String clue)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cluevalues = new ContentValues();
cluevalues.put("hash",hash);
cluevalues.put("X",x);
cluevalues.put("Y",y);
cluevalues.put("Cellposition",cellposition);
cluevalues.put("Cluenumber",cluenumber);
cluevalues.put("Clue",clue);
long clueresult=db.insert(Table3_name,null,cluevalues);
if(clueresult==-1)
return false;
else
return true;
}
public Cursor getpuzdata()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor puzquery=db.rawQuery("select * from" +Table1_name,null);
return puzquery;
}}
I want the following code in sqlite: I tried but it's showing some errorr, kindly help me!.
public CustomAdapter(Context context, int screenWidth, final int width,int screenHeight, int height, int hash, TextView clueTextView, TextView titleTextView){
this.context = context;
this.width = width;
this.height = height;
this.screenHeight = screenHeight;
this.screenWidth = screenWidth;
activity = (Activity)context;
this.hash = hash;
this.clueTextView = clueTextView;
this.titleTextView = titleTextView;
clueNumber = 0;
//cell count
count = width*height;
//to store each cell view
view = new View[count];
//contains solution
letterChar = new char[count];
clueAcross = new HashMap<>();
clueDown = new HashMap<>();
Log.d("parseSize", String.valueOf(letterChar.length));
//fetch data saved locally
query = ParseQuery.getQuery("Item").fromLocalDatastore();
query.whereEqualTo("hash", hash);
query.orderByAscending("cellPosition");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if(e == null)
for (ParseObject parseObject : objects) {
if(parseObject.getString("letter").equals(""))
letterChar[parseObject.getInt("cellPosition")] = ' ';
else
letterChar[parseObject.getInt("cellPosition")] = parseObject.getString("letter").charAt(0);
}
ParseQuery.getQuery("Clue").fromLocalDatastore().whereEqualTo("hash", CustomAdapter.this.hash).orderByDescending("clueNumber").getFirstInBackground(new GetCallback<ParseObject>() {
#Override
public void done(ParseObject object, ParseException e) {
if(e == null)
clueSize = object.getInt("clueNumber");
Log.d("clueNumber", String.valueOf(clueSize));
}
});
ParseQuery.getQuery("Clue").fromLocalDatastore().whereEqualTo("hash", CustomAdapter.this.hash).orderByAscending("cellPosition").findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null)
for (ParseObject object : objects) {
//int pos = (object.getInt("y")*width)+object.getInt("x");
if(object.getString("position").equals("Hor"))
clueAcross.put(object.getInt("cellPosition"), object.getString("clue"));
else
clueDown.put(object.getInt("cellPosition"), object.getString("clue"));
Log.d("clue", object.getInt("cellPosition")+" "+object.getString("clue")+" "+object.getString("position"));
}
//will populate the griview
Game.gridView.setAdapter(Game.customAdapter);
//to adjust layout on keyboard up
activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
//dismiss progress dialog on UI thread
activity.runOnUiThread(new Runnable() {
#Override
public void run() {
Game.progress.dismiss();
}
});
}
});
}
});
//to fix clueNumber change on minimize and restore bug
if(clueNumber > clueSize)
clueNumber = 0;
}
#Override
public int getCount() {
return count;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
view[position] = convertView;
if(view[position] == null){
LayoutInflater layoutInflater = LayoutInflater.from(context);
view[position] = layoutInflater.inflate(R.layout.grid_cell, null);
view[position].setLayoutParams(new RelativeLayout.LayoutParams(screenWidth / width, screenHeight / height));
}
//to shade black on cells containing no letters
view[position].setBackgroundResource(R.drawable.shape);
TextView cellNumberTextView = (TextView)view[position].findViewById(R.id.cellNumber);
final EditText letter = (EditText)view[position].findViewById(R.id.letter);
/*letter.setCursorVisible(false);
letter.setClickable(false);
letter.setLongClickable(false);
letter.setFocusable(false);
letter.setSelected(false);
letter.setKeyListener(null);
letter.setBackgroundResource(android.R.color.transparent);*/
//letter.setText(Character.toString(letterChar[position]));
// cellNumberTextView.setTextSize(cellNumberTextView.getTextSize() / 1.5f);
//set clue number on cells
if(clueAcross.get(position) != null){
cellNumberTextView.setText(String.valueOf(clueNumber));
clueNumber++;
//to fix clueNumber change on minimize and restore bug
if(clueNumber > clueSize)
clueNumber = 0;
Log.d("clueNumber", position+" "+clueNumber+ " "+clueSize);
}
else if(clueDown.get(position) != null){
cellNumberTextView.setText(String.valueOf(clueNumber));
clueNumber++;
//to fix clueNumber change on minimize and restore bug
if(clueNumber > clueSize)
clueNumber = 0;
Log.d("clueNumber", position+" "+clueNumber+ " "+clueSize);
}
//to disable EditText operations on black cells
if(letterChar[position] == ' ') {
view[position].setBackgroundColor(Color.BLACK);
letter.setClickable(false);
letter.setLongClickable(false);
letter.setFocusable(false);
letter.setSelected(false);
letter.setKeyListener(null);
}else
view[position].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//update clues on view click
clueTextView.setText(getClueDown(position));
titleTextView.setText(getClueAcross(position));
//to open keyboard and focus on the letter to edit
letter.requestFocus();
letter.setCursorVisible(true);
((InputMethodManager)context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(letter, InputMethodManager.SHOW_IMPLICIT);
}
});
//update clues on letter click
letter.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
letter.setText("");
clueTextView.setText(getClueDown(position));
titleTextView.setText(getClueAcross(position));
}
}
});
//check value and change color of cell accordingly
letter.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//letter.setText(s.toString().toUpperCase());
if(s.toString().isEmpty())
return;
Log.d("letter", "input "+s.toString()+"position "+String.valueOf(position)+Character.toString(letterChar[position]));
if (s.toString().equals(Character.toString(letterChar[position]))) {
view[position].setBackgroundResource(R.drawable.correct);
focusNext(position);
}
else
view[position].setBackgroundResource(R.drawable.wrong);
}
#Override
public void afterTextChanged(Editable s) {
/* if(s.toString().isEmpty())
return;*/
//view[0].setBackgroundResource(R.drawable.correct);
}
});
return view[position];
}
//to focus next cell
public void focusNext(int position) {
for (int i = position; i < count; i++) {
if (letterChar[i+1] == ' ')
continue;
else {
EditText editText = (EditText) ((ViewGroup) view[i + 1]).getChildAt(0);
editText.requestFocus();
((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
return;
}
}
}
//get ACROSS clue based on position
public String getClueAcross(int position){
for(int i=position; i>=0; i--)
if(clueAcross.get(i) != null)
return "(across): "+clueAcross.get(i);
return "";
}
//get DOWN clue based on position
public String getClueDown(int position){
for(int i=position; i>=0; i-=width)
if(clueDown.get(i) != null)
return "(down): "+clueDown.get(i);
return "";
}
#Override
public Object getItem(int position) {
return view[position];
}
#Override
public long getItemId(int position) {
return position;
}
}
The following code is how i tried to change the code from parse.com to sqlite
public class CustomAdapter extends BaseAdapter {
int count, hash;
int width, height, screenWidth, screenHeight;
Activity activity;
Context context;
private static final String SELECTitem_SQL = "SELECT * FROM item";
private static final String SELECTpuz_SQL = "SELECT * FROM puz";
private static final String SELECTclue_SQL = "SELECT * FROM clue";
private SQLiteDatabase db,db1 ;
puzzle ca=new puzzle(context);
char[] letterChar;
HashMap<Integer, String> clueAcross, clueDown;
TextView clueTextView, titleTextView;
int clueNumber, clueSize;
View view[];
public CustomAdapter(Context context, int screenWidth, final int width,int screenHeight, int height, int hash, TextView clueTextView, TextView titleTextView) {
this.context = context;
this.width = width;
this.height = height;
this.screenHeight = screenHeight;
this.screenWidth = screenWidth;
activity = (Activity) context;
this.hash = hash;
this.clueTextView = clueTextView;
this.titleTextView = titleTextView;
clueNumber = 0;
letterChar = new char[100];
//cell count
count = width * height;
//to store each cell view
view = new View[count];
//contains solution
letterChar = new char[count];
clueAcross = new HashMap<>();
clueDown = new HashMap<>();
Log.d("parseSize", String.valueOf(letterChar.length));
Cursor c1=db.rawQuery(SELECTitem_SQL,null);
Cursor c2=db.rawQuery(SELECTclue_SQL,null);
c1.moveToFirst();
c2.moveToFirst();
db= openOrCreateDatabase("item", null);
db1=openOrCreateDatabase("clue",null);
String hashid=c1.getString(0);
String cluehash=c2.getString(0);
String cluenum=c2.getString(4);
String hashpos=c1.getString(3);
String hashletter=c1.getString(5);
String hashblack=c1.getString(4);
int id=hashid.length();
for(int i=0;i<id;i++)
{
if(hashletter== "")
{
letterChar[Integer.parseInt(hashpos)]=' ';
}
else
{
letterChar[Integer.parseInt(hashpos)]=hashletter.charAt(0);
}
}
}
#Override
public int getCount() {
return 0;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
return null;
}
}
This is my code to convert from parse to sqlite but when i build the project it stays still.

I'm not sure if this helps you but there is a sql syntax error in your code:
db.execSQL("CREATE TABLE IF NOT EXISTS " + Table1_name + " (hash INTEGER, title TEXT, author TEXT,copyright TEXT,height INTEGER ,width INTEGER)");
db.execSQL("CREATE TABLE IF NOT EXISTS "+ Table2_name + " (hash INTEGER, x INTEGER ,y INTEGER, cell position INTEGER , black BOOLEAN , letter TEXT)");
db.execSQL("CREATE TABLE IF NOT EXISTS " + Table3_name + " (hash INTEGER, x INTEGER ,y INTEGER, cellposition INTEGER, cluenumber INTEGER, position INTEGER,clue TEXT)");
you missed "(" before "hash",a space after "EXISTS" and ")" at the end of each statement

Related

pass data from one activity to another and save it

i have two activities, each one have a listview. The first one contain the data and i want the other one to be as a favorite list. Right now i can pass the data with intent but its not saving. it shows when i start the intent but when i exit the second activity and go back to it with a custom button nothing is saved in the listview. Please tell me what to do. here is my code
public class MainActivity extends AppCompatActivity {
DB_Sqlite dbSqlite;
ListView listView;
String fav_name;
long fav_id;
ArrayAdapter adapter;
ArrayList arrayList;
String[] number;
Button button;
StringResourcesHandling srh;
Cursor getAllDataInCurrentLocale,getDataInCurrentLocaleById;
SimpleCursorAdapter favourites_adapter,non_favourites_adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
SharedPreferences mPrefs = getPreferences(MODE_PRIVATE);
arrayList = new ArrayList<String>();
listView.setAdapter(adapter);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, cc.class);
startActivity(intent);
}
});
/* Show the resources for demo */
for (String s : StringResourcesHandling.getAllStringResourceNames()) {
Log.d("RESOURCEDATA", "String Resource Name = " + s +
"\n\tValue = " + StringResourcesHandling.getStringByName(this, s)
);
}
dbSqlite = new DB_Sqlite(this);
Cursor csr = dbSqlite.getAllDataInCurrentLocale(this);
DatabaseUtils.dumpCursor(csr);
csr.close();
}
#Override
protected void onDestroy() {
super.onDestroy();
getAllDataInCurrentLocale.close();
}
#Override
protected void onResume() {
super.onResume();
manageNonFavouritesListView();
}
private void manageNonFavouritesListView() {
getAllDataInCurrentLocale = dbSqlite.getAllDataInCurrentLocale(this);
if (non_favourites_adapter == null) {
non_favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
getAllDataInCurrentLocale,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView.setAdapter(non_favourites_adapter);
setListViewHandler(listView,false);
} else {
non_favourites_adapter.swapCursor(getAllDataInCurrentLocale);
}
}
private void setListViewHandler(ListView listView, boolean favourite_flag) {
if (!favourite_flag) {
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (i == 0) {
Intent intent = new Intent(MainActivity.this,tc.class);
startActivity(intent);
}
if (i == 1) {
Intent intent = new Intent(MainActivity.this,vc.class);
startActivity(intent);
}
}
});
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long l) {
if (position == 0) {
Intent intent = new Intent(MainActivity.this, cc.class);
intent.putExtra("EXTRAKEY_ID",l); // THIS ADDED
startActivity(intent);}
String name = getAllDataInCurrentLocale.getString(getAllDataInCurrentLocale.getColumnIndex(FAVOURITES_COL_NAME));
Toast.makeText(MainActivity.this, name+" Added To Favorite", Toast.LENGTH_SHORT).show();
return true;
}
});
}}
}
public class DB_Sqlite extends SQLiteOpenHelper {
public static final String BDname = "data.db";
public static final int DBVERSION = 1; /*<<<<< ADDED BUT NOT NEEDED */
public static final String TABLE_FAVOURITES = "mytable";
public static final String FAVOURITES_COL_ID = BaseColumns._ID; /*<<<< use the Android stock ID name*/
public static final String FAVOURITES_COL_NAME = "name";
public static final String FAVOURITES_COL_FAVOURITEFLAG = "favourite_flag"; /*<<<<< NEW COLUMN */
public DB_Sqlite(#Nullable Context context) {
super(context, BDname, null, DBVERSION /*<<<<< used constant above */);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_FAVOURITES + " (" +
FAVOURITES_COL_ID + " INTEGER PRIMARY KEY," + /*<<<<< AUTOINCREMENT NOT NEEDED AND IS INEFFICIENT */
FAVOURITES_COL_NAME + " TEXT, " +
FAVOURITES_COL_FAVOURITEFLAG + " INTEGER DEFAULT 0" + /*<<<<< COLUMN ADDED */
")");
/* CHANGES HERE BELOW loop adding all Resource names NOT VALUES */
ContentValues cv = new ContentValues();
for (String s: StringResourcesHandling.getAllStringResourceNames()) {
cv.clear();
cv.put(FAVOURITES_COL_NAME,s);
db.insert(TABLE_FAVOURITES,null,cv);
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_FAVOURITES);
onCreate(db);
}
public boolean insertData(String name){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(FAVOURITES_COL_NAME, name);
long result = db.insert(TABLE_FAVOURITES,null, contentValues);
if (result == -1)
return false;
else
return true;
}
public Cursor getFavouriteRows(boolean favourites) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_FAVOURITEFLAG + "=?";
String compare = "<1";
if (favourites) {
compare =">0";
}
return db.query(
TABLE_FAVOURITES,null,
FAVOURITES_COL_FAVOURITEFLAG + compare,
null,null,null,null
);
}
private int setFavourite(long id, boolean favourite_flag) {
SQLiteDatabase db = this.getWritableDatabase();
String whereclause = FAVOURITES_COL_ID + "=?";
String[] whereargs = new String[]{String.valueOf(id)};
ContentValues cv = new ContentValues();
cv.put(FAVOURITES_COL_FAVOURITEFLAG,favourite_flag);
return db.update(TABLE_FAVOURITES,cv,whereclause,whereargs);
}
public int setAsFavourite(long id) {
return setFavourite(id,true);
}
public int setAsNotFavourite(long id) {
return setFavourite(id, false);
}
/* Getting everything and make MatrixCursor VALUES from Resource names from Cursor with Resource names */
public Cursor getAllDataInCurrentLocale(Context context) {
SQLiteDatabase db = this.getWritableDatabase();
Cursor csr = db.query(TABLE_FAVOURITES,null,null,null,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
public Cursor getDataInCurrentLocaleById(Context context, long id) {
SQLiteDatabase db = this.getWritableDatabase();
String wherepart = FAVOURITES_COL_ID + "=?";
String[] args = new String[]{String.valueOf(id)};
Cursor csr = db.query(TABLE_FAVOURITES,null,wherepart,args,null,null,null);
if (csr.getCount() < 1) return csr;
MatrixCursor mxcsr = new MatrixCursor(csr.getColumnNames(),csr.getCount());
while (csr.moveToNext()) {
mxcsr.addRow(convertCursorRow(context,csr,new String[]{FAVOURITES_COL_NAME}));
}
csr.close();
return mxcsr;
}
/* This getting columns from Cursor into String array (no BLOB handleing)*/
private String[] convertCursorRow(Context context, Cursor csr, String[] columnsToConvert) {
String[] rv = new String[csr.getColumnCount()];
for (String s: csr.getColumnNames()) {
boolean converted = false;
for (String ctc: columnsToConvert) {
if (csr.getType(csr.getColumnIndex(s)) == Cursor.FIELD_TYPE_BLOB) {
//........ would have to handle BLOB here if needed (another question if needed)
}
if (ctc.equals(s)) {
rv[csr.getColumnIndex(s)] = StringResourcesHandling.getStringByName(context,csr.getString(csr.getColumnIndex(s)));
converted = true;
}
} if (!converted) {
rv[csr.getColumnIndex(s)] = csr.getString(csr.getColumnIndex(s));
}
}
return rv;
}
}
public class cc extends AppCompatActivity {
String fav_name;
long fav_id;
DB_Sqlite dbSqlite;
SimpleCursorAdapter favourites_adapter;
ListView listView1;
ArrayList<String> arrayList1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cc);
listView1 = (ListView) findViewById(R.id.list_view1);
arrayList1 = new ArrayList<String>();
fav_id = getIntent().getLongExtra("EXTRAKEY_ID", 0);
if (fav_id == 0) {
}
dbSqlite = new DB_Sqlite(this);
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this, fav_id);
if (cursor.moveToFirst()) {
fav_name = cursor.getString(cursor.getColumnIndex(FAVOURITES_COL_NAME));
manageNonFavouritesListView();
}
cursor.close();
}
private void manageNonFavouritesListView() {
Cursor cursor = dbSqlite.getDataInCurrentLocaleById(this,fav_id);
if (favourites_adapter == null) {
favourites_adapter = new SimpleCursorAdapter(
this,
R.layout.textview,
cursor,
new String[]{FAVOURITES_COL_NAME},
new int[]{R.id.textview10},
0
);
listView1.setAdapter(favourites_adapter);
setListViewHandler(listView1,true);
} else {
favourites_adapter.swapCursor(cursor);
}
}
private void setListViewHandler(ListView listView1, boolean b) {
listView1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (fav_id == 1) {
Intent intent = new Intent(cc.this, tc.class);
startActivity(intent);
}
if (fav_id == 2) {
Intent intent = new Intent(cc.this, vc.class);
startActivity(intent);
}
}
});
}
}
public class StringResourcesHandling {
private static final String[] allowedStringResourcePrefixes = new String[]{"db_"};
private static boolean loaded = false;
private static Field[] fields = R.string.class.getFields();
private static ArrayList<String> allowedStringResourceNames = new ArrayList<>();
private static void loadStringResources() {
if (loaded) return;
for (Field f: fields) {
if (isResourceNameAllowedPrefix(f.getName())) {
allowedStringResourceNames.add(f.getName());
}
}
loaded = true;
}
private static boolean isResourceNameAllowedPrefix(String resourceName) {
if (allowedStringResourcePrefixes.length < 1) return true;
for (String s: allowedStringResourcePrefixes) {
if (resourceName.substring(0,s.length()).equals(s)) return true;
}
return false;
}
public static String getStringByName(Context context, String name) {
String rv = "";
boolean nameFound = false;
if (!loaded) {
loadStringResources();
}
for (String s: allowedStringResourceNames) {
if (s.equals(name)) {
nameFound = true;
break;
}
}
if (!nameFound) return rv;
return context.getString(context.getResources().getIdentifier(name,"string",context.getPackageName()));
}
public static List<String> getAllStringResourceNames() {
if (!loaded) {
loadStringResources();
}
return allowedStringResourceNames;
}
}
note: i get the data in 1st listview from strings.xml
please help me thank u in advance
You can add a column say 'isFavourite' in your db table which has list vew data. When user mark listitem as favourite, save the change in db table . When user navigates to favourite list populate the list from. db table with favourite filter in select query.
I suggest using SharedPreferences. You stated that your value gets overwritten. That won't be the case if you create multiple keys.
Example:
Say you have an ArrayList of String you want to pass from ClassA to ClassB:
ClassA:
for (int i = 0; i < list.size(); i++) {
sharedPref.edit().putString("text" + i, "abcde").apply();
}
ClassB:
for (int i = 0; i < list.size(); i++) {
sharedPref.getString("text" + i, null);
}
If you have problems with the listsize, you can also pass the listsize to sharedpref and retrieve it again.

Inserting and fetching data into SQLite [duplicate]

This question already has answers here:
Unfortunately MyApp has stopped. How can I solve this?
(23 answers)
Closed 6 years ago.
I am having difficulty inserting data into my SQLite database. When I call my addData() method my app crashes. I call my addData method (which is in MainActivity) from my GameView class inside my onTouchEvent method. I need to insert my turns integer into the COLUMN_SCORES column in my database. Appreciate any help!
DatabaseHelper.java:
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "scores.db";
public static final String TABLE_NAME = "scores_table";
public static final String COLUMN_ID = "ID";
public static final String COLUMN_SCORE = "SCORE";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table " + TABLE_NAME +" (ID INTEGER PRIMARY KEY AUTOINCREMENT, SCORE INTEGER)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean insertData(String score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_SCORE, score);
long result = db.insert(TABLE_NAME, null, contentValues);
if(result == -1) {
return false;
}
else {
return true;
}
}
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from " + TABLE_NAME, null);
return res;
}
public boolean updateData(String id, String score) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COLUMN_ID, id);
contentValues.put(COLUMN_SCORE, score);
db.update(TABLE_NAME, contentValues, "ID = ?", new String[] { id });
return true;
}
public Integer deleteData(String id) {
SQLiteDatabase db = this.getWritableDatabase();
return db.delete(TABLE_NAME, "ID = ?", new String[] { id });
}
}
GameView.java:
public class GameView extends View {
int mcolumns = 5;
int mrows = 5;
private NetwalkGrid mGame = new NetwalkGrid(mcolumns, mrows);
private GestureDetector mGestureDetector;
Random rand = new Random();
int sizeSqX;
int sizeSqY;
int sizeSq;
public static int turns;
Paint bgPaint;
public GameView(Context context) {
super(context);
init();
}
private void init() {
bgPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
bgPaint.setStyle(Paint.Style.FILL);
bgPaint.setColor(0xff0000ff);
mGame.gridCopy();
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
int num = rand.nextInt(3) + 1;
for (int turns = 1; turns < num; turns++) {
mGame.rotateRight(col, row);
}
}
}
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.BLACK);
sizeSqX = getWidth() / mcolumns;
sizeSqY = getHeight() / mrows;
if (sizeSqX < sizeSqY) {
sizeSq = sizeSqX;
}
else {
sizeSq = sizeSqY;
}
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder);
//Bitmap s = BitmapFactory.decodeResource(getResources(), R.drawable.straight);
//Bitmap dl = BitmapFactory.decodeResource(getResources(), R.drawable.downleft);
int cellContent;
//square = get width / col
int square = 140;
for (int col = 0; col < mGame.getColumns(); col++) {
for (int row = 0; row < mGame.getRows(); row++) {
cellContent = mGame.getGridElem(col,row);
if (cellContent == 1) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down); // Image for down position
if (cellContent == 65 && mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.up_down_connected);
}
}
else if (cellContent == 2) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right); // Right position
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.left_right_connected);
}
}
else if (cellContent == 3) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down); // Down right position WORKS
if (mGame.checkWin()) {
b = BitmapFactory.decodeResource(getResources(), R.drawable.right_down_connected);
}
else {
b = BitmapFactory.decodeResource(getResources(), R.drawable.placeholder2); //
}
canvas.drawBitmap(b, null,new Rect(col * sizeSq, row * sizeSq,col*sizeSq+sizeSq, row*sizeSq+sizeSq), null);
//Paint paint = new Paint();
//paint.setColor(Color.WHITE);
// paint.setStyle(Paint.Style.FILL);
TextPaint tp = new TextPaint();
tp.setColor(Color.GREEN);
tp.setTextSize(70);
tp.setTypeface(Typeface.create("Courier", Typeface.BOLD));
canvas.drawText("Moves: " + String.valueOf(turns), 10, 1180, tp);
canvas.drawText("High score: ", 10, 1280, tp);
}
}
}
//SoundPoolPlayer sound = new SoundPoolPlayer(getContext());
#Override
public boolean onTouchEvent(MotionEvent event) {
//boolean eventConsumed = mGestureDetector.onTouchEvent(event);
//GameView mGameView = new GameView(getApplicationContext());
//if (eventConsumed) {
int x = (int) event.getX();
int y = (int) event.getY();
int column = getColTouched(event.getX());
int row = getRowTouched(event.getY());
try {
mGame.rotateRight(column, row);
System.out.println(mcolumns);
turns++;
MainActivity main = new MainActivity();
//main.setTurns();
main.addData();
//main.getData();
mGame.checkWin();
if (mGame.checkWin()) {
System.out.println("check win works");
invalidate();
//main.setTurns();
//main.AddData();
}
invalidate();
}
catch (ArrayIndexOutOfBoundsException err) {
System.out.println("User has pressed outside game grid - exception caught");
}
//sound.playShortResource(R.raw.click);
// sound.release();
return super.onTouchEvent(event);
}
public int getColTouched(float x) {
return (int) (x / sizeSq);
}
public int getRowTouched(float y) {
return (int) (y / sizeSq);
}
public int getCols() {
return mcolumns;
}
public void setColRow(int columns, int rows) {
this.mcolumns = columns;
this.mrows = rows;
}
public int getTurns() {
return turns;
}
}
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private GestureDetector mGestureDetector;
private ImageView imageView;
private RadioGroup radioGroup;
private int mcolumns;
private int mrows;
DatabaseHelper myDb;
String test = "test data";
int turns;
static Context appcon;
String highScore;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
appcon = this;
myDb = new DatabaseHelper(this);
}
public void runGame(View view){
Intent intent = new Intent(this, GameViewActivity.class);
startActivity(intent);
}
public void runInstructions(View view) {
Intent intent = new Intent(this, InstructionsActivity.class);
startActivity(intent);
}
public void setTurns() {
//GameView mGameView = new GameView(getApplicationContext());
this.turns = GameView.turns;
System.out.println("Turns: " + Integer.toString(turns));
}
public void addData() {
boolean isInserted = myDb.insertData(test);
if(isInserted == true) {
System.out.println("Data inserted");
}
else {
System.out.println("Data NOT inserted");
}
}
public void getData() {
Cursor res = myDb.getAllData();
StringBuffer buffer = new StringBuffer();
while(res.moveToNext()) {
buffer.append(res.getString(1));
}
System.out.println(buffer.toString());
}
}
In your onTouchEvent in the GameView class instead of creating a new instance of MainActivity, which I suspect is casuing the failiure, you could call the insertData method of the DatabaseHelper class directly. e.g. instead of using :-
MainActivity main = new MainActivity();
//main.setTurns();
main.addData();
//main.getData();
Try
DatabaseHelper mydb = new DatabaseHelper(this);
mydb.insertData("test");

How can I fix list Array with the cursor data in Android [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
Hi i creata an aplication on android using SQL. I have problem when I want to set cursor. I don't know what I did wrong, becouse is my first program using Array list with cursor. Thanks for help.
public class ThoughtManager {
private Thought thought;
private ThoughtDbHelper dbHelper;
private Cursor cursor;
private Context context;
SQLiteDatabase db;
private ContentValues contentValues;
private ArrayList<Thought> allThoughts;
int iTitle;
int iDetail;
int iTime;
int iDate;
int iReason;
int iComment;
private String[] columns=new String[]{ThoughtDbHelper.KEY,
ThoughtDbHelper.TITLE,
ThoughtDbHelper.DETAIL,
ThoughtDbHelper.TIME,
ThoughtDbHelper.DATE,
ThoughtDbHelper.REASON,
ThoughtDbHelper.COMMENT}; // Tablica wypisywanych elementow
public ThoughtManager(Context context)
{
this.context = context; // CO tu dokładnie robimy????
dbHelper=new ThoughtDbHelper(context);
contentValues=new ContentValues();
}
public ThoughtManager openForWrite() // Gdy chcemy zapisywac cos w bazie nowego
{
db=dbHelper.getWritableDatabase();
return this;
}
public ThoughtManager openForRead() // Gdy chcemy odczytywac dane z bazy
{
db=dbHelper.getReadableDatabase();
return this;
}
public void close()
{
dbHelper.close(); // Bezpieczne zamykanie aplikacji
}
public long createThought(Thought thought) // TWORZE NOWY ELEMENT W BAZIE DANYCH!!!
{
contentValues.put(ThoughtDbHelper.TITLE, thought.getTitle());
contentValues.put(ThoughtDbHelper.DETAIL, thought.getDetails());
contentValues.put(ThoughtDbHelper.TIME, thought.getTime());
contentValues.put(ThoughtDbHelper.DATE, thought.getDate());
contentValues.put(ThoughtDbHelper.REASON, thought.getReason());
contentValues.put(ThoughtDbHelper.COMMENT, thought.getComment());
return db.insert(ThoughtDbHelper.TABLE_NAME, null, contentValues);
}
public int updateThought(Thought thought) // Edytuje element W BAZIE DANYCH!!!
{
contentValues.put(ThoughtDbHelper.TITLE, thought.getTitle());
contentValues.put(ThoughtDbHelper.DETAIL, thought.getDetails());
contentValues.put(ThoughtDbHelper.TIME, thought.getTime());
contentValues.put(ThoughtDbHelper.DATE, thought.getDate());
contentValues.put(ThoughtDbHelper.REASON, thought.getReason());
contentValues.put(ThoughtDbHelper.COMMENT, thought.getComment());
return db.update(ThoughtDbHelper.TABLE_NAME, contentValues, ThoughtDbHelper.TITLE + "=" + thought.getTitle(), null);
}
public int deleteThought(Thought thought) // Usuwa element W BAZIE DANYCH!!!
{
return db.delete(ThoughtDbHelper.TABLE_NAME, ThoughtDbHelper.TITLE + "=" + thought.getTitle(), null);
}
public ArrayList<Thought> getAllThoughts() // Pobieramy wszystkie elementy do tablicy
{
//Cursor cursor=db.query(ThoughtDbHelper.TABLE_NAME, columns, null,null,null,null,null);
//cursor.moveToFirst();
cursor = db.query(ThoughtDbHelper.TABLE_NAME, new String[]{ThoughtDbHelper.KEY,
ThoughtDbHelper.TITLE,
ThoughtDbHelper.DETAIL,
ThoughtDbHelper.TIME,
ThoughtDbHelper.DATE,
ThoughtDbHelper.REASON,
ThoughtDbHelper.COMMENT}, (String)null, (String[])null, (String)null, (String)null, (String)null);
iTitle = cursor.getColumnIndex(ThoughtDbHelper.TITLE);
iDetail=cursor.getColumnIndex(ThoughtDbHelper.DETAIL);
iTime=cursor.getColumnIndex(ThoughtDbHelper.TIME);
iDate=cursor.getColumnIndex(ThoughtDbHelper.DATE);
iReason=cursor.getColumnIndex(ThoughtDbHelper.REASON);
iComment=cursor.getColumnIndex(ThoughtDbHelper.COMMENT);
// W petli wpisuje kolejno wszystkie dane do kolejnych tablic w zlaeznosic ile mamy elemetow
for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()) // (zacznij od poczatku ; rózny(!) od ostatniego ; idz co jeden
{
thought=new Thought(cursor.getString(iTitle), // pobieram tytul
cursor.getString(iDetail), // poberam opis
cursor.getString(iReason), // pobierma czas etc...
cursor.getString(iComment),
cursor.getString(iDate),
cursor.getString(iTime));
allThoughts.add(thought);
}
return allThoughts;
}
public Thought getThought(Thought thought)
{
cursor=db.query(ThoughtDbHelper.TABLE_NAME, columns, null, null, null, null, null);
iTitle=cursor.getColumnIndex(ThoughtDbHelper.TITLE);
iDetail=cursor.getColumnIndex(ThoughtDbHelper.DETAIL);
iTime=cursor.getColumnIndex(ThoughtDbHelper.TIME);
iDate=cursor.getColumnIndex(ThoughtDbHelper.DATE);
iReason=cursor.getColumnIndex(ThoughtDbHelper.REASON);
iComment=cursor.getColumnIndex(ThoughtDbHelper.COMMENT);
if(cursor!=null) // Jezeli mamy jakies dane
{
cursor.moveToFirst(); // przerzuc kursor do poczatku, by odczytywac dane od 1
thought=new Thought(cursor.getString(iTitle), // pobieram tytul
cursor.getString(iDetail), // posberam opis
cursor.getString(iReason), // pobierma czas etc...
cursor.getString(iComment),
cursor.getString(iDate),
cursor.getString(iTime));
allThoughts.add(thought);
}
return thought;
}
}
CatLog:
ThoughtDbHelper:
public class ThoughtDbHelper extends SQLiteOpenHelper{
//Zmienne do mojej bazy danych
static final String TITLE="title";
static final String DETAIL="detail";
static final String REASON="reason";
static final String COMMENT="comment";
static final String KEY="_id";
static final String DATE="date";
static final String TIME="time";
static final String TABLE_NAME="thought_tbl";
static final String DATABASE_NAME="thought_db.sql"; // nasza baza danych
static final int DATABASE_VERSION = 1; // wesja naszej bazy danych
private String QUERY_STRING="CREATE TABLE " + TABLE_NAME + " ( "+KEY
+ " INTEGER PRIMARY KEY AUTOINCREMENT , "+ TITLE
+ " TEXT NOT NULL, " + DETAIL + " TEXT NOT NULL , " + TIME
+ " TEXT, " + DATE + " TEXT, " + REASON + " TEXT, " + COMMENT
+ " TEXT )";
public ThoughtDbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(QUERY_STRING);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL("DROP TABLE IF EXIST"+TABLE_NAME);
onCreate(db);
}
}
View Thought: There I want to view my saved thought
public class ViewThought extends ListActivity {
ThoughtManager manager;
ArrayList<Thought> allThoughts;
ArrayList<String> allTitles;
ListView listView;
Thought thought;
String titlePosition;
Dialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.view_thought);
manager=new ThoughtManager(this);
allTitles = new ArrayList<String>();
listView = getListView();
//listView.setBackgroundResource();
listView.setPadding(10, 20, 10, 15);
listView.setFooterDividersEnabled(true);
listView.setHeaderDividersEnabled(true);
d
allThoughts = manager.getAllThoughts();
// Pobieram wszystkie zadania/notatki
for (Thought thought : allThoughts) // od d ostatniego elemetnu
{
allTitles.add(thought.getTitle());
}
listView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1 ,allTitles));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
/* titlePosition = allTitles.get(position);
//thought=manager.getThought(titlePosition);
dialog=new Dialog(ViewThought.this);
dialog.setContentView(R.layout.view_details);
// 1 sposob
//dialog.setTitle("Thought Detail view");
//2 sposob
TextView tvTime,tvDetail,tvReason,tvComment;
tvComment=(TextView) dialog.findViewById(R.id.tvViewComment);
tvDetail=(TextView) dialog.findViewById(R.id.tvViewDetails);
tvReason=(TextView) dialog.findViewById(R.id.tvViewReason);
tvTime=(TextView) dialog.findViewById(R.id.tvViewTime);
dialog.setTitle(thought.getTitle());
tvComment.setText(thought.getComment());
tvDetail.setText(thought.getDetails());
tvReason.setText(thought.getReason());
tvTime.setText("Created on"+thought.getDate()+"At "+thought.getTime());
dialog.show();
*/
}
}
Look here for a full walk-through.
You need to initialize your db, like:
SQLiteDatabase db = mDbHelper.getReadableDatabase();
before you can read anything from it.

Refreshing a ListView to reflect ArrayList population

I am running into an issue where my app crashes and I am given an error that reads
04-28 15:08:32.378: E/AndroidRuntime(27229): FATAL EXCEPTION: main
04-28 15:08:32.378: E/AndroidRuntime(27229): Process: com.example.datetracker, PID: 27229
04-28 15:08:32.378: E/AndroidRuntime(27229): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
04-28 15:08:32.378: E/AndroidRuntime(27229): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
I can successfully remove an item from the lstEvents arraylist and I can also remove the event object from the database, but I can't seem to have it disappear from the screen. No matter what I do it seems to keep refreshing the listview with the same contents.
What am I doing wrong? I keep getting this IndexOutOfBoundsException, and I am pretty sure it is because the view is not updating properly and it continues to allow me to swipe-to-dismiss which is in return trying to delete objects which eventually are not going to be there.
MainActivity
public class MainActivity extends FragmentActivity implements OnClickListener {
ListView listView;
int lastIndex = -1;
ArrayList<Event> lstEvents = new ArrayList<Event>();
ArrayList<Event> templstEvents = new ArrayList<Event>();
// detail view
TextView tvTitle, tvTime, tvDate;
ImageView ivPic;
View vw_master;
boolean _isBack = true;
ImageButton add;
String title;
String date;
String time;
int resId;
Context context;
static final int PICK_CONTACT_REQUEST = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// // get detail controls
tvTitle = (TextView) findViewById(R.id.textViewTitle);
tvDate = (TextView) findViewById(R.id.textViewDate);
tvTime = (TextView) findViewById(R.id.textViewTime);
ivPic = (ImageView) findViewById(R.id.imageView1);
add = (ImageButton) findViewById(R.id.add);
add.setOnClickListener(this);
// ///////////////////////////////LISTVIEW////////////////////////////////////////
// Create the adapter to convert the array to views
EventAdapter adapter = new EventAdapter(this, lstEvents);
// attach adapter to a list view
listView = (ListView) findViewById(R.id.listViewFragment);
listView.setAdapter(adapter);
context = this;
SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(
listView,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
EventAdapter adapter = new EventAdapter(context, lstEvents);
DatabaseHandler db = new DatabaseHandler(context);
#Override
public boolean canDismiss(int position) {
return true;
}
#Override
public void onDismiss(ListView listView,
int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
if (lstEvents.isEmpty()){
Log.e("EMPTYLIST","THELISTISEMPTY");
}
else
db.deleteEvent(lstEvents.get(position));
lstEvents.remove(position);
//adapter.remove(adapter.getItem(position));
}
adapter.notifyDataSetChanged();
}
});
listView.setOnTouchListener(touchListener);
// Setting this scroll listener is required to ensure that during
// ListView scrolling,
// we don't look for swipes.
listView.setOnScrollListener(touchListener.makeScrollListener());
// /////////////////////////////DATABASE/////////////////////////////////////////////
DatabaseHandler db = new DatabaseHandler(this);
// /////////////////////////////DATABASE/////////////////////////////////////////////
lstEvents = db.getAllContacts();
adapter.addAll(lstEvents);
adapter.notifyDataSetChanged();
}
// #Override
// protected void onResume() {
// // TODO Auto-generated method stub
// super.onResume();
// //
// /////////////////////////////DATABASE/////////////////////////////////////////////
// DatabaseHandler db = new DatabaseHandler(this);
// //
// /////////////////////////////DATABASE/////////////////////////////////////////////
//
// lstEvents = db.getAllContacts();
// EventAdapter adapter = new EventAdapter(this, lstEvents);
// adapter.addAll(lstEvents);
// adapter.notifyDataSetChanged();
// }
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.add:
Intent intent = new Intent(this, CreateActivity.class);
startActivityForResult(intent, 100);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// /////////////////////////////DATABASE/////////////////////////////////////////////
DatabaseHandler db = new DatabaseHandler(this);
// /////////////////////////////DATABASE/////////////////////////////////////////////
// Create the adapter to convert the array to views
EventAdapter adapter = new EventAdapter(this, lstEvents);
// attach adapter to a list view
listView = (ListView) findViewById(R.id.listViewFragment);
listView.setAdapter(adapter);
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
Bundle b = data.getExtras();
title = b.getString("TITLE");
time = b.getString("TIME");
date = b.getString("DATE");
Bitmap bitmap = b.getParcelable("BITMAP");
// ///CONVERTING A BITMAP TO A BYTE[]
byte[] image = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
image = bos.toByteArray();
// ///////
// /////////////////////////////DATABASE/////////////////////////////////////////////
/**
* CRUD OPERATIONS
*/
Log.e("Insert: ", "Inserting ..");
db.addEvent(new Event((int) Math.floor(Math.random() * 101),
title, time, date, image));
// Reading all contacts
Log.e("Reading: ", "Reading all contacts..");
lstEvents = db.getAllContacts();
adapter.addAll(lstEvents);
adapter.notifyDataSetChanged();
// logging all events
for (Event ev : lstEvents) {
String log = "Id: " + ev.get_Id() + " ,Title: "
+ ev.get_title() + " ,Date: " + ev.get_date()
+ " ,RESOURCEID: " + ev.get_image();
// Writing Contacts to log
Log.e("Name: ", log);
}
// /////////////////////////////DATABASE/////////////////////////////////////////////
}
}
}
}
SwipeDismissListViewTouchListener
public class SwipeDismissListViewTouchListener implements View.OnTouchListener {
// Cached ViewConfiguration and system-wide constant values
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
private ListView mListView;
private DismissCallbacks mCallbacks;
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
// Transient properties
private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>();
private int mDismissAnimationRefCount = 0;
private float mDownX;
private boolean mSwiping;
private VelocityTracker mVelocityTracker;
private int mDownPosition;
private View mDownView;
private boolean mPaused;
/**
* The callback interface used by {#link SwipeDismissListViewTouchListener} to inform its client
* about a successful dismissal of one or more list item positions.
*/
public interface DismissCallbacks {
/**
* Called to determine whether the given position can be dismissed.
*/
boolean canDismiss(int position);
/**
* Called when the user has indicated they she would like to dismiss one or more list item
* positions.
*
* #param listView The originating {#link ListView}.
* #param reverseSortedPositions An array of positions to dismiss, sorted in descending
* order for convenience.
*/
void onDismiss(ListView listView, int[] reverseSortedPositions);
}
/**
* Constructs a new swipe-to-dismiss touch listener for the given list view.
*
* #param listView The list view whose items should be dismissable.
* #param callbacks The callback to trigger when the user has indicated that she would like to
* dismiss one or more list items.
*/
public SwipeDismissListViewTouchListener(ListView listView, DismissCallbacks callbacks) {
ViewConfiguration vc = ViewConfiguration.get(listView.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mAnimationTime = listView.getContext().getResources().getInteger(
android.R.integer.config_shortAnimTime);
mListView = listView;
mCallbacks = callbacks;
}
/**
* Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures.
*
* #param enabled Whether or not to watch for gestures.
*/
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
/**
* Returns an {#link android.widget.AbsListView.OnScrollListener} to be added to the {#link
* ListView} using {#link ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener)}.
* If a scroll listener is already assigned, the caller should still pass scroll changes through
* to this listener. This will ensure that this {#link SwipeDismissListViewTouchListener} is
* paused during list view scrolling.</p>
*
* #see SwipeDismissListViewTouchListener
*/
public AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
};
}
/**
* Manually cause the item at the given position to be dismissed (trigger the dismiss
* animation).
*/
public void dismiss(int position) {
dismiss(getViewForPosition(position), position, true);
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (mViewWidth < 2) {
mViewWidth = mListView.getWidth();
}
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
if (mPaused) {
return false;
}
// TODO: ensure this is a finger, and set a flag
// Find the child view that was touched (perform a hit test)
Rect rect = new Rect();
int childCount = mListView.getChildCount();
int[] listViewCoords = new int[2];
mListView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child;
for (int i = 0; i < childCount; i++) {
child = mListView.getChildAt(i);
child.getHitRect(rect);
if (rect.contains(x, y)) {
mDownView = child;
break;
}
}
if (mDownView != null) {
mDownX = motionEvent.getRawX();
mDownPosition = mListView.getPositionForView(mDownView);
if (mCallbacks.canDismiss(mDownPosition)) {
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
} else {
mDownView = null;
}
}
view.onTouchEvent(motionEvent);
return true;
}
case MotionEvent.ACTION_UP: {
if (mVelocityTracker == null) {
break;
}
float deltaX = motionEvent.getRawX() - mDownX;
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = mVelocityTracker.getXVelocity();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
boolean dismiss = false;
boolean dismissRight = false;
if (Math.abs(deltaX) > mViewWidth / 2) {
dismiss = true;
dismissRight = deltaX > 0;
} else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
&& absVelocityY < absVelocityX) {
// dismiss only if flinging in the same direction as dragging
dismiss = (velocityX < 0) == (deltaX < 0);
dismissRight = mVelocityTracker.getXVelocity() > 0;
}
if (dismiss) {
// dismiss
dismiss(mDownView, mDownPosition, dismissRight);
} else {
// cancel
mDownView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
break;
}
case MotionEvent.ACTION_CANCEL: {
if (mVelocityTracker == null) {
break;
}
if (mDownView != null) {
// cancel
mDownView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
break;
}
case MotionEvent.ACTION_MOVE: {
if (mVelocityTracker == null || mPaused) {
break;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
if (Math.abs(deltaX) > mSlop) {
mSwiping = true;
mListView.requestDisallowInterceptTouchEvent(true);
// Cancel ListView's touch (un-highlighting the item)
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
(motionEvent.getActionIndex()
<< MotionEvent.ACTION_POINTER_INDEX_SHIFT));
mListView.onTouchEvent(cancelEvent);
cancelEvent.recycle();
}
if (mSwiping) {
mDownView.setTranslationX(deltaX);
mDownView.setAlpha(Math.max(0.15f, Math.min(1f,
1f - 2f * Math.abs(deltaX) / mViewWidth)));
return true;
}
break;
}
}
return false;
}
private void dismiss(final View view, final int position, boolean dismissRight) {
++mDismissAnimationRefCount;
if (view == null) {
// No view, shortcut to calling onDismiss to let it deal with adapter
// updates and all that.
mCallbacks.onDismiss(mListView, new int[] { position });
return;
}
view.animate()
.translationX(dismissRight ? mViewWidth : -mViewWidth)
.alpha(0)
.setDuration(mAnimationTime)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
performDismiss(view, position);
}
});
}
private View getViewForPosition(int position) {
int index = position
- (mListView.getFirstVisiblePosition() - mListView.getHeaderViewsCount());
return (index >= 0 && index < mListView.getChildCount())
? mListView.getChildAt(index)
: null;
}
class PendingDismissData implements Comparable<PendingDismissData> {
public int position;
public View view;
public PendingDismissData(int position, View view) {
this.position = position;
this.view = view;
}
#Override
public int compareTo(PendingDismissData other) {
// Sort by descending position
return other.position - position;
}
}
private void performDismiss(final View dismissView, final int dismissPosition) {
// Animate the dismissed list item to zero-height and fire the dismiss callback when
// all dismissed list item animations have completed. This triggers layout on each animation
// frame; in the future we may want to do something smarter and more performant.
final ViewGroup.LayoutParams lp = dismissView.getLayoutParams();
final int originalHeight = dismissView.getHeight();
ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);
animator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
--mDismissAnimationRefCount;
if (mDismissAnimationRefCount == 0) {
// No active animations, process all pending dismisses.
// Sort by descending position
Collections.sort(mPendingDismisses);
int[] dismissPositions = new int[mPendingDismisses.size()];
for (int i = mPendingDismisses.size() - 1; i >= 0; i--) {
dismissPositions[i] = mPendingDismisses.get(i).position;
}
mCallbacks.onDismiss(mListView, dismissPositions);
ViewGroup.LayoutParams lp;
for (PendingDismissData pendingDismiss : mPendingDismisses) {
// Reset view presentation
pendingDismiss.view.setAlpha(1f);
pendingDismiss.view.setTranslationX(0);
lp = pendingDismiss.view.getLayoutParams();
lp.height = originalHeight;
pendingDismiss.view.setLayoutParams(lp);
}
mPendingDismisses.clear();
}
}
});
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
lp.height = (Integer) valueAnimator.getAnimatedValue();
dismissView.setLayoutParams(lp);
}
});
mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
animator.start();
}
}
DatabaseHandler
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "scheduleManager";
// Contacts table name
private static final String TABLE_EVENTS = "events";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_TIME = "time";
private static final String KEY_DATE = "date";
private static final String KEY_IMAGE = "image";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE_EVENTS + "("
+ KEY_ID + " INTEGER," + KEY_TITLE + " TEXT,"
+ KEY_TIME + " TEXT," + KEY_DATE + " TEXT," + KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_EVENTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
//adding an event (NEEDS TO ADD DRAWABLE)
public void addEvent(Event event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, event.get_Id()); //Event ID
values.put(KEY_TITLE, event.get_title()); // Event Title
values.put(KEY_TIME, event.get_time()); // Event Time
values.put(KEY_DATE, event.get_date()); // Event Date
values.put(KEY_IMAGE, event.get_image()); // Event RESOURCEID
// Inserting Row
db.insert(TABLE_EVENTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
public Event getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_EVENTS, new String[] { KEY_ID,
KEY_TITLE, KEY_TIME, KEY_DATE, KEY_IMAGE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Event event = new Event(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getBlob(4));
// return contact
return event;
}
// Getting All Contacts
public ArrayList<Event> getAllContacts() {
ArrayList<Event> eventList = new ArrayList<Event>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_EVENTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Event event = new Event();
event.set_Id(Integer.parseInt(cursor.getString(0)));
event.set_title(cursor.getString(1));
event.set_time(cursor.getString(2));
event.set_date(cursor.getString(3));
event.set_image(cursor.getBlob(4));
eventList.add(event);
} while (cursor.moveToNext());
}
// return contact list
return eventList;
}
// Getting event Count
public int getEventsCount() {
String countQuery = "SELECT * FROM " + TABLE_EVENTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public int updateEvent(Event event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, event.get_title());
values.put(KEY_TIME, event.get_time());
values.put(KEY_DATE, event.get_date());
// updating row
return db.update(TABLE_EVENTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(event.get_Id()) });
}
// Deleting single contact
public void deleteEvent(Event event) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_EVENTS, KEY_ID + " = ?",
new String[] { String.valueOf(event.get_Id()) });
db.close();
}
}
EventAdapter
public class EventAdapter extends ArrayAdapter<Event> {
// View lookup cache
private static class ViewHolder {
//adding drawable to imageview
ImageView img;
TextView title;
TextView time;
TextView date;
}
public EventAdapter(Context context, ArrayList<Event> objects) {
super(context, R.layout.date_detail);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Event event = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.date_detail, null);
viewHolder.title = (TextView) convertView
.findViewById(R.id.textViewTitle);
viewHolder.time = (TextView) convertView
.findViewById(R.id.textViewTime);
viewHolder.date = (TextView) convertView
.findViewById(R.id.textViewDate);
//adding drawable to imageview
viewHolder.img = (ImageView) convertView
.findViewById(R.id.imageView1);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.title.setText(event._title);
viewHolder.time.setText(event._time);
viewHolder.date.setText(event._date);
//convert from byte array to bitmap
Bitmap bitmap = convertByteArrayToBitmap(event._image);
// CONVERT BITMAP TO DRAWABLE
viewHolder.img.setImageBitmap(bitmap);
// Return the completed view to render on screen
return convertView;
}
public static Bitmap convertByteArrayToBitmap(
byte[] byteArrayToBeCOnvertedIntoBitMap)
{
Bitmap bitmap = BitmapFactory.decodeByteArray(
byteArrayToBeCOnvertedIntoBitMap, 0,
byteArrayToBeCOnvertedIntoBitMap.length);
return bitmap;
}
}
You are trying to remove the first item from an empty list. It says so in the exception text.
The problem was solved by removing the following lines of code in the swipeDismissViewListener and the OnActivityResult.
DatabaseHandler db = new DatabaseHandler(context);
EventAdapter adapter = new EventAdapter(context, db.getAllContacts());

Order of list items populated from SQLLite DB is incorrect

I have a SQLLite DB that stores an ftp site's login information (name,address,username,password,port,passive). When an item (site) is clicked in the list, it's supposed to load the name, address, username, password etc. into the corresponding EditTexts. What's happening is that the password value is getting loaded into the address EditText and the address isn't getting loaded anywhere.
My Activity's addRecord function looks like this:
public void addRecord() {
long newId = myDb.insertRow(_name, _address, _username, _password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
The order of the parameters in insertRow() correspond to the order in my DBAdapter, however when I change the order of the parameters I can get the address and password values to end up in the correct EditTexts, just never all of them at once. What am I doing wrong?
public class DBAdapter {
// ///////////////////////////////////////////////////////////////////
// Constants & Data
// ///////////////////////////////////////////////////////////////////
// For logging:
private static final String TAG = "DBAdapter";
// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
/*
* CHANGE 1:
*/
// TODO: Setup your fields here:
public static final String KEY_NAME = "name";
public static final String KEY_ADDRESS = "address";
public static final String KEY_USERNAME = "username";
public static final String KEY_PASSWORD = "password";
public static final String KEY_PORT = "port";
public static final String KEY_PASSIVE = "passive";
// TODO: Setup your field numbers here (0 = KEY_ROWID, 1=...)
public static final int COL_NAME = 1;
public static final int COL_ADDRESS = 2;
public static final int COL_USERNAME = 3;
public static final int COL_PASSWORD = 4;
public static final int COL_PORT = 5;
public static final int COL_PASSIVE = 6;
public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_NAME,
KEY_ADDRESS, KEY_USERNAME, KEY_PASSWORD, KEY_PORT, KEY_PASSIVE };
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "Sites";
public static final String DATABASE_TABLE = "SiteTable";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE_SQL = "create table "
+ DATABASE_TABLE
+ " ("
+ KEY_ROWID
+ " integer primary key autoincrement, "
/*
* CHANGE 2:
*/
// TODO: Place your fields here!
// + KEY_{...} + " {type} not null"
// - Key is the column name you created above.
// - {type} is one of: text, integer, real, blob
// (http://www.sqlite.org/datatype3.html)
// - "not null" means it is a required field (must be given a
// value).
// NOTE: All must be comma separated (end of line!) Last one must
// have NO comma!!
+ KEY_NAME + " string not null, " + KEY_ADDRESS
+ " string not null, " + KEY_USERNAME + " string not null, "
+ KEY_PASSWORD + " string not null, " + KEY_PORT
+ " integer not null," + KEY_PASSIVE + " integer not null"
// Rest of creation:
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
// ///////////////////////////////////////////////////////////////////
// Public methods:
// ///////////////////////////////////////////////////////////////////
public DBAdapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBAdapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Add a new set of values to the database.
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
/*
* CHANGE 3:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, name);
initialValues.put(KEY_ADDRESS, address);
initialValues.put(KEY_USERNAME, user);
initialValues.put(KEY_PASSWORD, pass);
initialValues.put(KEY_PORT, port);
initialValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}
// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}
public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
// Change an existing row to be equal to new data.
public boolean updateRow(long rowId, String name, String address,
String username, String password, int port, int passive) {
String where = KEY_ROWID + "=" + rowId;
/*
* CHANGE 4:
*/
// TODO: Update data in the row with new fields.
// TODO: Also change the function's arguments to be what you need!
// Create row's data:
ContentValues newValues = new ContentValues();
newValues.put(KEY_NAME, name);
newValues.put(KEY_ADDRESS, address);
newValues.put(KEY_USERNAME, username);
newValues.put(KEY_PASSWORD, password);
newValues.put(KEY_PORT, port);
newValues.put(KEY_PASSIVE, passive);
// Insert it into the database.
return db.update(DATABASE_TABLE, newValues, where, null) != 0;
}
// ///////////////////////////////////////////////////////////////////
// Private Helper Classes:
// ///////////////////////////////////////////////////////////////////
/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version "
+ oldVersion + " to " + newVersion
+ ", which will destroy all old data!");
// Destroy old database:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(_db);
}
}
}
public class SiteManager extends Activity {
DBAdapter myDb;
public FTPClient mFTPClient = null;
public EditText etSitename;
public EditText etAddress;
public EditText etUsername;
public EditText etPassword;
public EditText etPort;
public CheckBox cbPassive;
public ListView site_list;
public Button clr;
public Button test;
public Button savesite;
public Button close;
public Button connect;
String _name;
String _address;
String _username;
String _password;
int _port;
int _passive = 0;
List<FTPSite> model = new ArrayList<FTPSite>();
ArrayAdapter<FTPSite> adapter;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.site_manager);
site_list = (ListView) findViewById(R.id.siteList);
adapter = new SiteAdapter(this, R.id.ftpsitename, R.layout.siterow,
model);
site_list.setAdapter(adapter);
etSitename = (EditText) findViewById(R.id.dialogsitename);
etAddress = (EditText) findViewById(R.id.dialogaddress);
etUsername = (EditText) findViewById(R.id.dialogusername);
etPassword = (EditText) findViewById(R.id.dialogpassword);
etPort = (EditText) findViewById(R.id.dialogport);
cbPassive = (CheckBox) findViewById(R.id.dialogpassive);
close = (Button) findViewById(R.id.closeBtn);
connect = (Button) findViewById(R.id.connectBtn);
clr = (Button) findViewById(R.id.clrBtn);
test = (Button) findViewById(R.id.testBtn);
savesite = (Button) findViewById(R.id.saveSite);
addListeners();
openDb();
displayRecords();
}
public void addListeners() {
connect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent returnResult = new Intent();
returnResult.putExtra("ftpname", _name);
returnResult.putExtra("ftpaddress", _address);
returnResult.putExtra("ftpusername", _username);
returnResult.putExtra("ftppassword", _password);
returnResult.putExtra("ftpport", _port);
setResult(RESULT_OK, returnResult);
finish();
}
});
test.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
boolean status = ftpConnect(_address, _username, _password,
_port);
ftpDisconnect();
if (status == true) {
Toast.makeText(SiteManager.this, "Connection Succesful",
Toast.LENGTH_LONG).show();
savesite.setVisibility(0);
} else {
Toast.makeText(SiteManager.this,
"Connection Failed:" + status, Toast.LENGTH_LONG)
.show();
}
}
});
savesite.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
_name = etSitename.getText().toString();
_address = etAddress.getText().toString();
_username = etUsername.getText().toString();
_password = etPassword.getText().toString();
_port = Integer.parseInt(etPort.getText().toString());
if (cbPassive.isChecked()) {
_passive = 1;
} else {
_passive = 0;
}
addRecord();
adapter.notifyDataSetChanged();
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
clr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
clearAll();
}
});
site_list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
final FTPSite item = (FTPSite) parent
.getItemAtPosition(position);
String tmpname = item.getName();
String tmpaddress = item.getAddress();
String tmpuser = item.getUsername();
String tmppass = item.getPassword();
int tmpport = item.getPort();
String tmp_port = Integer.toString(tmpport);
int tmppassive = item.isPassive();
etSitename.setText(tmpname);
etAddress.setText(tmpaddress);
etUsername.setText(tmpuser);
etPassword.setText(tmppass);
etPort.setText(tmp_port);
if (tmppassive == 1) {
cbPassive.setChecked(true);
} else {
cbPassive.setChecked(false);
}
}
});
}
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
private void openDb() {
myDb = new DBAdapter(this);
myDb.open();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
closeDb();
}
private void closeDb() {
myDb.close();
}
public void displayRecords() {
Cursor cursor = myDb.getAllRows();
displayRecordSet(cursor);
}
protected void displayRecordSet(Cursor c) {
// String msg = "";
if (c.moveToFirst()) {
do {
// int id = c.getInt(0);
_name = c.getString(1);
_address = c.getString(2);
_username = c.getString(3);
_password = c.getString(4);
_port = c.getInt(5);
FTPSite sitesFromDB = new FTPSite();
sitesFromDB.setName(_name);
sitesFromDB.setAddress(_address);
sitesFromDB.setUsername(_username);
sitesFromDB.setAddress(_password);
sitesFromDB.setPort(_port);
sitesFromDB.setPassive(_passive);
model.add(sitesFromDB);
adapter.notifyDataSetChanged();
} while (c.moveToNext());
}
c.close();
}
public void clearAll() {
myDb.deleteAll();
adapter.notifyDataSetChanged();
}
public boolean ftpConnect(String host, String username, String password,
int port) {
try {
mFTPClient = new FTPClient();
// connecting to the host
mFTPClient.connect(host, port);
// now check the reply code, if positive mean connection success
if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) {
// login using username & password
boolean status = mFTPClient.login(username, password);
mFTPClient.enterLocalPassiveMode();
return status;
}
} catch (Exception e) {
// Log.d(TAG, "Error: could not connect to host " + host );
}
return false;
}
public boolean ftpDisconnect() {
try {
mFTPClient.logout();
mFTPClient.disconnect();
return true;
} catch (Exception e) {
// Log.d(TAG,
// "Error occurred while disconnecting from ftp server.");
}
return false;
}
class SiteAdapter extends ArrayAdapter<FTPSite> {
private final List<FTPSite> objects;
private final Context context;
public SiteAdapter(Context context, int resource,
int textViewResourceId, List<FTPSite> objects) {
super(context, R.id.ftpsitename, R.layout.siterow, objects);
this.context = context;
this.objects = objects;
}
/** #return The number of items in the */
public int getCount() {
return objects.size();
}
public boolean areAllItemsSelectable() {
return false;
}
/** Use the array index as a unique id. */
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.siterow, parent, false);
TextView textView = (TextView) rowView
.findViewById(R.id.ftpsitename);
textView.setText(objects.get(position).getName());
return (rowView);
}
}
I think you should try to use :
int keyNameIndex = c.getColumnIndex(DBAdapter.KEY_NAME);
_name = c.getString(keyNameIndex);
Instead of using direct number.I am not sure it cause the bug, but it gonna be better exercise. Hope it's help.
There is mismatch in your arguments see below
public long insertRow(String name, String address, String user,
String pass, int port, int passive) {
public void addRecord() {
long newId = myDb.insertRow(_name, _username, _address,_password,
_port, _passive);
Cursor cursor = myDb.getRow(newId);
displayRecordSet(cursor);
}
you are passing username to address and address to user
This is embarrassing. I had sitesFromDB.setAddress(_password); instead of sitesFromDB.setPassword(_password);

Categories

Resources