Enter Data in TextBox save and show in another Activity Using Intent - java

Hello I'm new to android programming. I would like to ask how can I pass data to another activity using intent? My case here is, I have a 2 TextBox , if the user clicks on the button it should be retrieved(the text) to the database.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sqlcon = new SQLController(this);
firstname_et = (EditText) findViewById(R.id.fistname_et_id);
lastname_et = (EditText) findViewById(R.id.lastname_et_id);
addmem_btn = (Button) findViewById(R.id.addmem_btn_id);
table_layout = (TableLayout) findViewById(R.id.tableLayout1);
BuildTable();
addmem_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
table_layout.removeAllViews();
String firstname = firstname_et.getText().toString();
String lastname = lastname_et.getText().toString();
firstname_et.setText("");
lastname_et.setText("");
// inserting data
sqlcon.open();
sqlcon.insertData(firstname, lastname);
BuildTable();
}
});
}
private void BuildTable() {
sqlcon.open();
Cursor c = sqlcon.readEntry();
int rows = c.getCount();
int cols = c.getColumnCount();
c.moveToFirst();
// outer for loop
for (int i = 0; i < rows; i++) {
TableRow row = new TableRow(this);
row.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT,
TableRow.LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 0; j < cols; j++) {
TextView tv = new TextView(this);
tv.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT,
TableRow.LayoutParams.WRAP_CONTENT));
tv.setBackgroundResource(R.drawable.abc_btn_borderless_material);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(0, 5, 0, 5);
tv.setText(c.getString(j));
row.addView(tv);
}
c.moveToNext();
table_layout.addView(row);
}
sqlcon.close();
}
SQLitecontroller.java
public SQLController(Context c) {
ourcontext = c;
}
public SQLController open() throws SQLException {
dbhelper = new DatabaseHelper(ourcontext);
database = dbhelper.getWritableDatabase();
return this;
}
public void close() {
dbhelper.close();
}
public void insertData(String name, String lname) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(DatabaseHelper.MEMBER_FIRSTNAME, name);
cv.put(DatabaseHelper.MEMBER_LASTNAME, lname);
database.insert(DatabaseHelper.TABLE_MEMBER, null, cv);
}
public Cursor readEntry() {
// TODO Auto-generated method stub
String[] allColumns = new String[] { DatabaseHelper.MEMBER_ID, DatabaseHelper.MEMBER_FIRSTNAME,
DatabaseHelper.MEMBER_LASTNAME };
Cursor c = database.query(DatabaseHelper.TABLE_MEMBER, allColumns, null, null, null,
null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String TABLE_MEMBER = "member";
public static final String MEMBER_ID = "_id";
public static final String MEMBER_FIRSTNAME = "firstname";
public static final String MEMBER_LASTNAME = "lastname";
// DATABASE INFORMATION
static final String DB_NAME = "MEMBER.DB";
static final int DB_VERSION = 1;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
public static final String CREATE_TABLE = "create table " + TABLE_MEMBER
+ "(" + MEMBER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
+ MEMBER_FIRSTNAME + " TEXT NOT NULL ," + MEMBER_LASTNAME
+ " TEXT NOT NULL);";
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MEMBER);
onCreate(db);
}
}
please help me.
i have try many time but error will generated so please help me.
show all data in TableView.

Related

can't get to show data from a database sqlite with a requirement JAVA ANDROID STUDIO

