Hello I build a dictionary app in androidstudio
by searching "word" it should show "def" and "desc"
but it does not show the desc value because of HashMap only put one value how can I put two values and show desc value?
my DictObjectModel is
public class DictObjectModel {
String word, def,desc;
public DictObjectModel(String word, String def,String desc){
this.word=word;
this.def = def;
this.desc = desc;
}
public String getWord()
{
return word;
}
public String getDef()
{
return def;
}
public String getDesc() {
return desc;
}
}
And my search Activity is
private static RecyclerView.Adapter adapter;
private RecyclerView.LayoutManager layoutManager;
private static RecyclerView recyclerView;
public static ArrayList<DictObjectModel> data;
DatabaseHelper db ;
ArrayList<String> wordcombimelist;
ArrayList<String> defcombimelist;
ArrayList<String> desccombimelist;
LinkedHashMap<String,String> namelist;
SearchView searchView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_activity );
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
recyclerView.setHasFixedSize(true);
db= new DatabaseHelper(this);
searchView = (SearchView) findViewById(R.id.searchView);
searchView.setQueryHint("Search Here");
searchView.setQueryRefinementEnabled(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
data = new ArrayList<DictObjectModel>();
fetchData();
searchView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View view) {
searchView.setIconified( false );
}
} );
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {return false; }
#Override
public boolean onQueryTextChange(String newText) {
newText = newText.toLowerCase();
final ArrayList<DictObjectModel> filteredList = new ArrayList<DictObjectModel>();
for (int i = 0; i < wordcombimelist.size(); i++) {
final String text = wordcombimelist.get(i).toLowerCase();
if (text.contains(newText)) {
filteredList.add(new DictObjectModel(wordcombimelist.get(i),defcombimelist.get(i),desccombimelist.get( i )));
}
}
adapter = new CustomAdapter(filteredList);
recyclerView.setAdapter(adapter);
return true;
}
});
}
public void fetchData()
{
db =new DatabaseHelper(this);
try {
db.createDataBase();
db.openDataBase();
}
catch (Exception e)
{
e.printStackTrace();
}
namelist=new LinkedHashMap<>();
int ii;
SQLiteDatabase sd = db.getReadableDatabase();
Cursor cursor = sd.query("content" ,null, null, null, null, null, null);
ii=cursor.getColumnIndex("word");
wordcombimelist=new ArrayList<String>();
defcombimelist= new ArrayList<String>();
desccombimelist= new ArrayList<String>();
while (cursor.moveToNext()){
namelist.put(cursor.getString(ii), cursor.getString(cursor.getColumnIndex("def")));
}
Iterator entries = namelist.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry thisEntry = (Map.Entry) entries.next();
wordcombimelist.add(String.valueOf(thisEntry.getKey()));
defcombimelist.add("- "+String.valueOf(thisEntry.getValue()));
desccombimelist.add("- "+String.valueOf(thisEntry.getValue()));
}
for (int i = 0; i < wordcombimelist.size(); i++) {
data.add(new DictObjectModel(wordcombimelist.get(i), defcombimelist.get(i),desccombimelist.get(i)));
}
adapter = new CustomAdapter(data);
recyclerView.setAdapter(adapter);
}
}
Can anyone suggest how can I fix that?
You need to change the type of namelist from LinkedHashMap<String,String> to LinkedHashMap<String,DictObjectModel>. When you load your data from your database you need to go through each item in cursor, build a DictObjectModel object from it and put the DictObjectModel object in your LinkedHashMap something like namelist.put(cursor.getString(ii), myDictObjectModel). And you'll probably want to rename namelist to dictionary. Hope this helps!
Related
I displayed the contacts in list view but when displaying it shows repeated phone numbers and names. so I tried to remove the duplicate names and numbers. It shows the single names but it displays the incorrect phone numbers of the user. How to solve that issue. This is my code :
public class Split extends AppCompatActivity implements AdapterView.OnItemClickListener {
public static String TAG = "amount";
ListView mainListView;
ProgressDialog pd;
public static final int PERMISSIONS_REQUEST_READ_CONTACTS = 100;
final static List<String> name1 = new ArrayList<>();
List<String> phno1 = new ArrayList<>();
List<Long> bal = new ArrayList<>();
List<Bitmap> img = new ArrayList<>();
private Splitadapter mCustomAdapter;
List<String> names = new ArrayList<String>();
List<String> phonenumbers = new ArrayList<String>();
private ArrayList<ContactModel> _Contacts = new ArrayList<ContactModel>();
Button select;
int amount=100;
float result;
String ph;
String phoneNumber;
EditText search;
private FirebaseAuth mAuth;
FirebaseUser firebaseUser;
FirebaseFirestore db = FirebaseFirestore.getInstance();
#SuppressLint("StaticFieldLeak")
#Override
protected void onCreate(Bundle savedInstanceState) {
setTitle("Split");
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
super.onCreate(savedInstanceState);
setContentView(R.layout.split);
mAuth = FirebaseAuth.getInstance();
search = findViewById(R.id.search_bar);
firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
final List<String> phonenumber = new ArrayList<>();
System.out.print(phonenumber);
mainListView = findViewById(R.id.listview);
showContacts();
select = findViewById(R.id.button1);
search.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
// When user chan ged the Text
mCustomAdapter.getFilter().filter(cs.toString());
//
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
//ma.filter(text);
}
});
select.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder checkedcontacts = new StringBuilder();
ArrayList checkedcontacts1 = new ArrayList();
ArrayList names = new ArrayList();
System.out.println(".............." + (mCustomAdapter.mCheckStates.size()));
System.out.println("name size is" + name1.size());
int a = mCustomAdapter.mCheckStates.size();
result = ((float) amount / a);
System.out.println("final1 amount is " + result);
long result1 = (long) result;
System.out.println("final amount is " + result1);
for (int k = 0; k <= a; k++) {
bal.add(result1);
}
System.out.println("balance" + bal);
System.out.println("selected contacts split amount" + result);
for (int i = 0; i < name1.size(); i++) // it displays selected contacts with amount
{
if (mCustomAdapter.mCheckStates.get(i)) {
checkedcontacts.append(phno1.get(i)).append("\t").append("\t").append("\t").append(result1);
checkedcontacts1.add((phno1.get(i)));
names.add((name1.get(i)));
checkedcontacts.append("\n");
System.out.println("checked contacts:" + "\t" + phno1.get(i) + "\t" + "amount" + "\t" + result1);
}
}
System.out.println("checked names" + names);
System.out.println(
"checkec contcts foggfgfgfgfgf" + checkedcontacts1
);
List<Object> list = new ArrayList<>();
for (Object i : checkedcontacts1) {
list.add(i);
}
System.out.println("checked contacts size is" + checkedcontacts1.size());
HashMap<String, HashMap<String, Object>> Invites = new HashMap<>();
for (int i = 0; i < checkedcontacts1.size(); i++) {
HashMap<String, Object> entry = new HashMap<>();
entry.put("PhoneNumber", list.get(i));
entry.put("Name", names.get(i));
System.out.println("entry is" + entry);
for (int j = i; j <= i; j++) {
System.out.println("phonenumber" + i + ":" + list.get(i));
System.out.println("amount" + j + ":" + bal.get(j));
//dataToSave.put("phonenumber" +i, list.get(i));
entry.put("Amount", bal.get(j));
}
Invites.put("Invite" + i, entry);
}
}
private void showContacts() // it is for to check the build versions of android . if build version is >23 or above it is set the permissions at the run time . if the build version is less than 23 the we give the permissions at manifest file .
{if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_CONTACTS}, PERMISSIONS_REQUEST_READ_CONTACTS);
}
else {
mCustomAdapter = new Splitadapter(Split.this,_Contacts);
//ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,aa);
mainListView.setAdapter(mCustomAdapter);
mainListView.setOnItemClickListener(this);
mainListView.setItemsCanFocus(false);
mainListView.setTextFilterEnabled(true);
getAllContacts(this.getContentResolver());
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, // it is display the request access permission dilogue box to access the contacts of user.
#NonNull int[] grantResults) {
if (requestCode == PERMISSIONS_REQUEST_READ_CONTACTS) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission is granted
showContacts();
} else {
Toast.makeText(this, "Until you grant the permission, we canot display the names", Toast.LENGTH_SHORT).show();
}
}
}
private void getAllContacts(ContentResolver getcontentResolver) {
// it displays the contact phonenumber and name rom the phone book. and add to the list.
Cursor phones = getcontentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
while (phones.moveToNext()) {
String name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME ));
phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER ));
long contactId = Long.parseLong(phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)));
if(!phonenumbers.contains(phoneNumber)) {
phonenumbers.add(phoneNumber);
}
if(!names.contains(name)) {
names.add(name);
}
}
Collections.sort(names);
for (int i = 0; i < names.size(); i++) {
ContactModel contacts = new ContactModel();
contacts.setName(names.get(i));
contacts.setPhonenum(phonenumbers.get(i));
_Contacts.add(contacts);
}
System.out.println("phonenumber size is" + phonenumbers.size());
System.out.println("name size is" + names.size());
phones.close();
}
}
And this is my adapter class :
public class Splitadapter extends BaseAdapter implements Filterable,CompoundButton.OnCheckedChangeListener
{
public SparseBooleanArray mCheckStates;
private ArrayList<ContactModel> _Contacts;
private Context mContext;
private LayoutInflater inflater;
private ValueFilter valueFilter;
private ArrayList<ContactModel> mStringFilterList;
List<Bitmap> img = new ArrayList<>();
public Splitadapter(Context context, ArrayList<ContactModel> _Contacts) {
super();
mContext = context;
this._Contacts = _Contacts;
mStringFilterList = _Contacts;
mCheckStates = new SparseBooleanArray(_Contacts.size());
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
getFilter();
}//End of CustomAdapter constructor
#Override
public int getCount() {
return _Contacts.size();
}
#Override
public Object getItem(int position) {
return _Contacts.get(position).getName();
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
TextView textviewName;
TextView textviewNumber;
CheckBox checkbox;
ImageView image;
int id;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
final int pos = position;
//
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.row, null);
holder.textviewName = (TextView) convertView.findViewById(R.id.name);
holder.textviewNumber = (TextView) convertView.findViewById(R.id.mobile);
holder.checkbox = (CheckBox) convertView.findViewById(R.id.check);
holder.image = convertView.findViewById(R.id.image);
convertView.setTag(holder);
}//End of if condition
else {
holder = (ViewHolder) convertView.getTag();
}//End of else
holder.checkbox.setId(position);
holder.textviewName.setId(position);
holder.textviewNumber.setId(position);
holder.textviewName.setText(_Contacts.get(position).getName());
holder.textviewNumber.setText(_Contacts.get(position).getPhonenum());
holder.checkbox.setTag(position);
holder.checkbox.setChecked(mCheckStates.get(position, false));
holder.checkbox.setOnCheckedChangeListener(this);
holder.image.setImageBitmap(_Contacts.get(position).getImage());
//holder.id = position;
return convertView;
// }//End of getView method
}
boolean isChecked(int position) {// it returns the checked contacts
return mCheckStates.get(position, false);
}
void setChecked(int position, boolean isChecked) { //set checkbox postions if it sis checked
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), true);
} else {
mCheckStates.delete((Integer) buttonView.getTag());
}
}
#Override
public Filter getFilter() {
if (valueFilter == null) {
valueFilter = new ValueFilter();
}
return valueFilter;
}
private class ValueFilter extends Filter {
//Invoked in a worker thread to filter the data according to the constraint.
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
if (constraint != null && constraint.length() > 0) {
ArrayList<ContactModel> filterList = new ArrayList<ContactModel>();
for (int i = 0; i < mStringFilterList.size(); i++) {
if ((mStringFilterList.get(i).getName().toUpperCase())
.contains(constraint.toString().toUpperCase())) {
ContactModel contacts = new ContactModel();
contacts.setName(mStringFilterList.get(i).getName());
contacts.setPhonenum(mStringFilterList.get(i).getPhonenum());
filterList.add(contacts);
}
}
results.count = filterList.size();
results.values = filterList;
} else {
results.count = mStringFilterList.size();
results.values = mStringFilterList;
}
return results;
}
//Invoked in the UI thread to publish the filtering results in the user interface.
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint,
FilterResults results) {
_Contacts = (ArrayList<ContactModel>) results.values;
notifyDataSetChanged();
}
}
} //End of CustomAdapter instance inne
And this my class :
public class ContactModel {
String phonenum;
String cname;
Bitmap b;
public String getPhonenum() {
return phonenum;
}
public void setPhonenum(String phonenum) {
this.phonenum = phonenum;
System.out.println("se ph num"+phonenum);
}
public String getName() {
return cname;
}
public void setName(String name) {
this.cname = name;
}
public void setImage(Bitmap image) {
this.b = image;
}
public Bitmap getImage() {
return b;
}
}
How to solve that issue?
Use below link.I hope this will solve your problem.
Android get phone contacts and remove duplicates
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, ContactsContract.Contacts.DISPLAY_NAME + " ASC ");
String lastnumber = "0";
if (cur.getCount() > 0)
{
while (cur.moveToNext())
{
String number = null;
String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)
{
Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?", new String[]
{ id }, null);
while (pCur.moveToNext())
{
number = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.e("lastnumber ", lastnumber);
Log.e("number", number);
if (number.equals(lastnumber))
{
}
else
{
lastnumber = number;
Log.e("lastnumber ", lastnumber);
int type = pCur.getInt(pCur.getColumnIndex(Phone.TYPE));
switch (type)
{
case Phone.TYPE_HOME:
Log.e("Not Inserted", "Not inserted");
break;
case Phone.TYPE_MOBILE:
databaseHandler.insertContact(id, name, lastnumber, 0);
break;
case Phone.TYPE_WORK:
Log.e("Not Inserted", "Not inserted");
break;
}
}
}
pCur.close();
}
}
}
Several wrong things here:
You have independent conditions for uniqueness of names vs phone numbers. It should be one to keep it all consistent.
Even if, somehow, the matching is preserved from the first point, you will mess everything up by sorting only the names list. The names will be ordered alphabetically but the phones will remain as they were.
You can use HashSet instead of arrayList and you must override equal and hashset method of your ContactModel class like this :
#Override
public boolean equals(Object o) {
if(o == null)
return false;
if (o == this) {
return true;
}
if(o instanceof ContactModel) {
return this.phoneNum.equals(o.phoneNum); //Or check other Parameters
}
}
#Override
public int hashCode() {
return this.phoneNum!= null ? this.phoneNum.hashCode() : 0;
}
if you do this , it will not add duplicate automatically contact in your list.
This is my query in my DatabaseHelper
public List<String> getallstatus(){
List<String> list = new ArrayList<>();
String query = "select * from ref_status";
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(query,null);
try{
if(cursor.moveToFirst()){
do{
list.add(cursor.getString(0));
list.add(cursor.getString(1));
}while(cursor.moveToNext());
}
cursor.close();
db.close();
}catch(Exception e){
Log.e("onins" , e.getMessage(),e);
}
return list;
}
This is my dataProvider class
public class DataProvider {
private String regcode, regname;
public DataProvider(String regcode, String regname){
this.regcode =regcode;
this.regname = regname;
}
public String getRegcode(){ return regcode; }
public void setRegCode(){ this.regcode = regcode; }
public String getRegname(){ return regname; }
public void setRegname() { this.regname = regname; }
#Override
public String toString(){
return regname;
}
#Override
public boolean equals(Object obj) {
if(obj instanceof DataProvider){
DataProvider c = (DataProvider ) obj;
if(c.getRegname().equals(regname) && c.getRegcode()==regcode )
return true;
}
return false;
}
}
and this is my onCreate in my main activity
db = new DatabaseHelper(getApplicationContext());
List<String> result = db.getallstatus();
//spinner elements
ArrayList<DataProvider> datalist = new ArrayList<>();
ArrayAdapter<DataProvider> adapter = new ArrayAdapter<DataProvider>(this,android.R.layout.simple_spinner_dropdown_item,datalist);
// Drop down layout style - list view with radio button
// adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//attaching adapter to spinner
valueofspin.setAdapter(adapter);
// valueofspin.setSelection(adapter.getPosition(myItem));
I just wanna pass the result of this List result to my array adapter. I'm new in android studio hope somebody can help me. Thanks in advance.
Do this Create a constructor in your Arrayadapter
public class ArrayAdapter extends....{
ArrayList<DataProvider> dataList;
List<String> list;
ArrayAdapter(Context context,resources id,ArrayList<DataProvider>
dataList,List<String> list){
this.context=context;
this.dataList = datalist;
this.list = list
}
}
On your Activity...Do this
ArrayAdapter<DataProvider> adapter = new ArrayAdapter<DataProvider>(this,android.R.layout.simple_spinner_dropdown_item,datalist,result);
Pass result through constructor..
I am using Recyclerview ,Here is Json file the insert query written in Json array though the json data is not stored in SQLite.When we destroy the app and again restart it will only show
blank rows and again press a button and it will show json data aftr emptyrow ie:after destroy data gets lost.Do help me thank you
public class Recyclerview extends AppCompatActivity {
private RecyclerView mRecyclerView;
CustomAdapter cu;
ArrayList<Employee> arr, arr1;
Toolbar toolbar;
TextView t1, t2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recyclerview);
toolbar = (Toolbar) findViewById(R.id.toolbar1);
setSupportActionBar(toolbar);
final RecyclerView rv = (RecyclerView) findViewById(R.id.rv);
rv.setHasFixedSize(true);
arr = new ArrayList<Employee>();
arr = InitializeData();
final LinearLayoutManager llm = new LinearLayoutManager(Recyclerview.this);
rv.setLayoutManager(llm);
rv.setHasFixedSize(true);
cu = new CustomAdapter(Recyclerview.this, arr);
rv.setAdapter(cu);
registerForContextMenu(rv);
final bank ban = new bank(Recyclerview.this);
ImageButton refresh = (ImageButton) findViewById(R.id.refresh);
refresh.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(Recyclerview.this, "ok", Toast.LENGTH_LONG).show();
if (isNetworkAvailable()) {
String url = ConstantValues.BASE_URL;
RequestBody formBody = new FormBody.Builder()
.add("key1", "value1")
.add("key2", "value2")
.add("key3", "value3")
.build();
try {
post(url, formBody, new Callback() {
#Override
public void onFailure(Call call, IOException e) {
Log.e("JSONDemo", "IOException", e);
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
String JSON = response.body().string();
Log.e("res", " " + JSON);
try {
JSONObject jsonObj = new JSONObject(JSON);
JSONArray resultarr = jsonObj.getJSONArray("result");
final JSONArray resultarr1 = jsonObj.getJSONArray("result1");
ban.OpenDB();
ban.OpenDB();
for (int i = 0; i < resultarr1.length(); i++) {
Employee emp = new Employee();
JSONObject result1obj = resultarr1.getJSONObject(i);
String result1Id = result1obj.getString(ConstantValues.Bank_ID);
String result1NAME = result1obj.getString(ConstantValues.Bank_NAME);
Log.e("result", " " + result1Id);
Log.e("result", " " + result1NAME);
emp.setId(result1obj.getString(ConstantValues.Bank_ID));
emp.setName(result1obj.getString(ConstantValues.Bank_NAME));
arr.add(emp);
long l = 0;
l=ban.InsertQryForTabEmpData(ConstantValues.Bank_ID,ConstantValues.Bank_NAME);
}
ban.CloseDB();
runOnUiThread(new Runnable() {
#Override
public void run() {
cu.notifyDataSetChanged();
}
});
} catch (Exception e) {
Log.e("JSONDemo", "onResponse", e);
}
}
});
} catch (Exception e) {
Log.e("JSONDemo", "Post Exception", e);
}
} else {
Toast.makeText(Recyclerview.this, "Internet not available", Toast.LENGTH_LONG).show();
}
}
});
}
private ArrayList<Employee> InitializeData() {
ArrayList<Employee> arr_emp = new ArrayList<Employee>();
bank ban = new bank(Recyclerview.this);
long l = 0;
ban.OpenDB();
arr_emp = ban.AllSelectQryForTabEmpData1();
ban.CloseDB();
return arr_emp;
}
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private final OkHttpClient client = new OkHttpClient();
Call post(String url, RequestBody formBody, Callback callback) throws IOException {
Request request = new Request.Builder()
.url(url)
.post(formBody)
.build();
Call call = client.newCall(request);
call.enqueue(callback);
return call;
}
}
It is the query of all SQLite:
public class bank {
private Context context;
private SQLiteDatabase SQLiteDb;
public bank(Context context){
this.context=context;
}
public static class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context) {
super(context, ConstantValues.DBName, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(" create table if not exists " + ConstantValues.TabEmpData+"("
+ ConstantValues.Bank_ID + " text, "
+ ConstantValues.Bank_NAME + " text )");
}
#Override
public void onUpgrade(SQLiteDatabase db, int i, int i1) {
db.execSQL(" create table if not exists " + ConstantValues.TabEmpData+"("
+ ConstantValues.Bank_ID + " text, "
+ ConstantValues.Bank_NAME + " text )");
}
}
public void OpenDB() {
SQLiteDb = new DBHelper(context).getWritableDatabase();
}
public void CloseDB() {
if (SQLiteDb.isOpen()) {
SQLiteDb.close();
}
}
public long InsertQryForTabEmpData(String ID, String NAME) {
ContentValues cv = new ContentValues();
cv.put(ConstantValues.Bank_ID, ID);
cv.put(ConstantValues.Bank_NAME, NAME);
long l = SQLiteDb.insert(ConstantValues.TabEmpData, null, cv);
return l;
}
public long UpdateQryForTabEmpData(String ID
, String NAME
) {
ContentValues cv = new ContentValues();
cv.put(ConstantValues.Bank_ID, ID);
cv.put(ConstantValues.Bank_NAME, NAME);
long l = SQLiteDb.update(ConstantValues.TabEmpData, cv, ConstantValues.Bank_ID+ "=" + ID, null);
return l;
}
public long DeleteQryForTabEmpData(String ID) {
long l = SQLiteDb.delete(ConstantValues.TabEmpData, ConstantValues.Bank_ID+ "=" + ID, null);
return l;
}
public ArrayList SelectQryForTabEmpData(String ID) {
ArrayList<String> data = new ArrayList();
String[] arg = {
"ID"
, "NAME"
};
String selection = " ID= " + ID;
String QRY = " SELECT ID,NAME FROM TabEmpData WHERE ID = " + ID;// +" AND EmpFName = 'test' grup by empid,fname,lastname having Empsalary > = 2000 order by fname asc,salry desc limit 100";
Cursor cursor = SQLiteDb.rawQuery(QRY, null);//
SQLiteDb.query(ConstantValues.TabEmpData, arg, selection, null, null, null, null, null);
while (cursor.moveToNext()) {
data.add(0, cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_ID)));
data.add(1, cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_NAME)));
}
cursor.close();
return data;
}
public ArrayList AllSelectQryForTabEmpData1() {
ArrayList<Employee> data = new ArrayList();
Cursor cursor = SQLiteDb.query(ConstantValues.TabEmpData, null, null, null, null, null, null, null);
while (cursor.moveToNext()) {
String id = cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_ID));
String name = cursor.getString(cursor.getColumnIndex(ConstantValues.Bank_NAME));
data.add(new Employee(id, name));
}
cursor.close();
return data;
}
}
Its my Custom Adapter:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.EmpDataViewHolder> {
final bank ban = new bank(CustomAdapter.this.context);
private ArrayList<Employee> arr,filterlist;
private Context context;
public CustomAdapter(Context context, ArrayList<Employee> arr) {
this.arr=arr;
this.context=context;
Toast.makeText(context,""+arr.size(),Toast.LENGTH_LONG).show();
}
#Override
public EmpDataViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.cardview, parent, false);
EmpDataViewHolder edvh = new EmpDataViewHolder(v);
return edvh;
}
#Override
public void onBindViewHolder(EmpDataViewHolder holder, int position) {
Employee emp=arr.get(position) ;
holder.id.setText(emp.getId());
holder.name.setText(emp.getName());
holder.cv.setTag(R.string.KeyForCV,position);
}
#Override
public int getItemCount() {
return arr.size();
}
public class EmpDataViewHolder extends RecyclerView.ViewHolder {
CardView cv;
TextView id;
TextView name;
public EmpDataViewHolder(View itemView) {
super(itemView);
cv= (CardView) itemView.findViewById(R.id.cv);
id= (TextView) itemView.findViewById(R.id.id);
name= (TextView) itemView.findViewById(R.id.name);
}
}
}
Do help me i want to get rid out of this problem thank you in advance
Hello i am a beginner in android programming. i have this recipe app with sqlite database. i am already done making the context menu with add to favorites on it. My problem is that i dont know how will i put the selected recipe to my dbase table named "favorites".. based on the TOAST i am already getting the position of the listview.
this is my main activity class
public class MainActivity extends Activity {
protected ListView lv;
protected ListAdapter adapter;
SQLiteDatabase db;
Cursor cursor;
EditText et_db;
int itemPos;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
db = (new DB_Resep(this)).getWritableDatabase();
lv = (ListView) findViewById(R.id.lv);
et_db = (EditText) findViewById(R.id.et);
registerForContextMenu(lv);
try {
cursor = db.rawQuery("SELECT * FROM recipe ORDER BY name ASC", null);
adapter = new SimpleCursorAdapter(this, R.layout.isi_lv, cursor,
new String[] { "name", "ingredients", "img" }, new int[] {
R.id.tv_nama, R.id.tvBahan, R.id.imV });
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
detail(position);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressWarnings("deprecation")
public void search_db(View v) {
String edit_db = et_db.getText().toString();
if (!edit_db.equals("")) {
try {
cursor = db.rawQuery("SELECT * FROM recipe WHERE name LIKE ?",new String[] { "%" + edit_db + "%" });
adapter = new SimpleCursorAdapter(this,R.layout.isi_lv,cursor,
new String[] { "name", "ingredients", "img" },
new int[] { R.id.tv_nama, R.id.tvBahan, R.id.imV });
if (adapter.getCount() == 0) {
Toast.makeText(
this,
"No Data Found " + edit_db
+ "", Toast.LENGTH_SHORT).show();
} else {
lv.setAdapter(adapter);
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
try {
cursor = db.rawQuery("SELECT * FROM recipe ORDER BY name ASC",
null);
adapter = new SimpleCursorAdapter(
this,
R.layout.isi_lv,
cursor,
new String[] { "name", "ingredients", "img" },
new int[] { R.id.tv_nama, R.id.tvBahan, R.id.imV });
lv.setAdapter(adapter);
lv.setTextFilterEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void detail(int position) {
int im = 0;
String _id = "";
String name = "";
String ingredients = "";
String procedure = "";
if (cursor.moveToFirst()) {
cursor.moveToPosition(position);
im = cursor.getInt(cursor.getColumnIndex("img"));
name = cursor.getString(cursor.getColumnIndex("name"));
ingredients = cursor.getString(cursor.getColumnIndex("ingredients"));
procedure = cursor.getString(cursor.getColumnIndex("procedure"));
}
Intent iIntent = new Intent(this, DB_Parse.class);
iIntent.putExtra("dataIM", im);
iIntent.putExtra("dataname", name);
iIntent.putExtra("dataBahan", ingredients);
iIntent.putExtra("dataCara", procedure);
setResult(RESULT_OK, iIntent);
startActivityForResult(iIntent, 99);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu,menu);
}
#SuppressLint("ShowToast") #Override
public boolean onContextItemSelected(MenuItem item) {
// TODO Auto-generated method stub
AdapterContextMenuInfo info =(AdapterContextMenuInfo)item.getMenuInfo();
itemPos = info.position;
ContentValues values = new ContentValues();
switch (item.getItemId()) {
case R.id.addtofavorites:
Toast.makeText(getBaseContext(), "Added to Favorites"+itemPos, Toast.LENGTH_SHORT).show();
return true;
default:
return super.onContextItemSelected(item);
}
}
}
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long rowId) {
TextView id = (TextView) arg1.findViewById(R.id.listselectedid);
String strId=id.getText().toString;
dbutil.addData(strId); // adding that string into local db
}
}
Instead of adding to database you can convert the list item to json and put it in shared preferences
Create a class sharedpreference.java like this
public class SharedPreference
{
public static final String PREFS_NAME = "MY_APP";
public static final String FAVORITES = "MY_Favorite";
public SharedPreference(){
super();
}
public void saveFavorites(Context context, List<CodeList> favorites){
SharedPreferences settings;
Editor editor;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
editor = settings.edit();
Gson gson = new Gson();
String jsonFavorites = gson.toJson(favorites);
editor.putString(FAVORITES, jsonFavorites);
editor.commit();
}
public void addFavorite(Context context, CodeList code){
List<CodeList> favorites = getFavorites(context);
if(favorites == null)
favorites = new ArrayList<CodeList>();
favorites.add(code);
saveFavorites(context,favorites);
}
public void removeFavorite(Context context, CodeList code) {
ArrayList<CodeList> favorites = getFavorites(context);
if (favorites != null) {
favorites.remove(code);
saveFavorites(context, favorites);
}
}
public ArrayList<CodeList> getFavorites(Context context) {
SharedPreferences settings;
List<CodeList> favorites;
//ArrayList<CodeList> favorites;
settings = context.getSharedPreferences(PREFS_NAME,
Context.MODE_PRIVATE);
if (settings.contains(FAVORITES)) {
String jsonFavorites = settings.getString(FAVORITES, null);
Gson gson = new Gson();
CodeList[] favoriteItems = gson.fromJson(jsonFavorites,
CodeList[].class);
favorites = Arrays.asList(favoriteItems);
favorites = new ArrayList<CodeList>(favorites);
//favorites = new ArrayList<CodeList>();
//favorites.addAll(Arrays.asList(favoriteItems));
} else
return null;
return (ArrayList<CodeList>) favorites;
//return favorites;
}
}
THEN ON FAVORITES BUTTON USE addfavorites method to your list item
DONT FORGET TO ADD GSONLIBRARY AS A DEPENCY IN YOURGRADLE
I did some changes in my code and it runs but I didn't get appropriate output. I create a method.
public void fetchData() {
dbHandler = new CourseDbHandler(this,null,null,1);
List<CreateCourse> course_data = dbHandler.getdata();
String[] data = new String[course_data.size()];
int i=0;
for(CreateCourse co : course_data)
{
data[i] = co.getCourseSelected();
i++;
}
courseList = (ListView) findViewById(R.id.CourselistView);
courseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, data);
courseList.setAdapter(courseAdapter);
courseAdapter.notifyDataSetChanged();
}
in this method i used dbHandler.getdata method, which is as follows
public List<CreateCourse> getdata() throws NullPointerException {
String dbString = "";
String course;
String sec;
List<CreateCourse> list = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_COURSE +";";
Cursor c = db.rawQuery(query,null);
c.moveToFirst();
if(c.equals(null)){
System.out.println("NO DATA");
return null;
}
else {
do {
course = c.getString(1);
sec = c.getString(2);
dbString = course+" "+sec;
CreateCourse co = new CreateCourse();
co.setCourseSelected(dbString);
list.add(new CreateCourse(c.getString(1), c.getString(2)));
}while (c.moveToNext());
}
db.close();
return list;
}
These are the getter and setter method
public void setCourseSelected(String courSelected) {
courseSelected = courSelected;
}
public String getCourseSelected() {
System.out.println(courseSelected);
return courseSelected;
}
It gives an error unfortunately app has stopped.
Create a class with your data:
public class Course {
public String id;
public String course;
public String sec;
public Course (String id, String course, String sec) {
this.id = id;
this.course = course;
this.sec = sec;
}
Then modify your method to return List of your data:
public List<Course> getdata() throws NullPointerException {
List<Course> list = new ArrayList<>();
SQLiteDatabase db = getWritableDatabase();
String query = "SELECT * FROM " + TABLE_COURSE +";";
Cursor c = db.rawQuery(query,null);
c.moveToFirst();
if(c.equals(null)){
System.out.println("NO DATA");
return null;
}
else {
do {
list.add(new Course(c.getString(0), c.getString(1), c.getString(2)));
}while (c.moveToNext());
}
db.close();
return list;
}
Then you can use this List with ArrayAdapter to show your data in ListView.
I changed all the code and solve my problem in above code.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_course);
dbHandler = new CourseDbHandler(this, null, null, 1);
Cursor c = dbHandler.getData();
c.moveToFirst();
// System.out.println("Select");
if(c.equals(null)){
System.out.println("NO DATA");
}
else {
if(c.moveToFirst()) {
do {
dbString=null;
course = c.getString(1);
sec = c.getString(2);
dbString = course + " " + sec;
courseItem.add(dbString);
} while (c.moveToNext());
}
}
courseList = (ListView) findViewById(R.id.CourselistView);
courseAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, courseItem);
courseList.setAdapter(courseAdapter);
courseAdapter.notifyDataSetChanged();
}
Thank you for your help..