I have 2 tables: subject and notes table. I want to listview the notes that have the same subject name chosen.
First is a listview of all the subject(View_Subj) then when clicked it goes to a listview of the notes of the subject, and the add button inserts the notes to a subject
my View_Subj.java is:
public class View_Subj extends ListActivity {
private final String SAMPLE_DB_NAME = "project";
private final String SAMPLE_TABLE_NAME = "subject";
SQLiteDatabase sampleDB = null;
ArrayList<String> results = new ArrayList<String>();
/** Called when the activity is first created. */
public void onListItemClick(ListView l, View view, final int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, view, position, id);
Intent in = new Intent (View_Subj.this,View_PPT_List.class);
String subj = (l.getItemAtPosition(position)).toString();
Toast.makeText(getApplicationContext(), subj, Toast.LENGTH_SHORT).show();
in.putExtra("com.example.tinio_bolasa_project.sub1", subj);
startActivity(in);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
sampleDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
//name, mode MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE, factory
/*sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
SAMPLE_TABLE_NAME +
" (LastName VARCHAR, FirstName VARCHAR," +
" City VARCHAR, Age INT(3));");*/
Cursor c = sampleDB.rawQuery("SELECT * FROM " +
SAMPLE_TABLE_NAME, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String subid =
c.getString(c.getColumnIndex("subj_ID"));
String subject =
c.getString(c.getColumnIndex("subjName"));
results.add(subid + subject);
}while (c.moveToNext());
}
}
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,results));
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (sampleDB != null)
//sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME);
sampleDB.close();
}
}
}
my View_PPT_List.java:
public class View_PPT_List extends ListActivity {
private final String SAMPLE_DB_NAME = "project";
private final String PPT_TABLE_NAME1 = "notes";
private final String PPT_TABLE_NAME2 = "subject";
SQLiteDatabase notesDB = null;
ArrayList<String> results = new ArrayList<String>();
public void onListItemClick(ListView l, View view, final int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, view, position, id);
Intent ins = new Intent (View_PPT_List.this,PPTActivity.class);
String s = (l.getItemAtPosition(position)).toString();
ins.putExtra("com.example.tinio_bolasa_project.finame", s);
// ins.putExtra("Entries", l.getItemAtPosition(position).toString());
Toast.makeText(getApplicationContext(),s ,Toast.LENGTH_SHORT ).show();
startActivity(ins);
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String name = getSublabel();
try{
notesDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
notesDB.execSQL("CREATE TABLE IF NOT EXISTS " +
PPT_TABLE_NAME1 +
" ( notes_ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
"subjLabel VARCHAR, " + "pptName VARCHAR, " + "pptPath VARCHAR);");
// int x1 = getIntent().getExtras().getInt("Entries");
Cursor c = notesDB.rawQuery("SELECT * FROM notes WHERE subjLabel='"+name+"'",
null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String ppt = c.getString(c.getColumnIndex("pptName"));
results.add(ppt);
}while (c.moveToNext());
}
}
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,results));
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
if (notesDB != null)
//sampleDB.execSQL("DELETE FROM " + SAMPLE_TABLE_NAME);
notesDB.close();
}
setContentView(R.layout.activity_view__ppt__list);
Button addppt = (Button) this.findViewById(R.id.button1);
addppt.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent inten = new Intent (View_PPT_List.this,
Add_PPT_Activity.class);
startActivity(inten);
}
});
}
public String getSublabel(){
String sublabel =
getIntent().getStringExtra("com.example.tinio_bolasa_project.finame");
return sublabel;
}
}
And my Add_PPT_Activity:
public class Add_PPT_Activity extends ListActivity {
private final String SAMPLE_DB_NAME = "project";
private final String PPT_TABLE_NAME1 = "notes";
SQLiteDatabase notesDB = null;
View_PPT_List getsubla = new View_PPT_List();
ArrayList<String> FilesInFolder = GetFiles(Environment.getExternalStorageDirectory()
.getPath());
public ArrayList<String> GetFiles(String DirectoryPath) {
ArrayList<String> MyFiles = new ArrayList<String>();
File f = new File(DirectoryPath);
f.mkdirs();
File[] files = f.listFiles();
if (files.length == 0)
return null;
else {
for(int i=0; i<files.length;i++)
MyFiles.add(files[i].getName());
}
return MyFiles;
}
public void onListItemClick(ListView l, View view, final int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, view, position, id);
String filename = FilesInFolder.get(position);
String filepath = Environment.getExternalStorageDirectory()
.getPath() + "/" + filename;
String subla = getsubla.getSublabel();
notesDB = this.openOrCreateDatabase(SAMPLE_DB_NAME, MODE_PRIVATE, null);
notesDB.execSQL("INSERT INTO " +
PPT_TABLE_NAME1 + " (subjid, "+ "pptName, " +
"pptPath)" +
" Values ('"+subla+"', '"+filename+"',
'"+filepath+"');");
Intent in = new Intent (Add_PPT_Activity.this,View_PPT_List.class);
startActivity(in);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1,FilesInFolder));
}
}
please help,
Related
The main problem is that when i add bookmark codes from direct recyclerview it works perfectly fine but when i add those codes to another fragment it just only show a toast that bookmark is added or deleted but that bookmarked word doesn't show in favorite list.
Here is my Database codes
public class DictionaryDB {
public static final String ID = "id";
public static final String SANSKRIT = "sanskrit_word";
public static final String BANGLA = "bn_word";
public static final String STATUS = "status";
public static final String USER = "user_created";
public static final String TABLE_NAME = "sanskrit_words";
public static final String BOOKMARKED = "b";
public static final String USER_CREATED = "u";
DatabaseInitializer initializer;
public DictionaryDB(DatabaseInitializer initializer) {
this.initializer = initializer;
}
public void addWord(String sanskritWord, String banglaWord) {
SQLiteDatabase db = initializer.getWritableDatabase();
String sql = "INSERT INTO " + TABLE_NAME + " (" + SANSKRIT +
", " + BANGLA + ", " + USER + ") VALUES ('" + sanskritWord +
"', '" + banglaWord + "', '" + USER_CREATED + "') ";
db.execSQL(sql);
}
public List<Word> getWords(String sanskritWord) {
SQLiteDatabase db = initializer.getReadableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE " + SANSKRIT + " LIKE ? ";
Cursor cursor = null;
try {
cursor = db.rawQuery(sql, new String[]{sanskritWord + "%"});
List<Word> wordList = new ArrayList<Word>();
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String sanskrit = cursor.getString(1);
String bangla = cursor.getString(2);
String status = cursor.getString(3);
wordList.add(new Word(id, sanskrit, bangla, status));
}
return wordList;
} catch (SQLiteException exception) {
exception.printStackTrace();
return null;
} finally {
if (cursor != null)
cursor.close();
}
}
//************Waka Maka Saka *****************//******************//
public List<Word> getBookmarkedWords() {
SQLiteDatabase db = initializer.getReadableDatabase();
String sql = "SELECT * FROM " + TABLE_NAME + " WHERE " + STATUS + " = '" + BOOKMARKED + "'";
Cursor cursor = db.rawQuery(sql, null);
List<Word> wordList = new ArrayList<Word>();
while(cursor.moveToNext()) {
int id = cursor.getInt(0);
String sanskrit = cursor.getString(1);
String bangla = cursor.getString(2);
String status = cursor.getString(3);
wordList.add(new Word(id, sanskrit, bangla, status));
}
cursor.close();
db.close();
return wordList;
}
public void bookmark(int id) {
SQLiteDatabase db = initializer.getWritableDatabase();
String sql = "UPDATE " + TABLE_NAME + " SET " + STATUS + " = '"
+ BOOKMARKED + "' WHERE " + ID + " = " + id;
db.execSQL(sql);
db.close();
}
public void deleteBookmark(int id) {
SQLiteDatabase db = initializer.getWritableDatabase();
String sql = "UPDATE " + TABLE_NAME + " SET " + STATUS + " = '' " +
" WHERE " + ID + " = " + id;
db.execSQL(sql);
db.close();
}
}
My RecyclerView codes
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>implements Filterable {
private Context context;
private List<Word> wordList;
List<Word> filwordList;
private DictionaryDB dictionaryDB;
public RecyclerViewAdapter(Context context, List<Word> itemList, DictionaryDB dictionaryDB) {
this.context = context;
this.wordList = itemList;
this.dictionaryDB = dictionaryDB;
filwordList = new ArrayList<Word>(itemList);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.wordslist_two_rv, parent, false);
// Create and return a new holder instance
ViewHolder viewHolder = new ViewHolder(view);
return viewHolder;
}
#Override
public void onBindViewHolder(final ViewHolder holder, int position) {
final Word word = wordList.get(position);
holder.msanskrit.setText(word.sanskrit);
if(word.status != null && word.status.equals(DictionaryDB.BOOKMARKED)) {
holder.bookmark.setImageResource(R.drawable.cards_heart);
}
else {
holder.bookmark.setImageResource(R.drawable.cards_heart_grey);
}
holder.bookmark.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bookMarkWord(word, holder.bookmark);
}
});
}
private void bookMarkWord(final Word word, final ImageButton bookmark) {
if (word.status != null && word.status.equals(DictionaryDB.BOOKMARKED)) {
dictionaryDB.deleteBookmark(word.id);
word.status = "";
bookmark.setImageResource(R.drawable.cards_heart_grey);
Toast.makeText(context, "Bookmark Deleted", Toast.LENGTH_SHORT).show();
}
else {
dictionaryDB.bookmark(word.id);
word.status = DictionaryDB.BOOKMARKED;
bookmark.setImageResource(R.drawable.cards_heart);
Toast.makeText(context, "Bookmark Added", Toast.LENGTH_SHORT).show();
}
}
/*
public void updateEntries(List<Word> wordList) {
if (wordList == null) {
AlertDialog dialog = new AlertDialog.Builder(context)
.setTitle("Sorry!")
.setMessage("Your phone doesn't support pre-built database")
.create();
dialog.show();
} else {
this.wordList = wordList;
notifyDataSetChanged();
}
}
*/
#Override
public Filter getFilter() {
return Searched_Filter;
}
private Filter Searched_Filter = new Filter() {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
List<Word> filteredList = new ArrayList<>();
if (constraint == null || constraint.length() == 0) {
filteredList.addAll(filwordList);
} else {
String filterPattern = constraint.toString().toLowerCase().trim();
for (Word item : filwordList) {
if (item.getSanskrit().toLowerCase().contains(filterPattern)) {
filteredList.add(item);
}
}
}
FilterResults results = new FilterResults();
results.values = filteredList;
return results;
}
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
wordList.clear();
wordList.addAll((ArrayList<Word>)results.values);
notifyDataSetChanged();
}
};
#Override
public int getItemCount() {
return wordList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView msanskrit;
final ImageButton bookmark;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
msanskrit = itemView.findViewById(R.id.tvSansTerm);
// mbangla = itemView.findViewById(R.id.tvBnTerm);
bookmark = itemView.findViewById(R.id.bookmarkBtn);
}
#Override
public void onClick(View view) {
int position = this.getAdapterPosition();
Word word = wordList.get(position);
String sanskrit = word.getSanskrit();
String bangla = word.getBangla();
// String sources = term.getMSources();
Intent intent = new Intent(context, TermThreeDetailsActivity.class);
intent.putExtra("Rsanskrit", sanskrit);
intent.putExtra("Rbangla", bangla);
// intent.putExtra("Rsources", sources);
context.startActivity(intent);
}
}
}
My Detalis Fragment codes
public class TermThreeDetailsFragment extends Fragment {
private Toolbar toolbar;
TextView termTextView,descTextView;
private ImageButton imgBtn;
private DictionaryDB dictionaryDB;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.show_three_details, container, false);
termTextView = view.findViewById(R.id.textvWord);
descTextView = view.findViewById(R.id.textvDesc);
imgBtn = view.findViewById(R.id.favAddBtn);
getData();
toolbar = ((Toolbar) view.findViewById(R.id.toolbar));
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
DatabaseInitializer initializer = new DatabaseInitializer(getContext());
initializer.initializeDataBase();
dictionaryDB = new DictionaryDB(initializer);
WordCheck();
return view;
}
public void getData() {
Intent intent = getActivity().getIntent();
String sanskrit = intent.getStringExtra("Rsanskrit");
String bangla = intent.getStringExtra("Rbangla");
termTextView.setText(sanskrit);
descTextView.setText(bangla);
}
private void WordCheck() {
final Word word = new Word();
if(word.status != null && word.status.equals(DictionaryDB.BOOKMARKED)) {
imgBtn.setImageResource(R.drawable.cards_heart);
}
else {
imgBtn.setImageResource(R.drawable.cards_heart_grey);
}
imgBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
bookMarkWord(word, imgBtn);
}
});
}
private void bookMarkWord(final Word word, final ImageButton imgBtn) {
if (word.status != null && word.status.equals(DictionaryDB.BOOKMARKED)) {
dictionaryDB.deleteBookmark(word.id);
word.status = "";
imgBtn.setImageResource(R.drawable.cards_heart_grey);
Toast.makeText(getContext(), "Bookmark Deleted", Toast.LENGTH_SHORT).show();
}
else {
dictionaryDB.bookmark(word.id);
word.status = DictionaryDB.BOOKMARKED;
imgBtn.setImageResource(R.drawable.cards_heart);
Toast.makeText(getContext(), "Bookmark Added", Toast.LENGTH_SHORT).show();
}
}}
My Favorite Fragment codes
public class FavoritesFragment extends Fragment {
RecyclerView rv;
private LinearLayoutManager layoutManager;
DictionaryDB dictionaryDB;
FavoriteAdapter rvFavAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.favorites_fragment,container,false);
Toolbar toolbar = ((Toolbar) view.findViewById(R.id.fav_toolbar));
AppCompatActivity activity = (AppCompatActivity) getActivity();
activity.setSupportActionBar(toolbar);
setHasOptionsMenu(true);
DatabaseInitializer initializer = new DatabaseInitializer(getContext());
initializer.initializeDataBase();
dictionaryDB = new DictionaryDB(initializer);
List<Word> wordList = dictionaryDB.getBookmarkedWords();
rv = ((RecyclerView) view.findViewById(R.id.rvFavorites));
if (wordList.size() != 0) {
layoutManager = new LinearLayoutManager(getContext());
rv.setLayoutManager(layoutManager);
rv.setHasFixedSize(true);
rvFavAdapter = new FavoriteAdapter(getContext(), dictionaryDB,wordList);
rv.setAdapter(rvFavAdapter);
} else {
Toast.makeText(getContext(), "You have no bookmark yet.", Toast.LENGTH_SHORT).show();
}
return view;
}
}
When i use bookmark codes from direct RecyclerView
When i use same bookmark codes from another fragment this happens
Any help will be heavily appreciated 🙏
Problem Solved
Just add those to RecyclerView
int position = this.getAdapterPosition();
Word word = wordList.get(position);
Bundle bundle = new Bundle();
bundle.putParcelable("allData", word);
Fragment detailsFragment = new TermThreeDetailsFragment();
detailsFragment.setArguments(bundle);
FragmentTransaction fT =((AppCompatActivity)context).getSupportFragmentManager().beginTransaction();
fT.replace(R.id.fragment_container, detailsFragment);
fT.addToBackStack(null);
fT.commit();
}
And add this codes to Fragment Class
word = new Word(Parcel.obtain());
Bundle bundle = this.getArguments();
if (bundle != null) {
word = bundle.getParcelable("allData");
termTextView.setText(word.getSanskrit());
descTextView.setText(word.getBangla());
}
*** You need to make you POJO class Parcelable to pass objects between fragments. ***
I am new to android, I am trying to retrieve values from a sqlite database based on the listview values. I tried to retrieve values using string variable. I can do this if I directly substitute the value in the place of variable.
Following this I post my codes kindly help me to sort out this.
DBhelper.java
public class DBHelper extends SQLiteOpenHelper{
public SQLiteDatabase DB;
public String DBPath;
public static String DBName = "VERIFY ME1.sqlite3";
public static final int version = '1';
public static Context currentContext;
public static String tableName = "FORM2";
public DBHelper(Context context) {
super(context, DBName, null, version);
currentContext = context;
DBPath = "/data/data/" + context.getPackageName() + "/databases";
createDatabase();
Oninsert(DB);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}
private void createDatabase() {
boolean dbExists = checkDbExists();
if (dbExists) {
// do nothing
}
else {
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("CREATE TABLE IF NOT EXISTS " +tableName +" (AppNo VARCHAR, AppName VARCHAR," +
" Area VARCHAR, FHcode INT(3));");
}}
private boolean checkDbExists() {
SQLiteDatabase checkDB = null;
try {
String myPath = DBPath + DBName;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void Oninsert(SQLiteDatabase dB2) {
// TODO Auto-generated method stub
DB = currentContext.openOrCreateDatabase(DBName, 0, null);
DB.execSQL("INSERT INTO " +
tableName +
" Values ('M001','shumi','India',250);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('C002','sarah','India',251);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('D003','Lavya','USA',252);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('V004','Avi','EU',253);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('T005','Shenoi','Bangla',254);");
DB.execSQL("INSERT INTO " +
tableName +
" Values ('L006','Lamha','Australia',255);");
DB.close();
}
}
ListActivity.java
public class login2 extends ListActivity implements OnItemClickListener {
private static final login2 ListActivity = null;
private static final AdapterView<?> parent = null;
private static int mPosition = 0;
private static final long id = 0;
private ArrayList<String> results = new ArrayList<String>();
private String tableName = DBHelper.tableName;
private SQLiteDatabase newDB;
private String AppName1,ApplID,FHcode,Area;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
}
private void displayResultList() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
getListView().setOnItemClickListener(this);
}
private String openAndQueryDatabase() {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c = newDB.rawQuery("SELECT * FROM " +tableName +"", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
AppName1 = c.getString(c.getColumnIndex("AppName"));
results.add(AppName1 );
}while (c.moveToNext());
}
}
c.close();
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
//if (newDB == null)
// newDB.execSQL("DELETE FROM " + tableName);
//newDB.close();
}
return AppName1;
}
public void onClick(View arg0) {
login2 det = (login2)ListActivity;
det.onItemClick(parent, arg0, mPosition, id);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
String data=(String)parent.getItemAtPosition(position);
//showMessage("Successfully", data);
if (data != null ) {
try {
DBHelper dbHelper = new DBHelper(this.getApplicationContext());
newDB = dbHelper.getWritableDatabase();
Cursor c1 = newDB.rawQuery("SELECT DISTINCT AppNo, AppName, FHcode, Area FROM "
+tableName +" where AppName ="+data+"" ,null);
if (c1 != null ) {
if (c1.moveToFirst()) {
do {
ApplID= c1.getString(c1.getColumnIndex("AppNo"));
String AppName =c1.getString(c1.getColumnIndex("AppName"));
Area = c1.getString(c1.getColumnIndex("Area"));
FHcode =c1.getString(c1.getColumnIndex("FHcode"));
Intent intent = new Intent(getApplicationContext(), form.class);
//Create a bundle object
Bundle b = new Bundle();
//Inserts a String value into the mapping of this Bundle
b.putString("AppName", AppName.toString());
b.putString("Apprefno", ApplID.toString());
b.putString("FHcode", FHcode.toString());
b.putString("Area", Area.toString());
//Add the bundle to the intent.
intent.putExtras(b);
//start the DisplayActivity
startActivity(intent);
}
while (c1.moveToNext());
}
}
}
catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
//if (newDB == null)
//newDB.execSQL("DELETE FROM " + tableName);
newDB.close();
}
}
}
public void showMessage (String title, String message)
{
Builder builder=new Builder(this);
builder.setCancelable(true);
builder.setTitle(title);
builder.setMessage(message);
builder.show();
}
You have taken this column as an integer FHcode INT(3)
and trying to fetch values as an string that is wrong
c1.getString(c1.getColumnIndex("FHcode")
change to c1.getInt**(c1.getColumnIndex("FHcode")
In my app, I am allowing user to select five contact(one by one) so that I can send a custom message to selected contacts. I want to save the selected contacts to the DataBase. When user clicks on "Pick Contact Button", it opens phone's contact book and the selected contact will get displayed in List View. Similarly, he can add 5 contacts for which I want to save them in DataBase. I have been able to write some code but don't how to save the contact.Please Help.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
message = (EditText) findViewById(R.id.et_message);
DatabaseHandler db = new DatabaseHandler(this);
/**
* CRUD Operations
* */
// Inserting Contacts
Log.d("Insert: ", "Inserting ..");
// Reading all contacts
Log.d("Reading: ", "Reading all contacts..");
List<ContactItems> contacts = db.getAllContacts();
for (ContactItems cn : contacts) {
String log = "Id: "+cn.getType()+" ,Name: " + cn.getName() + " ,Phone: " + cn.getNumber();
// Writing Contacts to log
Log.d("Name: ", log);
}
/************************** saving custom message *****************************/
// for saving text that user can change as per need
final SharedPreferences preferences = PreferenceManager
.getDefaultSharedPreferences(this);
// loads the text that has been stored to SP and set it to Edit Text
message.setText(preferences.getString("autoSave", ""));
// adding addTextChangedListner() to the Edit Text View
message.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
// saving text after it is changed by the user
preferences.edit().putString("autoSave", s.toString()).commit();
}
});
ListView contactlist = (ListView) findViewById(R.id.contactListitems);
Resources res = getResources();
adapter = new CustomAdapter(MainActivity.this, selectedContactList, res);
contactlist.setAdapter(adapter);
/**************************EDIT******************************************/
contactlist.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
String contactData = selectedContactList.get(arg2).toString();
}
});
// defining button elements for picking contacts from phone-book
btn_cntct = (Button) findViewById(R.id.bpickperson);
btn_cntct.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (selectedContactList.size() < 5) {
// TODO Auto-generated method stub
// using Intent for fetching contacts from phone-book
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
startActivityForResult(intent, REQUESTCODE);
} else {
// print toast for not allowing user to add more contacts
Toast.makeText(getApplicationContext(),
"You Can Only Add 5 Contacts ", Toast.LENGTH_SHORT)
.show();
}
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (data != null) {
Uri uri = data.getData();
Log.i("data", uri.toString());
if (uri != null) {
Cursor c = null;
try {
c = getContentResolver()
.query(uri,
new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.TYPE },
null, null, null);
if (c != null && c.moveToFirst()) {
final ContactItems item = new ContactItems(
c.getString(0), c.getString(1), c.getInt(2));
item.setName(c.getString(0));
item.setNumber(c.getString(1));
item.setType(c.getInt(2));
selectedContactList.add(item);
Set<ContactItems> s = new TreeSet<ContactItems>(
new Comparator<ContactItems>() {
#Override
public int compare(ContactItems o1,
ContactItems o2) {
// for preventing duplicacy of contacts
// and calling toast
if (o1.number.equals(o2.number)) {
Toast.makeText(
getApplicationContext(),
"Selected Number Already Exists",
Toast.LENGTH_SHORT).show();
} else {
}
return o1.getNumber().compareTo(
o2.getNumber());
}
});
s.addAll(selectedContactList);
selectedContactList.clear();
selectedContactList.addAll(s);
adapter.notifyDataSetChanged();
// save the task list to preference
}
} finally {
if (c != null) {
c.close();
}
}
}
}
}
}
ContactItems.java
public class ContactItems {
String name = "";
String number = "";
int type = 0;
public ContactItems(String name, String number, int type) {
super();
this.name = name;
this.number = number;
this.type = type;
}
public ContactItems(Parcel source) {
// TODO Auto-generated constructor stub
this.name = source.readString();
this.number = source.readString();
this.type = source.readInt();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public static final Parcelable.Creator<ContactItems> CREATOR = new Parcelable.Creator<ContactItems>() {
#Override
public ContactItems createFromParcel(Parcel source) {
return new ContactItems(source);
}
#Override
public ContactItems[] newArray(int size) {
return new ContactItems[size];
}
};
}
DatabaseHandler.java
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 = "contactManager";
// contact table name
private static final String TABLE_CONTACTS = "contacts";
// contacts table column names
private static final String KEY_NAME = "name";
private static final String KEY_PH_NO = "phone_number";
private static final String KEY_ID = "id";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
// Creating Tables
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_CONACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
+ KEY_PH_NO + " TEXT" + ")";
db.execSQL(CREATE_CONACTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS" + TABLE_CONTACTS);
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
void addContact(ContactItems contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName()); // Contact Name
values.put(KEY_PH_NO, contact.getNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
ContactItems getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
ContactItems contact = new ContactItems(cursor.getString(2),
cursor.getString(1), Integer.parseInt(cursor.getString(0)));
// return contact
return contact;
}
// Getting All Contacts
public List<ContactItems> getAllContacts() {
List<ContactItems> contactList = new ArrayList<ContactItems>();
// 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 {
ContactItems contact = new ContactItems(null);
contact.setType(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
// return contact list
return contactList;
}
// Updating single contact
public int updateContact(ContactItems contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_NAME, contact.getName());
values.put(KEY_PH_NO, contact.getNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getType()) });
}
// Deleting single contact
public void deleteContact(ContactItems contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getType()) });
db.close();
}
// Getting contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
CustomAdapter.java
public class CustomAdapter extends BaseAdapter {
/*********** Declare Used Variables *********/
private Activity activity;
private ArrayList<ContactItems> data;
private static LayoutInflater inflater = null;
public Resources res;
// ListModel tempValues=null;
int i = 0;
String selectedNum = " ";
/************* CustomAdapter Constructor *****************/
public CustomAdapter(Activity a, ArrayList<ContactItems> d,
Resources resLocal) {
/********** Take passed values **********/
activity = a;
data = d;
res = resLocal;
/*********** Layout inflator to call external xml layout () ***********/
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
/******** What is the size of Passed Arraylist Size ************/
public int getCount() {
if (data.size() <= 0)
return 1;
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public static class ViewHolder {
public TextView text;
public TextView textNumber;
public ImageView image;
}
/****** Depends upon data size called for each row , Create each ListView row *****/
#SuppressLint("DefaultLocale")
public View getView(int position, View convertView, ViewGroup parent) {
final int pos = position;
View vi = convertView;
ViewHolder holder;
// check if converView is null, if it is null it probably means
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
vi = inflater.inflate(R.layout.contactlistitem, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
// if it is not null, just reuse it from the recycler
holder = new ViewHolder();
holder.text = (TextView) vi.findViewById(R.id.contactname);
holder.textNumber = (TextView) vi.findViewById(R.id.contactnumber);
holder.image = (ImageView) vi.findViewById(R.id.deleteimage);
/************ Set holder with LayoutInflater ************/
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
if (data.size() <= 0) {
holder.text.setText("Add Contacts");
holder.textNumber.setText(" ");
holder.image.setVisibility(View.GONE);
} else {
/***** Get each Model object from Arraylist ********/
/************ Set Model values in Holder elements ***********/
holder.text.setText("" + data.get(position).getName());
holder.textNumber.setText("" + data.get(position).getNumber());
holder.image.setVisibility(View.VISIBLE);
holder.image.setImageResource(res.getIdentifier("delete_button",
null, null));
holder.image.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder build = new AlertDialog.Builder(
activity);
build.setTitle("Delete");
build.setMessage("Are You Sure");
build.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
data.remove(pos);
MainActivity.adapter.notifyDataSetChanged();
dialog.dismiss();
}
});
/*
* data.remove(pos);
* MainActivity.adapter.notifyDataSetChanged();
*/
build.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
build.show();
}
});
/******** Set Item Click Listner for LayoutInflater for each row *******/
}
// return the view for a single item in the listview
return vi;
}
}
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);
I am having a problem on the line where I call the query to PostCategoryContent Provider
I get an error stating:
11-13 10:23:40.674: E/AndroidRuntime(26012): android.database.sqlite.SQLiteException: no such column: category_id (code 1): , while compiling: SELECT * FROM post WHERE (category_id=39)
Even though the URI points to another Table postCategory
Can anyone guide me on what I'm doing wrong?
public class PostFragment extends SherlockListFragment implements LoaderCallbacks<Cursor> {
private SimpleCursorAdapter adapter;
private boolean dataRetrieved;
private SlidingArea parent;
PullToRefreshListView pullToRefreshView;
EditText searchBox;
Bundle args = new Bundle();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
parent = (SlidingArea) getActivity();
setHasOptionsMenu(true);
fillData(false);
}
#Override
public void onResume() {
super.onResume();
parent.getSupportActionBar().setCustomView(R.layout.kpmg_actionbar_list_view);
parent.getSupportActionBar().setDisplayShowCustomEnabled(true);
parent.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
final ImageView searchButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_search_list);
searchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (searchBox.getVisibility() == View.GONE)
{
searchBox.setVisibility(View.VISIBLE);
searchBox.requestFocus();
InputMethodManager imm = (InputMethodManager) parent.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(searchBox, InputMethodManager.SHOW_IMPLICIT);
} else {
searchBox.setVisibility(View.GONE);
searchBox.clearFocus();
hideKeyboard(v);
}
}
});
final ImageView refreshButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_refresh_list);
refreshButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getData(getString(R.string.kpmg_json_get_articles), true);
refreshButton.setImageResource(R.drawable.kpmg_actionbar_refresh_dark);
fillData(true);
}
});
searchBox.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user changed the Text
filterData(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
}
//Constant used as key for ID being passed in the bundle between fragments
public static final String NEWS_ID = "newsID";
private void getData(String url, boolean showProgressDialog) {
new Request(showProgressDialog).execute(new String[] {url});
}
public class Request extends AsyncTask<String, Void, String> {
ProgressDialog dialog;
/* This is the only file that needs to be edited */
private GetResponse response = null;
private boolean showProgressDialog = true;
public Request(boolean showProgressDialog)
{
super();
this.showProgressDialog = showProgressDialog;
response = new GetResponse();
}
#Override
protected void onPreExecute() {
if (showProgressDialog) {
dialog = new ProgressDialog(parent);
dialog.setMessage("Retrieving latest information...");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
dialog.show();
}
}
//This method must return the type specified in the constructor
#Override
protected String doInBackground(String... url) {
response.setUrl(url[0]);
String res = response.execute();
// When it returns the "res" it will call onPostExecute
return res;
}
#Override
protected void onPostExecute(String result) {
// Here we have response from server
if ( isNetworkAvailable() ){
try {
JSONObject json = new JSONObject(result);
JSONArray arr = json.getJSONArray("posts");
for (int i = arr.length() - 1; i >= 0; --i) {
JSONObject row = arr.getJSONObject(i);
JSONArray arrCategories = row.getJSONArray("categories");
int Created = 0;
int Updated = 0;
for (int j = arrCategories.length() -1; j >= 0; --j){
JSONObject rowCategory = arrCategories.getJSONObject(j);
ContentValues categoryValues = new ContentValues();
categoryValues.put(PostCategoryTable.CATEGORY_ID, rowCategory.getInt("id"));
Cursor categoryCursor = parent.getContentResolver().query(PostCategoryContentProvider.CONTENT_URI, null, PostCategoryTable.CATEGORY_ID + "=" + categoryValues.getAsString(PostCategoryTable.CATEGORY_ID), null, null);
int categoryCount = categoryCursor.getCount();
if (categoryCount == 0) {
categoryValues.put(PostCategoryTable.ICON_NAME, rowCategory.getString("slug"));
categoryValues.put(PostCategoryTable.CATEGORY_NAME, rowCategory.getString("title"));
categoryValues.put(PostCategoryTable.PARENT_ID, rowCategory.getInt("parent"));
parent.getContentResolver().insert(PostCategoryContentProvider.CONTENT_URI, categoryValues);
Created++;
}
else {
categoryCursor.moveToFirst();
categoryValues.put(PostCategoryTable.ICON_NAME, rowCategory.getString("slug"));
categoryValues.put(PostCategoryTable.CATEGORY_NAME, rowCategory.getString("title"));
categoryValues.put(PostCategoryTable.PARENT_ID, rowCategory.getInt("parent"));
parent.getContentResolver().update(PostCategoryContentProvider.CONTENT_URI, categoryValues, PostCategoryTable.CATEGORY_ID + "=" + categoryValues.getAsString(PostCategoryTable.CATEGORY_ID), null);
Updated++;
}
categoryCursor.close();
}
Toast.makeText(parent,"Created : " + "" + Created + " | Updated : " + "" + Updated, Toast.LENGTH_SHORT).show();
if (row.getString("status").equals("publish")) {
ContentValues values = new ContentValues();
values.put(PostTable.POST_ID, row.getString("id"));
values.put(PostTable.CONTENT, Html.fromHtml(row.getString(PostTable.CONTENT)).toString());
values.put(PostTable.EXCERPT, Html.fromHtml(row.getString(PostTable.EXCERPT)).toString());
//image
//imageurl
values.put(PostTable.DATE_MODIFIED, row.getString(PostTable.DATE_MODIFIED));
values.put(PostTable.DATE_PUBLISHED, row.getString(PostTable.DATE_PUBLISHED));
//thumbnail
//thumbnailurl
values.put(PostTable.TITLE, row.getString(PostTable.TITLE));
values.put(PostTable.URL, row.getString("online-url"));
values.put(PostTable.VIDEO_URL, row.getString("video-url"));
//Check for new Categories
//getThumbnail
// byte[] image = AppHelper.getBlobFromURL(row.getString(BlogTable.THUMBNAIL));
// if (image != null) {
//
// values.put(BlogTable.THUMBNAIL, image);
//
// }
Cursor c = parent.getContentResolver().query(PostContentProvider.CONTENT_URI, null, PostTable.POST_ID + "=" + values.getAsString(PostTable.POST_ID), null, null);
int count = c.getCount();
if (count == 0) {
parent.getContentResolver().insert(PostContentProvider.CONTENT_URI, values);
}
else {
c.moveToFirst();
if (!(c.getString(c.getColumnIndex(PostTable.DATE_MODIFIED)).equalsIgnoreCase(values.getAsString(PostTable.DATE_MODIFIED)))) {
//
//
// if (c.getString(c.getColumnIndex(BlogTable.THUMBNAIL)) != values.get(BlogTable.THUMBNAIL)){
// //reset image
// }
//
parent.getContentResolver().update(PostContentProvider.CONTENT_URI, values, PostTable.POST_ID + "=" + values.getAsString(PostTable.POST_ID), null);
}
}
c.close();
//Here we should last retrieved time and used as part of the condition before retrieving data
}
else {
String currentID = row.getString("id");
// Delete unpublished fields
parent.getContentResolver().delete(PostContentProvider.CONTENT_URI, "_id = " + currentID, null);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else {
Toast toast = Toast.makeText( parent , "You are not connected to the internet. Please check your connection, or try again later",
Toast.LENGTH_SHORT);
toast.show();
}
// Call onRefreshComplete when the list has been refreshed.
pullToRefreshView.onRefreshComplete();
super.onPostExecute(result);
ImageView refreshButton = (ImageView) parent.findViewById(R.id.kpmg_actionbar_image_refresh_list);
refreshButton.setImageResource(R.drawable.kpmg_actionbar_refresh);
if (showProgressDialog) {
dialog.dismiss();
}
}
}
private void fillData(boolean isRefresh){
//_id is expected from this method that is why we used it earlier
String[] from = new String[] { PostTable.TITLE, PostTable.DATE_PUBLISHED, PostTable.EXCERPT};
int[] to = new int[] { R.id.kpmg_text_news_title, R.id.kpmg_text_news_date, R.id.kpmg_text_news_excerpt};
//initialize loader to call this class with a callback
if (!isRefresh){
getLoaderManager().initLoader(0, null, this);
}
else {
if (searchBox.getText().length() == 0) {
getLoaderManager().restartLoader(0, null, this);
}
else {
getLoaderManager().restartLoader(0, args, this);
}
}
//We create adapter to fill list with data, but we don't provide any data as it will be done by loader
adapter = new SimpleCursorAdapter(parent, R.layout.kpmg_list_view, null, from, to, 0);
adapter.setViewBinder(new SimpleCursorAdapter.ViewBinder() {
#Override
public boolean setViewValue(View view, Cursor cursor, int column) {
if( column == cursor.getColumnIndex(PostTable.DATE_PUBLISHED) ){ // let's suppose that the column 0 is the date
TextView textDate = (TextView) view.findViewById(R.id.kpmg_text_news_date);
String dateStr = cursor.getString(cursor.getColumnIndex(PostTable.DATE_PUBLISHED));
String formattedDate = AppHelper.calculateRelativeDate(dateStr);
textDate.setText( "Posted - " + formattedDate);
return true;
}
return false;
}
});
setListAdapter(adapter);
}
private void filterData(CharSequence cs){
args.putString("Selection", cs.toString());
getLoaderManager().restartLoader(0, args, this /*LoaderCallbacks<Cursor>*/);
}
#Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle args) {
String[] projection = new String[] { PostTable.TITLE, PostTable.DATE_PUBLISHED, PostTable.EXCERPT, PostTable.ID };
CursorLoader loader;
if (args == null) {
Log.i("Arguments","None");
loader = new CursorLoader(parent, PostContentProvider.CONTENT_URI, projection, null, null, PostTable.DATE_PUBLISHED + " DESC");
}
else {
Log.i("Arguments","Full");
String selectionKeyword = args.getString("Selection");
String selection = PostTable.TITLE + " LIKE ? OR " + PostTable.CONTENT + " LIKE ? OR " + PostTable.EXCERPT + " LIKE ?";
String[] selectionArgs = new String[] {"%" + selectionKeyword + "%","%" + selectionKeyword + "%","%" + selectionKeyword + "%"};
loader = new CursorLoader(parent, PostContentProvider.CONTENT_URI, projection, selection, selectionArgs, PostTable.DATE_PUBLISHED + " DESC");
}
return loader;
}
public void onLoadFinished(Loader<Cursor> arg0, Cursor data) {
adapter.swapCursor(data);
}
public void onLoaderReset(Loader<Cursor> arg0) {
adapter.swapCursor(null);
}
}
On which line is the exception thrown? The problem is more likely an issue with your SQLite syntax than with anything having to do with Loaders or Cursors. Make sure your table is getting initialized as you require. Do a DatabaseUtils.dumpCursor(cursor) to analyze the contents of the Cursor between the exception is thrown. Also, I would look into your use of LIKE... I have seen people having issues with that keyword before.