i can't get my data to show on my ListView. i created database handler with a query that says: "SELECT * FROM TABLE_NAME WHERE COLUMN_USERNAME = '"+Username+"'". i want to show Data that have the username i want only. But i cant seem to get it work. here is the code.
ViewEvent class with the List View
public class ViewEvent extends Activity {
private static String z = "";
private static final int _EDIT = 0, _DELETE = 1; // constants to be used later
static int longClickedItemIndex;
static List<Event> events = new ArrayList<Event>();
ArrayAdapter<Event> eventsAdapter;
ListView listViewEvents;
static DatabaseHandlerEvent helper;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_event);
Typeface myTypeFace = Typeface.createFromAsset(getAssets(), "Type Keys Filled.ttf");
TextView myTextview = (TextView) findViewById(R.id.textViewHead4);
myTextview.setTypeface(myTypeFace);
helper = new DatabaseHandlerEvent(getApplicationContext());
listViewEvents = (ListView) findViewById(R.id.listView);
registerForContextMenu(listViewEvents);
listViewEvents.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClickedItemIndex = position;
return false;
}
}
);
populateList();
SharedPreferences prfs = getSharedPreferences("AUTHENTICATION_FILE_NAME", Context.MODE_PRIVATE);
String Username = prfs.getString("Username", "");
if (helper.getEventCount() != 0 && events.size() == 0) {
events.addAll(helper.getAllEvent(Username));
}
}
public void registerForContextMenu(View view) {
view.setOnCreateContextMenuListener(this);
}
public void onButtonClick(View v){
if(v.getId() == R.id.bSignoutb){
Toast so = Toast.makeText(ViewEvent.this, "Signing out.. Redirecting to Login Page..." , Toast.LENGTH_SHORT);
so.show();
Intent i = new Intent(ViewEvent.this, MainActivity.class);
startActivity(i);
}
if(v.getId() == R.id.Bback){
Intent i = new Intent(ViewEvent.this, CreateEvent.class);
startActivity(i);
}
}
private void populateList() {
eventsAdapter = new eventListAdapter();
listViewEvents.setAdapter(eventsAdapter);
}
public class eventListAdapter extends ArrayAdapter<Event> {
public eventListAdapter() {
super(ViewEvent.this, R.layout.listview_event, events);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
view = getLayoutInflater().inflate(R.layout.listview_event, parent, false);
}
Event currentEvent = events.get(position);
TextView name = (TextView) view.findViewById(R.id.textViewEventName);
name.setText(currentEvent.getName());
TextView location = (TextView) view.findViewById(R.id.textViewLocation);
location.setText(currentEvent.getLocation());
TextView date = (TextView) view.findViewById(R.id.textViewDate);
date.setText(currentEvent.getDate());
TextView description = (TextView) view.findViewById(R.id.textViewDescription);
description.setText(currentEvent.getDescription());
TextView time = (TextView) view.findViewById(R.id.textViewTime);
time.setText(currentEvent.getTime());
TextView testnia = (TextView) view.findViewById(R.id.testnia);
testnia.setText(currentEvent.getUsername());
return view;
}
}
public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, view, menuInfo);
menu.setHeaderIcon(R.drawable.huhu);// find a suitable icon
menu.setHeaderTitle("Event options:");
menu.add(Menu.NONE, _EDIT, Menu.NONE, "Edit Event");
menu.add(Menu.NONE, _DELETE, Menu.NONE, "Delete Event");
}
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case _EDIT:
// editing a contact
Intent editContactIntent = new Intent(getApplicationContext(), EditEvent.class);
startActivityForResult(editContactIntent, 2); // reqcode=2
break;
case _DELETE:
helper.deleteEvent(events.get(longClickedItemIndex));
events.remove(longClickedItemIndex);
eventsAdapter.notifyDataSetChanged();
break;
}
return super.onContextItemSelected(item);
}
}
And this is my DataBaseHelperEvent class
public class DatabaseHandlerEvent extends SQLiteOpenHelper {
static DatabaseHelperUser helper;
Event event;
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "Events";
private static final String TABLE_NAME = "Events";
private static final String COLUMN_ID = "id",
COLUMN_NAME = "name", COLUMN_LOCATION = "location", COLUMN_DATE = "date",
COLUMN_TIME ="time", COLUMN_DESCRIPTION = "description", COLUMN_USERNAME = "username";
SQLiteDatabase db;
public DatabaseHandlerEvent(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
COLUMN_NAME + " TEXT, " + COLUMN_LOCATION + " TEXT, " +
COLUMN_DATE + " TEXT, " + COLUMN_TIME + " TEXT, " +
COLUMN_DESCRIPTION + " TEXT, " + COLUMN_USERNAME + " TEXT)"
);
}
public long createEvent (Event event) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, event.getName());
values.put(COLUMN_LOCATION, event.getLocation());
values.put(COLUMN_DATE, event.getDate());
values.put(COLUMN_TIME, event.getTime());
values.put(COLUMN_DESCRIPTION, event.getDescription());
values.put(COLUMN_USERNAME, event.getUsername());
long result = db.insert(TABLE_NAME, null, values);
db.close();
return result;
}
public int updateEvent(Event event) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLUMN_NAME, event.getName());
values.put(COLUMN_LOCATION, event.getLocation());
values.put(COLUMN_DATE, event.getDate());
values.put(COLUMN_TIME, event.getTime());
values.put(COLUMN_DESCRIPTION, event.getDescription());
int rowsAffected = db.update(TABLE_NAME, values, COLUMN_ID + "=?",
new String[]{String.valueOf(event.getId())});
db.close();
return rowsAffected;
}
public List<Event> getAllEvent(String Username) {
List<Event> events = new ArrayList<Event>();
db = this.getWritableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME +" WHERE "+COLUMN_USERNAME+" = "+ "'"+Username+"'", null);
if (cursor.moveToFirst()) {
do {
events.add(new Event(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(4),
cursor.getString(5), cursor.getString(6)));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return events;
}
public int getEventCount() {
db = this.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
int count = cursor.getCount();
cursor.close();
db.close();
return count;
}
public int deleteEvent(Event event) {
db = this.getWritableDatabase();
int rowsAffected = db.delete(TABLE_NAME, COLUMN_ID + "=?",
new String[]{String.valueOf(event.getId())});
db.close();
return rowsAffected;
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
String query = "DROP TABLE IF EXISTS "+TABLE_NAME;
db.execSQL(query);
this.onCreate(db);
}
}
So whenever i show my ListView, it will show nothing. How can i show the data that only have a specific username i want? thanks! Sorry for my bad english

