I am really stuck and have no idea what to do. I have looked into startActivityForResult and Content providers and I have no clue how to implement any of them for this app.
I am not seeing how to get the data from the database and update the displayBottomList using same listview so I don't have to redirect the user to a new layout/activity. Not sure if I can even call a new query and set that to a different cursor and switch between them. I have seen swapCursor but how does that work when using the same adapter?
I have a ListView that I want to refresh with new data from a web service call when the user clicks on a row within the list. I am using a CursorAdapter. I can get the data correctly onClick of the row.
Where I am stuck, is how do I update that listView to repopulate with the new info from the database/response without sending me to another Activity. I want the user to stay on the same screen but just update the listView with the new data.
Not sure how to get the adapter to notify the adapter to update and populate a new ListView when the onClick is in the adapter, but the ListView is being created in the MainActivity.
The Adapter for BottomListView, the one I want to update when a row is clicked.
public class BottomListViewAdapter extends CursorAdapter {
private String mEmployeeNumber;
private EmployeeDBHandler dbHandler;
public BottomListViewAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.contact_cardview_layout, parent, false);
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
dbHandler = new EmployeeDBHandler(context);
ViewHolder holder;
holder = new ViewHolder();
holder.tvFirstName = (TextView) view.findViewById(R.id.personFirstName);
holder.tvLastName = (TextView) view.findViewById(R.id.personLastName);
holder.tvTitle = (TextView) view.findViewById(R.id.personTitle);
holder.mPeepPic = (ImageView) view.findViewById(R.id.person_photo);
holder.mDetailsButton = (ImageButton) view.findViewById(R.id.fullDetailButton);
holder.mCardView = (CardView) view.findViewById(R.id.home_screen_cardView);
String mFirstName = cursor.getString(cursor.getColumnIndexOrThrow("First_name"));
String mLastName = cursor.getString(cursor.getColumnIndexOrThrow("Last_name"));
String mTitle = cursor.getString(cursor.getColumnIndexOrThrow("Payroll_title"));
String mThumbnail = cursor.getString(cursor.getColumnIndexOrThrow("ThumbnailData"));
holder.tvFirstName.setText(mFirstName);
holder.tvLastName.setText(mLastName);
holder.tvTitle.setText(mTitle);
if (mThumbnail != null) {
byte[] imageAsBytes = Base64.decode(mThumbnail.getBytes(), Base64.DEFAULT);
Bitmap parsedImage = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
holder.mPeepPic.setImageBitmap(parsedImage);
} else {
holder.mPeepPic.setImageResource(R.drawable.img_place_holder_adapter);
}
final int position = cursor.getPosition();
holder.mDetailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
cursor.moveToPosition(position);
String mEmployeeNumber = cursor.getString(1);
String mEmail = cursor.getString(8);
String mFirstName = cursor.getString(2);
String mLastName = cursor.getString(3);
String mPhoneMobile = cursor.getString(4);
String mPhoneOffice = cursor.getString(5);
String mCostCenter = cursor.getString(10);
String mHasDirectReports = cursor.getString(7);
String mTitle = cursor.getString(6);
String mPic = cursor.getString(9);
Intent mIntent = new Intent(context, EmployeeFullInfo.class);
mIntent.putExtra("Employee_number", mEmployeeNumber);
mIntent.putExtra("Email", mEmail);
mIntent.putExtra("First_name", mFirstName);
mIntent.putExtra("Last_name", mLastName);
mIntent.putExtra("Phone_mobile", mPhoneMobile);
mIntent.putExtra("Phone_office", mPhoneOffice);
mIntent.putExtra("Cost_center_id", mCostCenter);
mIntent.putExtra("Has_direct_reports", mHasDirectReports);
mIntent.putExtra("Payroll_title", mTitle);
mIntent.putExtra("ThumbnailData", mPic);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
view.getContext().startActivity(mIntent);
}
});
holder.mCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cursor.moveToPosition(position);
mEmployeeNumber = cursor.getString(1);
Toast.makeText(context, mEmployeeNumber, Toast.LENGTH_SHORT).show();
callNewDirectReport();
notifyDataSetChanged();
}
});
}
public static class ViewHolder {
TextView tvFirstName;
TextView tvLastName;
TextView tvTitle;
ImageView mPeepPic;
ImageButton mDetailsButton;
CardView mCardView;
}
private void callNewDirectReport() {
String mDirectReportUrl = "mURL";
HttpUrl.Builder urlBuilder = HttpUrl.parse(mDirectReportUrl).newBuilder();
urlBuilder.addQueryParameter("manager_employee_number", mEmployeeNumber);
String url = urlBuilder.build().toString();
OkHttpClient client = getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
}
});
}
#Override
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
}
My MainActivity that is calling the adapter
public class MainActivity extends AppCompatActivity {
private ProgressBar mProgressBar;
private BottomListViewAdapter mBottomAdapter;
private View mDividerView;
EmployeeDBHandler dbHandler;
private int mStartingEmployeeID = mStartingID;
private String table = "employees";
private static final int LOADER_INTEGER = 1;
private Cursor mBottomCursor, mTopCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mDividerView = findViewById(R.id.divider);
dbHandler = new EmployeeDBHandler(getApplicationContext());
mProgressBar.setVisibility(View.VISIBLE);
mDividerView.setVisibility(View.GONE);
getXMLData();
//GUI for seeing android SQLite Database in Chrome Dev Tools
Stetho.InitializerBuilder inBuilder = Stetho.newInitializerBuilder(this);
inBuilder.enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this));
Stetho.Initializer in = inBuilder.build();
Stetho.initialize(in);
}
public void getXMLData() {
OkHttpClient client = getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url(getString(R.string.API_FULL_URL))
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressBar.setVisibility(View.GONE);
mDividerView.setVisibility(View.VISIBLE);
displayTopList();
displayBottomList();
}
});
}
});
}
public void displayTopList() {
SQLiteDatabase db = dbHandler.getWritableDatabase();
mTopCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " + "Employee_number" + "=" + mStartingEmployeeID, null);
ListView mTopListView = (ListView) findViewById(R.id.mTopList);
TopListCursorAdapter topAdapter = new TopListCursorAdapter(this, mTopCursor);
mTopListView.setAdapter(topAdapter);
}
public void displayBottomList() {
SQLiteDatabase db = dbHandler.getWritableDatabase();
mBottomCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " +
"Employee_number" + "!=" + mStartingEmployeeID + " AND " +
"Manager_employee_number" + "=" + mStartingEmployeeID + " ORDER BY " +
"Last_name" + " ASC", null);
ListView mBottomListView = (ListView) findViewById(R.id.mDirectReportList);
mBottomAdapter = new BottomListViewAdapter(this, mBottomCursor);
mBottomListView.setAdapter(mBottomAdapter);
mBottomAdapter.notifyDataSetChanged();
}
}
Right now your code in callNewDirectReport() makes an API request and stores the results in the database. This will not update the adapter to show the new items, instead you need to requery the database and get a newer Cursor. Below is an example of how you may do it:
public class BottomListViewAdapter extends CursorAdapter {
private String mEmployeeNumber;
private EmployeeDBHandler dbHandler;
private Activity activityRef;
public BottomListViewAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
// keep a reference to the activity
activityRef = (Activity) context;
}
//...
private void callNewDirectReport() {
//...
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
// the new items are in the database so requery the database to get a new fresher Cursor:
SQLiteDatabase db = dbHandler.getWritableDatabase();
Cursor fresherCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " +
"Employee_number" + "!=" + mStartingEmployeeID + " AND " +
"Manager_employee_number" + "=" + mStartingEmployeeID + " ORDER BY " +
"Last_name" + " ASC", null);
//change the adapter's Cursor
activityRef.runOnUiThread(new Runnable() {
public void run() {
swapCursor(freshedCursor);
}
});
}
});
}
}
You can use startActivityForResult to receive a callback from an activity, here you have a tutorial explaining how to use it: https://developer.android.com/training/basics/intents/result.html
When you receive the callback in the onActivityResult, you can update your data and call notifyDatasetChanged.
You can't call code from an activity in another because activities are handled by android. Android could have killed the activity that you are trying to call and will just recreate it when necessary.
Related
I have a textview that gets data from sqlite database but when I delete a row,or change it ,I also want to change what the textview has,the data the textview contains is basically the sum of all rows specific column,so how can I update the textview when updating sqlite data?
here is my main code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_logged_in);
getSupportActionBar().hide();
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
tinyDB = new TinyDB(getApplicationContext());
listView = findViewById(R.id.listt);
pharmacynme = findViewById(R.id.pharmacynme);
constraintLayout = findViewById(R.id.thelayout);
mBottomSheetDialog2 = new Dialog(LoggedIn.this, R.style.MaterialDialogSheet);
inflater2 = (LayoutInflater) LoggedIn.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mBottomSheetDialog = new Dialog(LoggedIn.this, R.style.MaterialDialogSheet);
content = inflater2.inflate(R.layout.activity_main2, null);
content2 = inflater2.inflate(R.layout.smalldialog, null);
total = (TextView) content2.findViewById(R.id.totalpriceofsmalldialog);
pharmacydescrr = findViewById(R.id.pharmacydiscribtion);
String nme = getIntent().getStringExtra("pharmacy_name");
String diskr = getIntent().getStringExtra("pharmacy_disk");
pharmacydescrr.setText(diskr);
pharmacynme.setText(nme);
//Listview Declaration
connectionClass = new ConnectionClass();
itemArrayList = new ArrayList<ClassListItems>();// Connection Class Initialization
etSearch = findViewById(R.id.etsearch);
etSearch.setSingleLine(true);
chat = findViewById(R.id.chat);
mDatabaseHelper = new DatabaseHelper(this);
mBottomSheetDialog2.setContentView(content2);
mBottomSheetDialog2.setCancelable(false);
mBottomSheetDialog2.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog2.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog2.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
mBottomSheetDialog2.getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
System.out.println("IDKSDKASDJKAS"+mDatabaseHelper.ifExists());
if (mDatabaseHelper.ifExists()){
mBottomSheetDialog2.show();
total.setText(mDatabaseHelper.getPriceSum());
}else {
}
chat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nameid = getIntent().getStringExtra("nameid");
Intent intent = new Intent(LoggedIn.this,ChatActivity.class);
intent.putExtra("nameid",nameid);
startActivity(intent);
}
});
etSearch.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void afterTextChanged(Editable s) {
String text = etSearch.getText().toString().toLowerCase(Locale.getDefault());
// myAppAdapter.filter(text);
}
});
SyncData orderData = new SyncData();
orderData.execute("");
}
public void AddData(String newEntry,String price,String amount){
boolean insertData = mDatabaseHelper.addData(newEntry,price,amount);
if (insertData){
toastMessage("Data Successfully inserted!");
}else {
toastMessage("Al anta 4abebto da ya youssef >:(");
}
}
private void toastMessage(String message){
Toast.makeText(this,message,Toast.LENGTH_LONG).show();
}
private class SyncData extends AsyncTask<String, String, String> {
String msg;
ProgressDialog progress;
#Override
protected void onPreExecute() //Starts the progress dailog
{
progress = ProgressDialog.show(LoggedIn.this, "Loading...",
"Please Wait...", true);
}
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
runOnUiThread(new Runnable() {
public void run() {
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
String nme = getIntent().getStringExtra("pharmacy_name");
System.out.println(nme);
String query = "Select StoreArabicName,StoreEnglishName,StoreSpecialty,StoreCountry,StoreLatitude,StoreLongitude,Store_description,ProductData.ProductArabicName,ProductData.ProductImage,ProductData.ProductEnglishName,ProductData.ProductDescription,ProductData.ProductPrice FROM StoresData INNER JOIN ProductData ON StoresData.StoreID = ProductData.StoreID WHERE StoreEnglishName = '"+nme+"'";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListItems(rs.getString("ProductEnglishName"), rs.getString("ProductDescription"), rs.getString("ProductPrice"),rs.getString("ProductImage")));
System.out.println(rs.getString("ProductImage"));
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
}
});
return msg;
}
#Override
protected void onPostExecute(String msg) // disimissing progress dialoge, showing error and setting up my listview
{
progress.dismiss();
if (msg!=null){
Toast.makeText(LoggedIn.this, msg + "", Toast.LENGTH_LONG).show();
}
if (!success) {
} else {
try {
myAppAdapter = new MyAppAdapter(itemArrayList, LoggedIn.this);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setAdapter(myAppAdapter);
} catch (Exception ex) {
}
}
}
}
public class MyAppAdapter extends BaseAdapter//has a class viewholder which holds
{
private ArrayList<ClassListItems> mOriginalValues; // Original Values
private ArrayList<ClassListItems> mDisplayedValues;
public class ViewHolder {
TextView textName;
TextView textData;
TextView textImage;
ImageView producticon;
}
public List<ClassListItems> parkingList;
public Context context;
ArrayList<ClassListItems> arraylist;
private MyAppAdapter(List<ClassListItems> apps, Context context) {
this.parkingList = apps;
this.context = context;
arraylist = new ArrayList<ClassListItems>();
arraylist.addAll(parkingList);
}
#Override
public int getCount() {
return parkingList.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, final View convertView, ViewGroup parent) // inflating the layout and initializing widgets
{
View rowView = convertView;
ViewHolder viewHolder = null;
if (rowView == null) {
LayoutInflater inflater = getLayoutInflater();
rowView = inflater.inflate(R.layout.listcontent, parent, false);
viewHolder = new ViewHolder();
viewHolder.textName = rowView.findViewById(R.id.name);
viewHolder.textData = rowView.findViewById(R.id.details);
viewHolder.textImage = rowView.findViewById(R.id.sdadprice);
viewHolder.producticon = rowView.findViewById(R.id.producticon);
rowView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// here setting up names and images
viewHolder.textName.setText(parkingList.get(position).getProname() + "");
viewHolder.textData.setText(parkingList.get(position).getData());
viewHolder.textImage.setText(parkingList.get(position).getImage());
Picasso.with(context).load(parkingList.get(position).getProducticon()).into(viewHolder.producticon);
mBottomSheetDialog.setCancelable(true);
mBottomSheetDialog.getWindow().setLayout(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
mBottomSheetDialog.getWindow().setGravity(Gravity.BOTTOM);
mBottomSheetDialog.setContentView(content);
total.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(LoggedIn.this,Listitemsbought.class);
startActivity(intent);
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
//What happens when you click on a place!
// Intent intent = new Intent(LoggedIn.this,MapsActivity.class);
// startActivity(intent);
final int count = 0;
final Float allitemscount = Float.parseFloat(parkingList.get(position).getImage());
TextView textView = (TextView) content.findViewById(R.id.mebuyss);
final TextView itemcount = (TextView) content.findViewById(R.id.itemcount);
Button plus = (Button) content.findViewById(R.id.plus);
Button minus = (Button) content.findViewById(R.id.minus);
Button finish = (Button) content.findViewById(R.id.finishgettingitem);
textView.setText(parkingList.get(position).getProname());
plus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter = counter + 1;
itemcount.setText(String.valueOf(counter));
}
});
minus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter --;
if(counter<0){
counter=0;
}
itemcount.setText(String.valueOf(counter));
}
});
finish.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String get = itemcount.getText().toString();
Float last = Float.parseFloat(get) * Float.parseFloat(parkingList.get(position).getImage());
mBottomSheetDialog.dismiss();
AddData(parkingList.get(position).getProname(),String.valueOf(last),String.valueOf(counter));
total.setText(mDatabaseHelper.getPriceSum());
mBottomSheetDialog2.show();
doneonce = true;
}
});
// if (doneonce = true){
// Float priceofitem = parseFloat(parkingList.get(position).getImage());
// Float currentprice = parseFloat(total.getText().toString());
// Float finalfloat = priceofitem * currentprice;
// total.setText(String.valueOf(finalfloat));
//
// }
if (!mBottomSheetDialog.isShowing()){
counter = 1;
}
//
mBottomSheetDialog.show();
// if (tinyDB.getString("selecteditem").equals("English")){
// Toast.makeText(LoggedIn.this,"Sorry this ability isn't here yet",Toast.LENGTH_LONG).show();
// }else {
// Toast.makeText(LoggedIn.this,"عفوا هذه الخاصية ليست متوفرة حاليا",Toast.LENGTH_LONG).show();
// }
}
});
return rowView;
}
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
itemArrayList.clear();
if (charText.length() == 0) {
itemArrayList.addAll(arraylist);
} else {
for (ClassListItems st : arraylist) {
if (st.getProname().toLowerCase(Locale.getDefault()).contains(charText)) {
itemArrayList.add(st);
}
}
}
notifyDataSetChanged();
}
}
private Float parseFloat(String s){
if(s == null || s.isEmpty())
return 0.0f;
else
return Float.parseFloat(s);
}
And here is my DatabaseHelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
private static final String TAG = "DatabaseHelper";
private static final String TABLE_NAME = "DatabaseHelper";
private static final String NAME = "Name";
private static final String PRICE = "Price";
private static final String AMOUNT = "Amount";
public DatabaseHelper(Context context) {
super(context, TABLE_NAME, null , 4);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " ("+PRICE+" TEXT, "+ NAME + " TEXT,"+ AMOUNT +" TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+ TABLE_NAME);
onCreate(db);
}
public boolean addData(String item, String Price,String amount){
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(PRICE,Price);
contentValues.put(NAME, item);
contentValues.put(AMOUNT, amount);
Log.d(TAG, "addData: Adding " + item + " to " + TABLE_NAME);
long insert = db.insert(TABLE_NAME,null,contentValues);
if (insert == -1){
return false;
}else {
return true;
}
}
public Cursor getDataOfTable(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT Name,Amount FROM " + TABLE_NAME ;
Cursor data = db.rawQuery(query, null);
return data;
}
public String getPriceSum(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT COALESCE(SUM(Price), 0) FROM " + TABLE_NAME;
Cursor price = db.rawQuery(query, null);
String result = "" + price.getString(0);
price.close();
db.close();
return result;
}
public boolean ifExists()
{
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = null;
String checkQuery = "SELECT * FROM " + TABLE_NAME + " LIMIT 1";
cursor= db.rawQuery(checkQuery,null);
boolean exists = (cursor.getCount() > 0);
cursor.close();
return exists;
}
public void delete(String nameofrow) {
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+TABLE_NAME+" where "+NAME+"='"+nameofrow+"'");
}
}
Any help?!
The method getPriceSum() should return the sum and not a Cursor:
public String getPriceSum(){
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT COALESCE(SUM(Price), 0) FROM " + TABLE_NAME;
Cursor c = db.rawQuery(query, null);
String result = "";
if (c.moveToFirst()) result = "" + c.getString(0);
c.close();
db.close();
return result;
}
I don't think that you need the if block:
if (mDatabaseHelper.ifExists()) {
.......................
}
All you need to do is:
total.setText(mDatabaseHelper.getPriceSum());
Passing the cursor of position clicked but when doing so log is showing me I am getting only the first row no matter where I click.
holder.mTopCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mCallback != null) {
mCallback.onTopListClick(cursor);
notifyDataSetChanged();
Log.i("FROMCLICK", DatabaseUtils.dumpCursorToString(cursor));
}
}
});
The log inside the CursorAdapter onClickListener is showing only the first rows cursor even if I click 20 rows down the list.
#Override
public void onTopListClick(Cursor cursor) {
Log.i("FistClickBeforePassing", DatabaseUtils.dumpCursorToString(cursor));
BottomFragment bottomFragment = (BottomFragment) getSupportFragmentManager().findFragmentById(R.id.bottomFragment);
bottomFragment.refreshList(cursor);
}
Same thing here before passing to the BottomFragment.
public void refreshList(Cursor cursor) {
Log.i("RIGHTBEFOREREFRESH", DatabaseUtils.dumpCursorToString(cursor));
String mEmployeeNumber = cursor.getString(1);
Log.i("REFRESHLISTNUMBER", mEmployeeNumber);
dbHandler = EmployeeDBHandler.getInstance(getContext());
db = dbHandler.getReadableDatabase();
mNewBottomCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " +
/*"Employee_number" + "!=" + mStartingEmployeeID + " AND " +*/
"Manager_employee_number" + "=" + mEmployeeNumber + " ORDER BY " +
"Last_name" + " ASC", null);
Log.i("THECURSOR ", DatabaseUtils.dumpCursorToString(mNewBottomCursor));
BottomListCursorAdapter bottomListCursorAdapter = new BottomListCursorAdapter(getActivity(), cursor);
bottomListCursorAdapter.swapCursor(mNewBottomCursor);
mBottomListView.setAdapter(bottomListCursorAdapter);
}
}
Get the same cursor here for the log but do not get the same employee_number the cursor has for the REFRESHLISTNUMBER log statement. That is a random number from the list.
Not sure why the cursor isnt being passed correctly. I have a details button on each row that displays info from the cursor for each row and that is displaying correctly.
Completed Top Adapter
public class TopListCursorAdapter extends CursorAdapter {
public interface TopListClickListener {
void onTopListClick(Cursor cursor);
}
private TopListClickListener mCallback;
public TopListCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
if(!(context instanceof TopListClickListener)) {
throw new ClassCastException("Content must implement BottomListClickListener");
}
this.mCallback = (TopListClickListener) context;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.contact_cardview_top, parent, false);
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
ViewHolder holder;
holder = new ViewHolder();
holder.tvFirstName = (TextView) view.findViewById(R.id.personFirstName);
holder.tvLastName = (TextView) view.findViewById(R.id.personLastName);
holder.tvTitle = (TextView) view.findViewById(R.id.personTitle);
holder.mPeepPic = (ImageView) view.findViewById(R.id.person_photo);
holder.mDetailsButton = (ImageButton) view.findViewById(R.id.fullDetailButton);
holder.mTopCardView = (CardView) view.findViewById(R.id.mTopHomeScreenCV);
String mFirstName = cursor.getString(cursor.getColumnIndexOrThrow("First_name"));
String mLastName = cursor.getString(cursor.getColumnIndexOrThrow("Last_name"));
String mPayrollTitle = cursor.getString(cursor.getColumnIndexOrThrow("Payroll_title"));
String mThumbnail = cursor.getString(cursor.getColumnIndexOrThrow("ThumbnailData"));
holder.tvFirstName.setText(mFirstName);
holder.tvLastName.setText(mLastName);
holder.tvTitle.setText(mPayrollTitle);
if (mThumbnail != null) {
byte[] imageAsBytes = Base64.decode(mThumbnail.getBytes(), Base64.DEFAULT);
Bitmap parsedImage = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
holder.mPeepPic.setImageBitmap(parsedImage);
} else {
holder.mPeepPic.setImageResource(R.drawable.img_place_holder_adapter);
}
final int position = cursor.getPosition();
holder.mDetailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cursor.moveToPosition(position);
String mEmployeeNumber = cursor.getString(cursor.getColumnIndex("Employee_number"));
String mFirstName = cursor.getString(cursor.getColumnIndex("First_name"));
String mLastName = cursor.getString(cursor.getColumnIndex("Last_name"));
String mTitle = cursor.getString(cursor.getColumnIndex("Payroll_title"));
String mPic = cursor.getString(cursor.getColumnIndex("ThumbnailData"));
String mEmail = cursor.getString(cursor.getColumnIndex("Email"));
String mPhoneMobile = cursor.getString(cursor.getColumnIndex("Phone_mobile"));
String mPhoneOffice = cursor.getString(cursor.getColumnIndex("Phone_office"));
String mCostCenter = cursor.getString(cursor.getColumnIndex("Cost_center_id"));
String mHasDirectReports = cursor.getString(cursor.getColumnIndex("Has_direct_reports"));
String mManagerNumber = cursor.getString(cursor.getColumnIndex("Manager_employee_number"));
Intent mIntent = new Intent(context, EmployeeFullInfo.class);
mIntent.putExtra("Employee_number", mEmployeeNumber);
mIntent.putExtra("First_name", mFirstName);
mIntent.putExtra("Last_name", mLastName);
mIntent.putExtra("Payroll_title", mTitle);
mIntent.putExtra("ThumbnailData", mPic);
mIntent.putExtra("Email", mEmail);
mIntent.putExtra("Phone_mobile", mPhoneMobile);
mIntent.putExtra("Phone_office", mPhoneOffice);
mIntent.putExtra("Cost_center_id", mCostCenter);
mIntent.putExtra("Has_direct_reports", mHasDirectReports);
mIntent.putExtra("Manager_employee_number", mManagerNumber);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(mIntent);
}
});
holder.mTopCardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(mCallback != null) {
mCallback.onTopListClick(cursor);
notifyDataSetChanged();
Log.i("FROMCLICK", DatabaseUtils.dumpCursorToString(cursor));
}
}
});
}
public static class ViewHolder {
TextView tvFirstName;
TextView tvLastName;
TextView tvTitle;
ImageView mPeepPic;
ImageButton mDetailsButton;
CardView mTopCardView;
}
}
public class TopFragment extends Fragment {
Cursor mTopCursor;
EmployeeDBHandler dbHandler;
ListView mTopListView;
TopListCursorAdapter mTopAdapter;
MatrixCursor customCursor1;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_top_list, container, false);
String table = "employees";
dbHandler = EmployeeDBHandler.getInstance(getContext());
SQLiteDatabase db = dbHandler.getWritableDatabase();
customCursor1 = new MatrixCursor(new String[]{"_id", "Employee_number", "First_name",
"Last_name", "Payroll_title", "ThumbnailData", "Email", "Phone_mobile", "Phone_office", "Cost_center_id",
"Has_direct_reports", "Manager_employee_number"});
int mStartingEmployeeID = mStartingNumber;
mTopCursor = db.rawQuery("SELECT * FROM " + table + " WHERE " + "Employee_number" + "=" + mStartingEmployeeID, null);
mTopListView = (ListView) view.findViewById(R.id.mTopList);
mTopAdapter = new TopListCursorAdapter(getContext(), mTopCursor);
mTopListView.setAdapter(mTopAdapter);
return view;
}
public void update(Cursor cursor) {
if (cursor.moveToNext()) {
customCursor1.addRow(new Object[]{cursor.getInt(0), cursor.getString(1), cursor.getString(2),
cursor.getString(3), cursor.getString(6), cursor.getString(9), cursor.getString(8), cursor.getString(4),
cursor.getString(5), cursor.getString(10), cursor.getString(7), cursor.getString(11)});
MergeCursor newCursor = new MergeCursor(new Cursor[]{mTopCursor, customCursor1});
mTopAdapter.swapCursor(newCursor);
mTopAdapter.notifyDataSetChanged();
scrollMyListToBottom();
customCursor1.close();
} cursor.moveToNext();
}
private void scrollMyListToBottom() {
mTopListView.post(new Runnable() {
#Override
public void run() {
mTopListView.setSelection(mTopAdapter.getCount() - 1);
}
});
}
}
Maybe something is happening with my MergeCursor in TopFragment that is messing with the curors? If so, not sure how to fix it or why it would be happening.
Fixed by adding a line of code to the setClickListener of the mTopCardView in the TopListCursorAdapter.
cursor.moveToPosition(position);
I am getting a callback in my main activity that is passing an object of values from a ListView click. If I throw a toast the toast is displaying the key, value pairs. I want to take that and add it to the TopListCursorAdapter to populate a new row. I am getting null on the topAdapter.notifyDataSetChanged();
Not sure how to add mEmployee to the adapter, I have tried to
#Override
public void onBottomListClick(Employee e) {
mEmployee.add(e);
dbHandler.addEmployee(e);
SQLiteDatabase db = dbHandler.getWritableDatabase();
final Cursor clickedEmployee = db.rawQuery("SELECT * FROM " + "employees" + " WHERE " +
"Employee_number" + "=" + e.getEmployee_number(), null);
// change the adapter's Cursor
topAdapter.changeCursor(clickedEmployee);
}
But I do not want to pass a cursor and the TopListCursorAdapter wants one. I just want to add mEmployee to the existing List in TopListCursorAdapter.
public class MainActivity extends FragmentActivity implements BottomListViewAdapter.BottomListClickListener {
private ProgressBar mProgressBar;
EmployeeDBHandler dbHandler;
private TopListCursorAdapter topAdapter;
private BottomListViewAdapter bottomAdapter;
private ArrayList mEmployee;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
dbHandler = new EmployeeDBHandler(getApplicationContext());
mProgressBar.setVisibility(View.VISIBLE);
getXMLData();
//GUI for seeing android SQLite Database in Chrome Dev Tools
Stetho.InitializerBuilder inBuilder = Stetho.newInitializerBuilder(this);
inBuilder.enableWebKitInspector(Stetho.defaultInspectorModulesProvider(this));
Stetho.Initializer in = inBuilder.build();
Stetho.initialize(in);
}
public void getXMLData() {
OkHttpClient client = getUnsafeOkHttpClient();
Request request = new Request.Builder()
.url(getString(R.string.API_FULL_URL))
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
final String responseData = response.body().string();
final InputStream stream = new ByteArrayInputStream(responseData.getBytes());
final XMLPullParserHandler parserHandler = new XMLPullParserHandler();
final ArrayList<Employee> employees = (ArrayList<Employee>) parserHandler.parse(stream);
for (Employee e : employees) {
dbHandler.addEmployee(e);
}
runOnUiThread(new Runnable() {
#Override
public void run() {
mProgressBar.setVisibility(View.GONE);
displayTopList();
displayBottomList();
}
});
}
});
}
public void displayTopList() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.topFragment, new TopFragment());
fragmentTransaction.commit();
}
public void displayBottomList() {
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.bottomFragment, new BottomFragment());
fragmentTransaction.commit();
}
#Override
public void onBottomListClick(Employee e) {
mEmployee.add(e);
dbHandler.addEmployee(e);
SQLiteDatabase db = dbHandler.getWritableDatabase();
final Cursor clickedEmployee = db.rawQuery("SELECT * FROM " + "employees" + " WHERE " +
"Employee_number" + "=" + e.getEmployee_number(), null);
// change the adapter's Cursor
topAdapter.changeCursor(clickedEmployee);
}
}
TopListCursorAdapter
public class TopListCursorAdapter extends CursorAdapter {
private EmployeeDBHandler dbHandler;
private Activity activityRef;
public TopListCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
activityRef = (Activity) context;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return LayoutInflater.from(context).inflate(R.layout.contact_cardview_layout, parent, false);
}
#Override
public void bindView(View view, final Context context, final Cursor cursor) {
dbHandler = new EmployeeDBHandler(context);
ViewHolder holder;
holder = new ViewHolder();
holder.tvFirstName = (TextView) view.findViewById(R.id.personFirstName);
holder.tvLastName = (TextView) view.findViewById(R.id.personLastName);
holder.tvTitle = (TextView) view.findViewById(R.id.personTitle);
holder.mPeepPic = (ImageView) view.findViewById(R.id.person_photo);
holder.mDetailsButton = (ImageButton) view.findViewById(R.id.fullDetailButton);
holder.mCardView = (CardView) view.findViewById(R.id.home_screen_cardView);
String mFirstName = cursor.getString(cursor.getColumnIndexOrThrow("First_name"));
String mLastName = cursor.getString(cursor.getColumnIndexOrThrow("Last_name"));
String mPayrollTitle = cursor.getString(cursor.getColumnIndexOrThrow("Payroll_title"));
String mThumbnail = cursor.getString(cursor.getColumnIndexOrThrow("ThumbnailData"));
holder.tvFirstName.setText(mFirstName);
holder.tvLastName.setText(mLastName);
holder.tvTitle.setText(mPayrollTitle);
if (mThumbnail != null) {
byte[] imageAsBytes = Base64.decode(mThumbnail.getBytes(), Base64.DEFAULT);
Bitmap parsedImage = BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
holder.mPeepPic.setImageBitmap(parsedImage);
} else {
holder.mPeepPic.setImageResource(R.drawable.img_place_holder_adapter);
}
activityRef.runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
final int position = cursor.getPosition();
holder.mDetailsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cursor.moveToPosition(position);
String mEmployeeNumber = cursor.getString(1);
String mEmail = cursor.getString(8);
String mFirstName = cursor.getString(2);
String mLastName = cursor.getString(3);
String mPhoneMobile = cursor.getString(4);
String mPhoneOffice = cursor.getString(5);
String mCostCenter = cursor.getString(10);
String mHasDirectReports = cursor.getString(7);
String mTitle = cursor.getString(6);
String mPic = cursor.getString(9);
Intent mIntent = new Intent(context, EmployeeFullInfo.class);
mIntent.putExtra("Employee_number", mEmployeeNumber);
mIntent.putExtra("Email", mEmail);
mIntent.putExtra("First_name", mFirstName);
mIntent.putExtra("Last_name", mLastName);
mIntent.putExtra("Phone_mobile", mPhoneMobile);
mIntent.putExtra("Phone_office", mPhoneOffice);
mIntent.putExtra("Cost_center_id", mCostCenter);
mIntent.putExtra("Has_direct_reports", mHasDirectReports);
mIntent.putExtra("Payroll_title", mTitle);
mIntent.putExtra("ThumbnailData", mPic);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
v.getContext().startActivity(mIntent);
}
});
}
public static class ViewHolder {
TextView tvFirstName;
TextView tvLastName;
TextView tvTitle;
ImageView mPeepPic;
ImageButton mDetailsButton;
CardView mCardView;
}
}
I do not want to pass a cursor and the TopListCursorAdapter wants one
Sure. You have a DBHandler which can give you a Cursor.
dbHandler = new EmployeeDBHandler(getApplicationContext());
And you have an addEmployee method.
dbHandler.addEmployee(e);
So the question is - how did you create the TopListCursorAdapter without already having a Cursor since it is required??
Anyways, you should not stick a EmployeeDBHandler in the adapter.
It only wants a Cursor. Plus, you never seem to use that class in there.
public class TopListCursorAdapter extends CursorAdapter {
// private EmployeeDBHandler dbHandler; // ** Not needed
private Context mContext; // Don't need an Activity
public TopListCursorAdapter(Context context, Cursor cursor) {
super(context, cursor, 0);
mContext = context; // Just a Context, no Activity
}
And you should never need to create a new TopListAdapter after the first creation of one, you can call changeCursor directly on the existing adapter.
#Override
public void onBottomListClick(Employee e) {
mEmployee.add(e);
dbHandler.addEmployee(e);
// topAdapter = new TopListCursorAdapter(); // ** Nope
Cursor newCursor = dbHandler.getEmployees(); // TODO: Implement this
topAdapter.changeCursor(newCursor); // Updates the UI itself
Intent employeeDetail = new Intent(MainActivity.this, EmployeeFullInfo.class);
employeeDetail.putExtra("Employee_number", e.getNumber());
...
startActivity(employeeDetail);
}
Note: If you use Parcelable Employee objects, you do not need a bunch putExtra and getExtra methods on the Intents.
Additionally, you can store an Employee object as part of the ViewHolder for simpler data management. That way, you only need to extract data from the Cursor into an Employee, then the ViewHolder can maintain that since you are duplicating the effort within onClick to get the Cursor data.
public static class ViewHolder {
Employee employee; // See here
TextView tvFirstName;
TextView tvLastName;
TextView tvTitle;
ImageView mPeepPic;
ImageButton mDetailsButton;
CardView mCardView;
}
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
Am working for first time with SQLite on android and i have some trouble , so what i want to do is insert a date into my DB,
then onCLickLinsten to insert then retrieve the data to sent them to another activity, just tryed this to understand and practice it, here is the second part of my code:
public class MainActivity extends AppCompatActivity {
private RequestQueue requestQueue;
private static final String URL = "http://192.168.1.104/sync_adapter.php";
private StringRequest request;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SQLiteDatabase myDB= null;
final String TableName = "Personne";
final String[] name1 = new String[1];
final EditText edi1 = (EditText) findViewById(R.id.edittext1);
final TextView text1 = (TextView) findViewById(R.id.textview1);
Button btn = (Button) findViewById(R.id.button);
Button btn2 = (Button) findViewById(R.id.button2);
myDB = this.openOrCreateDatabase("namesDB", MODE_PRIVATE, null);
myDB.execSQL("CREATE TABLE IF NOT EXISTS "
+ TableName
+ " (id INT(3),name VARCHAR );");
final SQLiteDatabase finalMyDB = myDB;
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
final String text2 = edi1.getText().toString();
requestQueue = Volley.newRequestQueue(MainActivity.this);
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONArray contacts = null;
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
contacts = jsonObject.getJSONArray("result");
JSONObject c = contacts.getJSONObject(0);
final String name = c.getString("nom");
Toast.makeText(MainActivity.this, "Mr "+name+" ID: "+text2, Toast.LENGTH_SHORT).show();
text1.setText(""+name);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
public void onErrorResponse(VolleyError error) {
}
}){
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> hashMap = new HashMap<String, String>();
hashMap.put("text2",text2);
return hashMap;
}
};
requestQueue.add(request);
}
});
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finalMyDB.execSQL("INSERT INTO "
+ TableName
+ " (id, name)"
+ " VALUES ('text2' ,'name');");
Cursor c = finalMyDB.rawQuery("SELECT name FROM " + TableName , null);
int Column1 = c.getColumnIndex("name");
c.moveToFirst();
if (c != null) {
// Loop through all Results
do {
name1[0] = c.getString(Column1);
}
while(c.moveToNext());
}
Intent i = new Intent(MainActivity.this,ResultActivity.class);
i.putExtra("name1", name1[0]);
startActivity(i);
}
});
}
am i doing it right ? thank's for help