Sum int value of column of database Android

I want to sum integer value of a column.
my code use to sum:
public int getTotal() {
// TODO Auto-generated method stub
int sum=0;
Cursor cursor = database.rawQuery("SELECT SUM(name) FROM "+dbHelper.getTableName(), null);
if(cursor.moveToFirst()) {
sum=cursor.getInt(0);
}
return sum;
}
other way that I tried:
public int sum() {
x=0;
for (int i =list.size(); i>0 ; i--) {
Log.e("sumprice","");
x = x +list.get(i).getName();
}
return x;
}
and DATABASE HELPER
public class DatabaseHelper extends SQLiteOpenHelper {
private final String TAG = "DatabaseHelper";
private static final String DATABASE_NAME = "db";
private static final String TABLE_NAME = "contacts";
private static final String COLUMN_ID = "_id";
private static final String COLUMN_NAME = "name";
private static final String COLUMN_VALUE = "value";
private static final String COLUMN_NUM = "num";
private static final String COLUMN_TYPE = "type";
private static final String COLUMN_CODE = "CODE";
public static final String COLUMN_ESME = "ESME";
private static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME + " (" +
COLUMN_ID + " INTEGER PRIMARY KEY," +
COLUMN_NAME + "INTEGER," +
COLUMN_VALUE + "INTEGER," +
COLUMN_NUM + " TEXT," +
COLUMN_TYPE + " TEXT," +
COLUMN_CODE + " TEXT," +
COLUMN_ESME + " TEXT" +
");";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null,8);
Log.i(TAG, "Object created.");
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(DatabaseHelper.class.getName(), "Upgrading database from version "
+ oldVersion + " to " + newVersion + ", which will destroy all old data");
db.execSQL("Drop table if exists " + TABLE_NAME);
onCreate(db);
}
public String getTableName() {
return TABLE_NAME;
}
public String getRowIdName() {
return COLUMN_ID;
}
}
DATABASE handler
public class DatabaseHandler {
private final String TAG = "DatabaseHandler";
static final String NAME = "name";
static final String VALUE = "value";
static final String NUM = "num";
static final String TYPE = " type";
static final String CODE = "code";
static final String ESME = "esme";
private DatabaseHelper dbHelper;
private SQLiteDatabase database;
public DatabaseHandler(Context context) {
dbHelper = new DatabaseHelper(context);
Log.i(TAG, "Object created.");
}
public void open() throws SQLException {
database = dbHelper.getWritableDatabase();
}
public void close() {
dbHelper.close();
}
public void insertContact(contac contacts) {
database = dbHelper.getWritableDatabase();
ContentValues cv = new ContentValues();
Log.e("D","1.1");
cv.put(NAME,contacts.getName());
cv.put(VALUE,contacts.getPhoneNumber());
cv.put(NUM,contacts.getNUM());
cv.put(TYPE,contacts.getTYPE());
cv.put(CODE,contacts.getCODE());
cv.put(ESME,contacts.getESME());
Log.e("D","1.2");
// Log.e("",cv);
database.insert(dbHelper.getTableName(), NAME, cv);
Log.e("","1.8");
Log.i(TAG, "Contact added successfully.");
Log.e("","1.9");
}
public void deleteContact(long id) {
database.delete(dbHelper.getTableName(), dbHelper.getRowIdName() + "=" + id, null);
}
public void updateContact(long id) {
ContentValues cv = new ContentValues();
cv.put(NAME, 3123123);
cv.put(VALUE, "12345");
cv.put(NUM, "123543");
cv.put(TYPE, "benzini");
cv.put(CODE, "123543");
cv.put(ESME, "benzini");
database.update(dbHelper.getTableName(), cv, dbHelper.getRowIdName() + "=" + id, null);
}
public List<contac> getAllContacts() {
SQLiteDatabase database = dbHelper.getWritableDatabase();
Log.e("D","1.9");
List<contac> contacts = new ArrayList<contac>();
Log.e("D","1.9");
Cursor cursor = database.query(dbHelper.getTableName(),null, null, null, null, null, null);
Log.e("D","1.9");
cursor.moveToFirst();
Log.e("D","1.9");
while (!cursor.isAfterLast()) {
Log.e("D","1.9");
contac contact= cursorTocontac(cursor);
Log.e("D","1.9");
contacts.add(contact);
Log.e("D","1.9");
cursor.moveToNext();
}
// Make sure to close the cursor
cursor.close();
return contacts;
}
private contac cursorTocontac(Cursor cursor) {
contac contacts = new contac(0, 0, 0, TAG, TAG, TAG, TAG);
Log.e("","2");
contacts.setId(cursor.getLong(0));
contacts.setName(cursor.getInt(1));
contacts.setPhoneNumber(cursor.getInt(2));
contacts.setNUM(cursor.getString(3));
contacts.setTYPE(cursor.getString(4));
contacts.setCODE(cursor.getString(5));
contacts.setESME(cursor.getString(6));
Log.e("","2.1");
return contacts;
}
public void clearTable() {
SQLiteDatabase database = dbHelper.getWritableDatabase();
database.delete(dbHelper.getTableName(), null, null);
// helper is object extends SQLiteOpenHelper
}
public long getNAMESum() {
database = dbHelper.getWritableDatabase();
Log.e("F","1.9");
long result = 0;
Log.e("F","1.9.1");
Cursor cur = database.rawQuery("SELECT SUM(COLUMN_NAME) FROM myTable", null);
Log.e("F","1.9.2");
if(cur.moveToFirst())
{
return cur.getInt(0);
}
cur.close();
return result;
}
public int getTotal() {
// TODO Auto-generated method stub
int sum=0;
Cursor cursor = database.rawQuery("SELECT SUM(name) FROM "+dbHelper.getTableName(), null);
if(cursor.moveToFirst()) {
sum=cursor.getInt(0);
}
return sum;
}
public void delete(String id)
{
database = dbHelper.getWritableDatabase();
database.delete(dbHelper.getTableName(), "_id=?", new String[]{id});
database.close();
}
}
List Adapter
public class ListAdapter extends ArrayAdapter<contac> {
private final String TAG = "*** ListAdapter ***";
Context context;
LayoutInflater myInflater;
List<contac> list;
CheckBox checkBox6;
int x;
public ListAdapter(Context context, int resource,
List<contac> list) {
super(context, resource, list);
this.context = context;
this.list = list;
myInflater = LayoutInflater.from(context);
this.context = context;
Log.i(TAG, "Adapter setuped successfully.");
}
public void setData(List<contac> list) {
this.list = list;
Log.i(TAG, "Data passed to the adapter.");
}
public void clear(List<contac> list) {
list.clear();
Log.i(TAG, "Data passed to the adapter.");
}
#Override
public int getCount() {
return list.size();
}
public void remove(contac contac) {
list.remove(contac);
updateList(list);
setData(list);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = myInflater.inflate(R.layout.list_adapter, null);
holder = new ViewHolder();
// holder.tvId = (TextView) convertView.findViewById(R.id.tvId);
holder.tvName = (TextView) convertView.findViewById(R.id.tvName);
holder.tvPhone = (TextView) convertView.findViewById(R.id.tvPhone);
holder.tvnum = (TextView) convertView.findViewById(R.id.tvnum);
holder.tvtype = (TextView) convertView.findViewById(R.id.tvtype);
holder.tvcode = (TextView) convertView.findViewById(R.id.tvcode);
holder.tvesme = (TextView) convertView.findViewById(R.id.tvesme);
holder.checkBox6 = (CheckBox)convertView.findViewById(R.id.checkBox6);
holder.checkBox6
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
contac element = (contac) holder.checkBox6.getTag();
element.setSelected(buttonView.isChecked());
}
});
convertView.setTag(holder);
holder.checkBox6.setTag(list.get(position));
} else {
holder = (ViewHolder) convertView.getTag();
((ViewHolder) convertView.getTag()).checkBox6.setTag(list.get(position));
}
// ViewHolder holder = (ViewHolder) convertView.getTag();
NumberFormat format = NumberFormat.getCurrencyInstance();
// holder.tvId.setTag(list.get(position).getIdInString());
// holder.tvId.setText(list.get(position).getIdInString());
holder.tvName.setText(format.format(list.get(position).getName()));
holder.tvPhone.setText(format.format(list.get(position).getPhoneNumber()));
holder.tvnum.setText(list.get(position).getNUM());
holder.tvtype.setText(list.get(position).getTYPE());
holder.tvcode.setText(list.get(position).getCODE());
holder.tvesme.setText(list.get(position).getESME());
holder.checkBox6.setChecked(list.get(position).isSelected());
return convertView;
}
static class ViewHolder {
// TextView tvId;
TextView tvName;
TextView tvPhone;
TextView tvnum;
TextView tvtype;
TextView tvcode;
TextView tvesme;
CheckBox checkBox6;
}
public int sum() {
x=0;
for (int i =list.size(); i>0 ; i--) {
Log.e("sumprice","");
x = x +list.get(i).getName();
}
return x;
}
public List<contac> getcontac() {
return list;
}
public void updateList(List<contac> list) {
this.list = list;
notifyDataSetChanged();
}
}
and my code to set in text view
int sum=dbHandler.getTotal();
txtsumprice = (TextView) view.findViewById(R.id.sumprice);
NumberFormat format = NumberFormat.getCurrencyInstance();
txtsumprice.setText(""+format.format(sum));
can solve my problem I very try to do it but not worked
you have an SQL syntax error (...myTotalFROM...):
Cursor cursor = database.rawQuery("SELECT Sum(name)myTotalFROM "+dbHelper.getTableName(), null);
should be:
Cursor cursor = database.rawQuery("SELECT Sum(name) AS myTotal FROM "+dbHelper.getTableName(), null);

Cant Find Database file in Eclipse for Android

I have been doing an android database application project recently.When i tried to execute. I cant find the folder 'databases' in the file explorer of the DDMS. I checked the following path /data/data/packagename/databases,but there i could not find databases folder and my database file.
I have attached the code for database helper class
please help me if there is any error that is preventing me from creating the database or is it wrong with my eclipse. Because even some of my existing projects also don't show up with the databases folder inside them.
DBclass.java:
package pack.andyxdb;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBclass {
public static final String KEY_TIMESTAMP = "Timestamp";
public static final String KEY_UNIQUEID = "UniqueID";
public static final String KEY_DEVICETYPE = "Devicetype";
public static final String KEY_RSSI = "RSSI";
private static final String DATABASE_NAME = "DannyZ.db";
private static final String DATABASE_TABLE = "Data";
private static final int DATABASE_VERSION = 1;
private final Context ourContext;
private DbHelper dbh;
private SQLiteDatabase odb;
private static final String USER_MASTER_CREATE =
"CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE+ "("
+ KEY_TIMESTAMP + " INTEGER ,"
+ KEY_UNIQUEID + " INTEGER, " + KEY_DEVICETYPE + " TEXT, " + KEY_RSSI + " INTEGER PRIMARY KEY )";
//CREATE TABLE `DannyZ` (
private static class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(USER_MASTER_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// if DATABASE VERSION changes
// Drop old tables and call super.onCreate()
}
}
public DBclass(Context c) {
ourContext = c;
dbh = new DbHelper(ourContext);
}
public DBclass open() throws SQLException {
odb = dbh.getWritableDatabase();
return this;
}
public void close() {
dbh.close();
}
public long insertrecord(int timestamp, int uniqueID,String Device, int RSSI) throws SQLException{
// Log.d("", col1);
// Log.d("", col2);
ContentValues IV = new ContentValues();
IV.put(KEY_TIMESTAMP, timestamp);
IV.put(KEY_UNIQUEID, uniqueID );
IV.put(KEY_DEVICETYPE, Device != "");
IV.put(KEY_RSSI, RSSI );
return odb.insert(DATABASE_TABLE, null, IV);
// returns a number >0 if inserting data is successful
}
public void updateRow(long rowID, String col1, String col2,String col3,String col4) {
ContentValues values = new ContentValues();
values.put(KEY_TIMESTAMP, col1);
values.put(KEY_UNIQUEID, col2);
values.put(KEY_DEVICETYPE, col3);
values.put(KEY_RSSI, col4);
try {
odb.update(DATABASE_TABLE, values, KEY_RSSI + "=" + rowID, null);
} catch (Exception e) {
}
}
public boolean delete() {
return odb.delete(DATABASE_TABLE, null, null) > 0;
}
public Cursor getAllTitles() {
// using simple SQL query
return odb.rawQuery("select * from " + DATABASE_TABLE + "ORDER BY "+KEY_RSSI, null);
}
public Cursor getallCols(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_TIMESTAMP,
KEY_UNIQUEID, KEY_DEVICETYPE, KEY_RSSI }, null, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
public Cursor getColsById(String id) throws SQLException {
Cursor mCursor = odb.query(DATABASE_TABLE, new String[] { KEY_TIMESTAMP,
KEY_UNIQUEID,KEY_DEVICETYPE }, KEY_RSSI + " = " + id, null, null, null, null);
Log.e("getallcols zmv", "opening successfull");
return mCursor;
}
}
also my MainActivity.java code is here. Here i try to insert the data into database by making use of submit button. When i hit submit button the app does not stay for long time and says unfortunately myapp has stopped.my curious concern has been is my database being created or not?
please do help me thanks
MainActivity:
public class MainActivity extends Activity {
private ListView list_lv;
private EditText txt1;
private EditText txt2;
private EditText txt3;
private EditText txt4;
private Button btn1;
private Button btn2;
private DBclass db;
private ArrayList<String> collist_1;
private ArrayList<String> collist_2;
private ArrayList<String> collist_3;
private ArrayList<String> collist_4;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
collist_1 = new ArrayList<String>();
collist_2 = new ArrayList<String>();
collist_3 = new ArrayList<String>();
collist_4 = new ArrayList<String>();
items();
// getData();
}
private void items() {
btn1 = (Button) findViewById(R.id.button1);
btn2 = (Button) findViewById(R.id.button2);
txt1 = (EditText) findViewById(R.id.editText1);
txt2 = (EditText) findViewById(R.id.editText2);
txt3 = (EditText) findViewById(R.id.editText3);
txt4 = (EditText) findViewById(R.id.editText4);
// list_lv = (ListView) findViewById(R.id.dblist);
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//getData();
viewData();
}
private void viewData() {
Intent i = new Intent(MainActivity.this, viewActivity.class);
startActivity(i);
}
});
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
submitData();
}
});
}
protected void submitData() {
int a = Integer.parseInt( txt1.getText().toString());
int b = Integer.parseInt( txt2.getText().toString());
String c = txt3.getText().toString();
int d = Integer.parseInt( txt4.getText().toString());
db = new DBclass(this);
long num = 0;
try {
db.open();
num = db.insertrecord(a, b,c,d);
db.close();
} catch (SQLException e) {
Toast.makeText(this, "Error Duplicate value"+e,2000).show();
} finally {
//getData();
}
if (num > 0)
Toast.makeText(this, "Row number: " + num, 2000).show();
else if (num == -1)
Toast.makeText(this, "Error Duplicate value", 4000).show();
else
Toast.makeText(this, "Error while inserting", 2000).show();
}
}
Create object of helper class in your activity onCreate method for creating the database file in android app
DBclass db=new DBclass(context);
Hope this will help.

Android Listview not updating after delete item

I am working with sqllite. I have successfully create a database and I can input some values in my database. I can also show all values in listview and also i can remove item by listview's onitemclicklistener.i have one problem. when i delete item listview not updated,but this item is deleted in database.how i can solve this problem ?
DatabaseHandler .java code
public class DatabaseHandler extends SQLiteOpenHelper {
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "lvstone_2";
private static final String TABLE_CONTACTS = "CardTable1";
private static final String KEY_ID = "id";
private static final String KEY_Tittle = "name";
private static final String KEY_Description = "description";
private static final String KEY_Price = "price";
private static final String KEY_Counter = "counter";
private static final String KEY_Image = "image";
private final ArrayList<Contact> contact_list = new ArrayList<Contact>();
public static SQLiteDatabase db;
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_Tittle + " TEXT,"
+ KEY_Description + " TEXT,"
+ KEY_Price + " TEXT,"
+ KEY_Counter + " TEXT,"
+ KEY_Image + " TEXT"
+ ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
// Adding new contact
public void Add_Contact(Contact contact) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
if (!somethingExists(contact.getTitle())) {
values.put(KEY_Tittle, contact.getTitle()); // Contact title
values.put(KEY_Description, contact.getDescription()); // Contact//
// description
values.put(KEY_Price, contact.getPrice()); // Contact price
values.put(KEY_Counter, contact.getCounter()); // Contact image
values.put(KEY_Image, contact.getImage()); // Contact image
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
Log.e("Table Result isss", String.valueOf(values));
db.close(); // Closing database connection
}
}
public void deleteUser(String userName)
{
db = this.getWritableDatabase();
try
{
db.delete(TABLE_CONTACTS, "name = ?", new String[] { userName });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
// Getting single contact
Contact Get_Contact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS,
new String[] { KEY_ID, KEY_Tittle, KEY_Description, KEY_Price,
KEY_Counter, KEY_Image }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(cursor.getString(0), cursor.getString(1),
cursor.getString(2), cursor.getString(4), cursor.getString(5));
// return contact
cursor.close();
db.close();
return contact;
}
public boolean somethingExists(String x) {
Cursor cursor = db.rawQuery("select * from " + TABLE_CONTACTS
+ " where name like '%" + x + "%'", null);
boolean exists = (cursor.getCount() > 0);
Log.e("Databaseeeeeeeee", String.valueOf(cursor));
cursor.close();
return exists;
}
public ArrayList<Contact> Get_Contacts() {
try {
contact_list.clear();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setTitle(cursor.getString(1));
contact.setDescription(cursor.getString(2));
contact.setPrice(cursor.getString(3));
contact.setCounter(cursor.getString(4));
contact.setImage(cursor.getString(5));
contact_list.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return contact_list;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
return contact_list;
}
public int getProfilesCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
int cnt = cursor.getCount();
cursor.close();
return cnt;
}
}
SQLAdapter.java code
public class StradaSQLAdapter extends BaseAdapter {
Activity activity;
int layoutResourceId;
Contact user;
ArrayList<Contact> data = new ArrayList<Contact>();
public ImageLoader imageLoader;
UserHolder holder = null;
public int itemSelected = 0;
public StradaSQLAdapter(Activity act, int layoutResourceId,
ArrayList<Contact> data) {
this.layoutResourceId = layoutResourceId;
this.activity = act;
this.data = data;
imageLoader = new ImageLoader(act.getApplicationContext());
notifyDataSetChanged();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
if (row == null) {
LayoutInflater inflater = LayoutInflater.from(activity);
holder = new UserHolder();
row = inflater.inflate(layoutResourceId, parent, false);
holder.Title = (TextView) row.findViewById(R.id.smalltitle1);
holder.counter = (TextView) row.findViewById(R.id.smallCounter1);
holder.dbcounter = (TextView) row
.findViewById(R.id.DBSliderCounter);
holder.Description = (TextView) row.findViewById(R.id.smallDesc1);
holder.layout = (RelativeLayout) row
.findViewById(R.id.DBSlideLayout);
holder.layoutmain = (RelativeLayout) row
.findViewById(R.id.DBSlideLayoutMain);
holder.Price = (TextView) row.findViewById(R.id.smallPrice1);
holder.pt = (ImageView) row.findViewById(R.id.smallthumb1);
holder.close = (ImageView) row.findViewById(R.id.DBSliderClose);
holder.c_minus = (ImageView) row.findViewById(R.id.counter_minus);
holder.c_plus = (ImageView) row.findViewById(R.id.counter_plus);
row.setTag(holder);
} else {
holder = (UserHolder) row.getTag();
}
user = data.get(position);
holder.Title.setText(user.getTitle());
holder.Description.setText(user.getDescription());
holder.Price.setText(user.getPrice() + " GEL");
holder.counter.setText(user.getCounter());
holder.dbcounter.setText(user.getCounter());
Log.e("image Url is........", data.get(position).toString());
imageLoader.DisplayImage(user.getImage(), holder.pt);
return row;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public class UserHolder {
public TextView Price, counter, Description, Title, dbcounter;
public ImageView pt,close,c_plus,c_minus;
public RelativeLayout layout, layoutmain;
}
}
and Main java code
public class StradaChartFragments extends Fragment {
public static ListView list;
ArrayList<Contact> contact_data = new ArrayList<Contact>();
StradaSQLAdapter cAdapter;
private DatabaseHandler dbHelper;
UserHolder holder;
private RelativeLayout.LayoutParams layoutParams;
private ArrayList<Contact> contact_array_from_db;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.strada_chart_fragment,
container, false);
dbHelper = new DatabaseHandler(getActivity());
list = (ListView) rootView.findViewById(R.id.chart_listview);
cAdapter = new StradaSQLAdapter(getActivity(),
R.layout.listview_row_db, contact_data);
contact_array_from_db = dbHelper.Get_Contacts();
Set_Referash_Data();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
holder = (UserHolder) view.getTag();
layoutParams = (RelativeLayout.LayoutParams) holder.layoutmain
.getLayoutParams();
if (holder.layout.getVisibility() != View.VISIBLE) {
ValueAnimator varl = ValueAnimator.ofInt(0, -170);
varl.setDuration(1000);
varl.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
layoutParams.setMargins(
(Integer) animation.getAnimatedValue(), 0,
0, 0);
holder.layoutmain.setLayoutParams(layoutParams);
}
});
varl.start();
holder.layout.setVisibility(View.VISIBLE);
}
holder.close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ValueAnimator var2 = ValueAnimator.ofInt(-170, 0);
var2.setDuration(1000);
var2.addUpdateListener(new AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(
ValueAnimator animation) {
dbHelper.deleteUser(contact_array_from_db.get(position).getTitle());
if (contact_data.size() > 0)
contact_data.remove(position);
layoutParams.setMargins(0, 0,
(Integer) animation.getAnimatedValue(),
0);
holder.layoutmain.setLayoutParams(layoutParams);
holder.layout.setVisibility(View.INVISIBLE);
}
});
var2.start();
}
});
}
});
return rootView;
}
public void Set_Referash_Data() {
contact_data.clear();
for (int i = 0; i < contact_array_from_db.size(); i++) {
String title = contact_array_from_db.get(i).getTitle();
String Description = contact_array_from_db.get(i).getDescription();
String Price = contact_array_from_db.get(i).getPrice();
String Counter = contact_array_from_db.get(i).getCounter();
String image = contact_array_from_db.get(i).getImage();
Contact cnt = new Contact();
cnt.setTitle(title);
cnt.setDescription(Description);
cnt.setPrice(Price);
cnt.setCounter(Counter);
cnt.setImage(image);
contact_data.add(cnt);
}
dbHelper.close();
list.setAdapter(cAdapter);
Log.e("Adapter issss ...", String.valueOf(cAdapter));
}
}
i can remove item in database ,but listview not updated . what am i doing wrong ? if anyone knows solution help me
thanks
Under your method dbHelper.deleteUser add this code:
contact_data.remove(position);
To function in addition to deleting it from the database also have to delete the array of objects that you sent to adapter.
EDIT:
Add one remove method in your adapter for you can remove object. Code:
Adapter:
public void removeObject (int position) {
this.data.remove(position);
}
Activity:
Change:
contact_data.remove(position);
to:
cAdapter.removeObject(position);
cAdapter.notifyDataSetChanged();
EDIT 2:
Just delete all the objects from ArrayList.
contact_data.clear();
or in your adapter
data.clear();

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