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());
I am using an external SQlite database in my project and a Listview with simple adapter, in fact it works fine but i wanna show images in Listview using glide library. i stored images url in database but i don't know how can I pass it to glide , it's possible or not?
thanks in advance.
public class DatabaseHandler extends SQLiteOpenHelper {
private Context main_context;
private static String DB_PATH;
private static String DB_NAME = "ebook_db.db";
private static int DB_VERSION = 1;
private static String DB_TBL_BOOKS = "books";
private static String DB_TBL_SETTINGS = "settings";
private SQLiteDatabase db;
public DatabaseHandler(Context con) {
super(con, DB_NAME, null, DB_VERSION);
main_context = con;
DB_PATH = con.getCacheDir().getPath() + "/" + DB_NAME;
}
#Override
public void onCreate(SQLiteDatabase db) {
/* do nothing */
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/* do nothing */
}
private boolean dbExists() {
File f = new File(DB_PATH);
if (f.exists())
return true;
else
return false;
}
private boolean copyDB() {
try {
FileOutputStream out = new FileOutputStream(DB_PATH);
InputStream in = main_context.getAssets().open(DB_NAME);
byte[] buffer = new byte[1024];
int ch;
while ((ch = in.read(buffer)) > 0) {
out.write(buffer, 0, ch);
}
out.flush();
out.close();
in.close();
return true;
} catch (Exception e) {
/* do nothing */
return false;
}
}
public void open() {
if (dbExists()) {
try {
File temp = new File(DB_PATH);
db = SQLiteDatabase.openDatabase(
temp.getAbsolutePath(), null, SQLiteDatabase.OPEN_READWRITE
);
} catch (Exception e) {
/* do nothing */
}
} else {
if (copyDB())
open();
}
}
#Override
public synchronized void close() {
db.close();
}
public List<HashMap<String,Object>> getTableOfContent(String id) {
Cursor result = db.rawQuery("SELECT * FROM " + DB_TBL_BOOKS + " WHERE author = '" + id + "'", null);
List<HashMap<String, Object>> all_data = new ArrayList<>();
while (result.moveToNext()) {
HashMap<String,Object> temp = new HashMap<>();
temp.put("id", result.getString(0));
temp.put("title", result.getString(1));
temp.put("author", result.getString(3));
temp.put("image", result.getString(8));
if (result.getString(9).equals("1")) {
temp.put("fav_flag", R.drawable.is_favorite);
} else {
temp.put("fav_flag", R.drawable.not_favorite);
}
if (result.getString(10).equals("1")) {
temp.put("see_flag", R.drawable.see);
} else {
temp.put("see_flag", R.drawable.not_see);
}
all_data.add(temp);
}
return all_data;
}
tblOfContent.java
public class tblOfContent extends AppCompatActivity {
private ListView contentListView;
private List<HashMap<String, Object>> books_list;
private DatabaseHandler db;
public String my_key_number;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tbl_of_content);
getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);
Bundle extras = getIntent().getExtras();
if (extras != null) {
my_key_number = extras.getString("number_of_keys");
Toast.makeText(this, my_key_number, Toast.LENGTH_LONG).show();
}
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setHomeButtonEnabled(true);
//actionBar.setTitle(R.string.doctors_title);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
contentListView = findViewById(R.id.tblOfContentListView);
db = new DatabaseHandler(getBaseContext());
db.open();
books_list = db.getTableOfContent(my_key_number);
String[] from = {"title", "image", "fav_flag", "see_flag"};
int[] to = {R.id.txtTitle, R.id.url, R.id.setFav, R.id.setSee};
SimpleAdapter adb = new SimpleAdapter(
getBaseContext(), books_list, R.layout.foods_row_item, from, to
);
contentListView.setAdapter(adb);
db.close();
contentListView.setOnItemClickListener(
new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent i = new Intent(getBaseContext(), book_content.class);
String my_id = books_list.get(position).get("id").toString();
i.putExtra("id", my_id);
startActivity(i);
}
}
);
}
}
Try this:
String[] from = {"title", "fav_flag", "see_flag"};
int[] to = {R.id.txtTitle, R.id.setFav, R.id.setSee};
SimpleAdapter adb = new SimpleAdapter(getBaseContext(), books_list, R.layout.foods_row_item, from, to){
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = super.getView(position, convertView, parent);
String url = (String)((HashMap<String, Object>)getItem(position)).get("image");
ImageView imageView = (ImageView)itemView.findViewById(R.id.url);
Glide.with(this)
.load(url)
.into(imageView);
return itemView;
}
};
Hope it helps!
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
I want to insert data from a text file into SQLite database :
public class SyncActivity extends Activity {
...
private MessageDialogView dlg = null; // an AlertDialog showing a message
private Patienter wait = null; // an AlertDialog containing an imageview showing an animation-list
...
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.synchro);
...
dlg = new MessageDialogView(SyncActivity.this, getLayoutInflater());
wait = new Patienter(SyncActivity.this, getLayoutInflater());
...
}
public void synchroniser(View view) { // called when a button is clicked
wait.show();
new RequestTask().execute("http://192.168.1.8/impots/data/syncro/webVersAndroid/parcelles.txt");
}
private class RequestTask extends AsyncTask<String, Void, Void> {
private String err = "";
private boolean error = false;
private String[] enregs;
#Override
protected Void doInBackground(String... s_url) {
enregs = new String[s_url.length];
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
if(networkInfo != null) {
if (networkInfo.isAvailable() && networkInfo.isConnected()) {
System.setProperty("http.keepAlive", "false");
HttpURLConnection con = null;
BufferedReader reader = null;
for (int u=0; u<s_url.length; u++) {
String tmp;
String lines = "";
try {
URL url = new URL(s_url[u]);
if (url != null) {
con = (HttpURLConnection) url.openConnection();
if (con != null && con.getResponseCode() == HttpURLConnection.HTTP_OK) {
InputStream in = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(in));
boolean firstLine = true;
while ((tmp = reader.readLine()) != null) {
if (firstLine) {
firstLine = false;
lines += tmp;
}
else
lines += "\r\n" + tmp;
}
enregs[u] = lines;
}
}
} catch (MalformedURLException e) {
error = true;
err = getResources().getString(R.string.errBadUrl);
} catch (IOException e) {
error = true;
err = getResources().getString(R.string.errAccessError);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
if (con != null)
con.disconnect();
}
}
}
else {
error = true;
err = getResources().getString(R.string.errNotConnected);
}
} else {
error = true;
err = getResources().getString(R.string.errNoNetwork);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
if (error) {
wait.dismiss();
displayError(err);
} else {
populateDB();
wait.dismiss();
}
}
private void displayError(String msg) {
dlg.setTitre(getString(R.string.titreErrMsgBox));
dlg.setMsg(msg);
dlg.show();
}
private void populateDB() {
String[] enreg = SpliterString.Split(enregs[0], "\r\n"); // get each record of "parcelle"
db = new Db(SyncActivity.this).open();
for (int p=0; p<enreg.length; p++) {
Parcelle parcelle = new Parcelle(SpliterString.getColumnValueAt(enreg[p],0),
SpliterString.getColumnValueAt(enreg[p],1),
SpliterString.getColumnValueAt(enreg[p],2),
SpliterString.getColumnValueAt(enreg[p],3),
SpliterString.getColumnValueAt(enreg[p],4),
SpliterString.getColumnValueAt(enreg[p],5),
SpliterString.getColumnValueAt(enreg[p],6),
SpliterString.getColumnValueAt(enreg[p],7),
SpliterString.getColumnValueAt(enreg[p],8),
SpliterString.getColumnValueAt(enreg[p],9),
SpliterString.getColumnValueAt(enreg[p],10),
SpliterString.getColumnValueAt(enreg[p],11),
SpliterString.getColumnValueAt(enreg[p],12),
SpliterString.getColumnValueAt(enreg[p],13),
SpliterString.getColumnValueAt(enreg[p],14));
db.insertParcelle(parcelle);
}
db.close();
}
}
}
Data inside the text file is just one row ( data are represented like a csv but separator is | ) :
1||010-01-02|PARC-0001|PARCELLE DROUDOUDOU|10||2000.00|500.00|1500.00||10, Av Place de l'Independance - CENTRE VILLE|01/02/2000|10/02/2005|CENTRE VILLE|
The problem is that the AlertDialog is never dismissed ! There is no error ! So what is wrong ?
-- EDIT --
public class Patienter extends AlertDialog {
private View contenu;
AnimationDrawable frameAnimation = null;
public Patienter(Context context, LayoutInflater inflater) {
super(context);
contenu = inflater.inflate(R.layout.patienter, null);
setCancelable(false);
setCanceledOnTouchOutside(false);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(contenu);
ImageView img = (ImageView)contenu.findViewById(R.id.imgWait);
img.setBackgroundResource(R.drawable.wait);
frameAnimation = (AnimationDrawable) img.getBackground();
frameAnimation.start();
}
}
public class Db {
public static final String DB_NAME = "bdd_impot.bd", T_BIEN = "bien", T_PARCELLE = "parcelle", T_DECOUP_TERRIT = "decoupage_territoire";
public static int VERSION = 1;
private DbHelper DBHelper;
private SQLiteDatabase bd;
public Db(Context context) {
DBHelper = new DbHelper(context);
}
private class DbHelper extends SQLiteOpenHelper {
public DbHelper(Context context) {
super(context,DB_NAME, null, VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS "+T_BIEN+" (bien_code integer PRIMARY KEY AUTOINCREMENT,"
+ "bien_ident text,"
+ "bien_code_sig text);");
db.execSQL("CREATE TABLE IF NOT EXISTS "+T_PARCELLE+" (bien_code integer,"
+ "decoup_terri_code text,"
+ "dec_decoup_terri_code text,"
+ "bien_ident text,"
+ "parcel_denomination text,"
+ "parcel_porte_ppale text,"
+ "parcel_porte_second text,"
+ "parcel_superfi_totale numeric,"
+ "parcel_superf_batie numeric,"
+ "parcel_superf_non_batie numeric,"
+ "parcel_superf_plani numeric,"
+ "parcel_adresse text,"
+ "parcel_date_deb_construct text,"
+ "parcel_date_fin_construct text,"
+ "quartier_lib text);");
db.execSQL("CREATE TABLE IF NOT EXISTS "+T_DECOUP_TERRIT+" (decoup_terri_code TEXT PRIMARY KEY,"
+ "decoup_terri_nom TEXT);"); // rue
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS "+T_PARCELLE+";");
db.execSQL("DROP TABLE IF EXISTS "+T_DECOUP_TERRIT+";");
db.execSQL("DROP TABLE IF EXISTS "+T_BIEN+";");
onCreate(db);
}
}
public Db open() {
bd = DBHelper.getWritableDatabase();
return this;
}
public void close() {
bd.close();
}
public void insertBien(Bien b) {
ContentValues values = new ContentValues();
values.put("bien_ident", b.getBien_ident());
values.put("bien_code_sig", b.getBien_code_sig());
bd.insert(T_BIEN, null, values);
}
private int getBienLastInsertID() { // call this method after INSERT on table BIEN
Cursor c = bd.rawQuery("SELECT last_insert_rowid()", null);
if (c != null) {
c.moveToFirst();
int id = c.getInt(0);
c.close();
return id;
}
return 0;
}
public Parcelle getParcelle(int bien_code) {
Parcelle p = new Parcelle();
String[] columnsParcelle = {"bien_code","decoup_terri_code","dec_decoup_terri_code","bien_ident",
"parcel_denomination","parcel_porte_ppale","parcel_porte_second",
"parcel_superfi_totale","parcel_superf_batie","parcel_superf_non_batie",
"parcel_superf_plani","parcel_adresse","parcel_date_deb_construct","parcel_date_fin_construct","quartier_lib"};
Cursor c = bd.query(T_PARCELLE, columnsParcelle, "bien_code=?", new String[]{String.valueOf(bien_code)}, null, null, null);
if (c != null && c.getCount() > 0 ) {
c.moveToFirst();
p = new Parcelle(c.getString(0),c.getString(1),c.getString(2),c.getString(3),c.getString(4),c.getString(5),c.getString(6),c.getString(7),c.getString(8),c.getString(9),c.getString(10),c.getString(11),c.getString(12),c.getString(13),c.getString(14));
}
return p;
}
public ArrayList<Parcelle> getAllParcelles() {
ArrayList<Parcelle> parcelles = new ArrayList<Parcelle>();
String selectQuery = "SELECT * FROM " + T_PARCELLE;
Cursor c = bd.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
Parcelle p = new Parcelle();
p.setBien_code(c.getString(0));
p.setDecoup_terri_code(c.getString(1));
p.setDec_decoup_terri_code(c.getString(2));
p.setBien_ident(c.getString(3));
p.setParcel_denomination(c.getString(4));
p.setParcel_porte_ppale(c.getString(5));
p.setParcel_porte_second(c.getString(6));
p.setParcel_superfi_totale(c.getString(7));
p.setParcel_superf_batie(c.getString(8));
p.setParcel_superf_non_batie(c.getString(9));
p.setParcel_superf_plani(c.getString(10));
p.setParcel_adresse(c.getString(11));
p.setParcel_date_deb_construct(c.getString(12));
p.setParcel_date_fin_construct(c.getString(13));
p.setQuartier_lib(c.getString(14));
parcelles.add(p);
} while (c.moveToNext());
}
return parcelles;
}
public void insertParcelle(Parcelle p) {
ContentValues values = new ContentValues();
if (p.getBien_code() == "")
values.put("bien_code", getBienLastInsertID());
else
values.put("bien_code", p.getBien_code());
values.put("decoup_terri_code", p.getDecoup_terri_code());
values.put("dec_decoup_terri_code", p.getDec_decoup_terri_code());
values.put("bien_ident", p.getBien_ident());
values.put("parcel_denomination", p.getParcel_denomination());
values.put("parcel_porte_ppale", p.getParcel_porte_ppale());
values.put("parcel_porte_second", p.getParcel_porte_second());
values.put("parcel_superfi_totale", p.getParcel_superfi_totale());
values.put("parcel_superf_batie", p.getParcel_superf_batie());
values.put("parcel_superf_non_batie", p.getParcel_superf_non_batie());
values.put("parcel_superf_plani", p.getParcel_superf_plani());
values.put("parcel_adresse", p.getParcel_adresse());
values.put("parcel_date_deb_construct", p.getParcel_date_deb_construct());
values.put("parcel_date_fin_construct", p.getParcel_date_fin_construct());
values.put("quartier_lib", p.getQuartier_lib());
bd.insert(T_PARCELLE, null, values);
}
public int updateParcelle(Parcelle p) {
ContentValues values = new ContentValues();
values.put("decoup_terri_code", p.getDecoup_terri_code());
values.put("dec_decoup_terri_code", p.getDec_decoup_terri_code());
values.put("bien_ident", p.getBien_ident());
values.put("parcel_denomination", p.getParcel_denomination());
values.put("parcel_porte_ppale", p.getParcel_porte_ppale());
values.put("parcel_porte_second", p.getParcel_porte_second());
values.put("parcel_superfi_totale", p.getParcel_superfi_totale());
values.put("parcel_superf_batie", p.getParcel_superf_batie());
values.put("parcel_superf_non_batie", p.getParcel_superf_non_batie());
values.put("parcel_superf_plani", p.getParcel_superf_plani());
values.put("parcel_adresse", p.getParcel_adresse());
values.put("parcel_date_deb_construct", p.getParcel_date_deb_construct());
values.put("parcel_date_fin_construct", p.getParcel_date_fin_construct());
values.put("quartier_lib", p.getQuartier_lib());
return bd.update(T_PARCELLE, values, "bien_code = ?", new String[] { String.valueOf(p.getBien_code()) });
}
public int getParcelleCount() {
String countQuery = "SELECT count(*) as nb FROM " + T_PARCELLE;
Cursor cursor = bd.rawQuery(countQuery, null);
int nb = cursor.getInt(0);
cursor.close();
return nb;
}
}
Even if I write just this line inside the onPostExecute then the dialog does not dismiss :
#Override
protected void onPostExecute(Void result) { // appellé automatiquement quand le tache background est terminé
wait.dismiss();
}
private class RequestTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
}
#Override
protected Void doInBackground(String... s_url) {
return null;
}
#Override
protected void onPostExecute(Void result) {
pp.dismiss();
}
}
//=========================================//
public class Main extends Activity {
/** Called when the activity is first created. */
Patienter pp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main); // This needs to be done before
// trying to findViewById
final View vv = findViewById(R.id.my_webview);
vv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
pp = new Patienter(Main.this, getLayoutInflater());
pp.show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
new RequestTask().execute();
}
}, 5*1000);
}
});
}
Its working in my project.
please use wait.dismiss(); before if condition in onPostExecute() method.
I am trying to build up a application which has a custom adapter and all ListView row has three Button. I have onClick operation for all Button in custom adapter. I can change the data source when Button clicked however I can not reload the data from custom adapter.
public class CallListViewCustomAdapter extends ArrayAdapter<Person> {
Context context;
SQLiteDatabase sb;
private static final String SAMPLE_DB_NAME = "androidData.sqlite";
private static final String SAMPLE_TABLE_NAME = "calldetails";
int layoutResourceId;
ArrayList<Person> data = new ArrayList<Person>();
public CallListViewCustomAdapter(Context context, int layoutResourceId, ArrayList<Person> data) {
super(context, layoutResourceId,data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
public void refresh(ArrayList<Person>list)
{
data = list;
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = null;
View row = convertView;
final int fPosition = position;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
final WeatherHolder holder = new WeatherHolder();
holder.phoneNumber = (TextView)row.findViewById(R.id.number);
holder.fname = (TextView)row.findViewById(R.id.fName);
holder.call = (Button)row.findViewById(R.id.callButton);
holder.skip = (Button)row.findViewById(R.id.skip);
holder.called = (Button)row.findViewById(R.id.called);
holder.called.setTag(position);
Person weather = data.get(position);
holder.phoneNumber.setText(weather.number);
holder.fname.setText(weather.fName);
holder.call.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
holder.called.setVisibility(View.VISIBLE);///error comes
holder.skip.setVisibility(View.VISIBLE);///error comes
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + data.get(fPosition).number));
callIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(callIntent);
}
});
holder.called.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
//business logic for data source change
refresh(data);///I want listview change here
sb.close();
Log.v("ONMESSAGE", "HARD");
}
});
// holder.desc= (TextView)row.findViewById(R.id.txtViewDescription);
// holder.switchState = (Switch)row.findViewById(R.id.switch1);
row.setTag(holder);
}
return row;
}
static class WeatherHolder
{
TextView phoneNumber;
TextView fname;
Switch switchState;
Button call,skip,called;
}
}
Fragment where The list is used
public class NewFragment extends Fragment{
View rootView;
ProgressDialog pDialog;
private ListView listView1;
CallListViewCustomAdapter adapter;
private static final String SAMPLE_DB_NAME = "androidData.sqlite";
private SQLiteDatabase sampleDB;
ArrayList<Person>list;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
rootView = inflater.inflate(R.layout.newfragment, container, false);
initDB();
list = new ArrayList<Person>();
new CallLogDetails().execute();
return rootView;
}
public int checkTable() {
int return_var = 0;
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
Cursor cc = sampleDB.rawQuery("SELECT * FROM " + "calldetails", null);
if (cc != null){
if (cc.moveToFirst()) {
do {
return_var = cc.getInt(1);
} while (cc.moveToNext());
}
}
return return_var;
}
public void parseandStoreOpearation()
{
try{
CSVReader reader = new CSVReader(new InputStreamReader(getActivity().getAssets().open("batch2.csv")));
String [] nextLine;
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
while ((nextLine = reader.readNext()) != null) {
//Log.v("ONMESSAGE", "YES");
Log.v("ONMESSAGE", "Name: [" + nextLine[0] + "]\nAddress: [" + nextLine[1] + "]\nEmail: [" + nextLine[2] + "]");
if(!nextLine[0].equals("First Name"))
{
//Person newPerson = new Person(nextLine[0],nextLine[1], nextLine[2], 1);
ContentValues cv = new ContentValues();
cv.put("callNumber", nextLine[2]);
cv.put("fName", nextLine[0]);
cv.put("lName", nextLine[1]);
cv.put("callflag", 1);
sampleDB.insert("calldetails", null, cv);
//list.add(newPerson);
}
}
}
catch(Exception e)
{
Log.v("ONMESSAGE", "EXCEPTION " + e.toString());
}
}
public ArrayList<Person> getList()
{
ArrayList<Person> arr = new ArrayList<Person>();
sampleDB= getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
Cursor cc = sampleDB.rawQuery("SELECT * FROM " +"calldetails", null);
if(cc != null)
if(cc.moveToFirst()){
do
{ Log.v("Datas",cc.getString(2)+ " " +cc.getString(3) + " " + cc.getString(1) + " " + cc.getInt(4));
Person ph = new Person(cc.getString(2), cc.getString(3), cc.getString(1),cc.getInt(4),cc.getInt(0));
arr.add(ph);
}while(cc.moveToNext());
}
sampleDB.close();
Log.v("ONMESSAGE", new Integer(arr.size()).toString());
return arr;
}
private void initDB() {
sampleDB = getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, Context.MODE_PRIVATE, null);
sampleDB.execSQL("CREATE TABLE IF NOT EXISTS " +
"calldetails" +" (callid INTEGER PRIMARY KEY AUTOINCREMENT,"+ "callNumber TEXT," +
" fName TEXT," + "lName TEXT," + "callflag INTEGER);");
}
private class CallLogDetails extends AsyncTask<Void,Void,Void>{
#Override
protected void onPreExecute(){
pDialog = new ProgressDialog(getActivity());
pDialog.setTitle("Processing");
pDialog.setMessage("Loading Number List");
pDialog.setIndeterminate(true);
pDialog.setCancelable(false);
pDialog.show();
}
protected void onPostExecute(Void params){
super.onPostExecute(params);
pDialog.dismiss();
if(list.size() == 0)
{
list.add(new Person("No Data", "NO Data", "No Data", 0,0));
}
Collections.reverse(list);
if(adapter != null)
adapter.clear();
adapter = new CallListViewCustomAdapter(getActivity(),
R.layout.listview_row, list);
listView1 = (ListView)getActivity().findViewById(R.id.lvAlbumList);
listView1.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
final int arg2, long arg3) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Delete Record");
builder.setMessage("Do you want to delete the record?");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
if(list.size() > 0){
sampleDB=getActivity().openOrCreateDatabase(SAMPLE_DB_NAME, SQLiteDatabase.OPEN_READWRITE, null);
//sampleDB.execSQL("DELETE FROM "+ SAMPLE_DB_NAME + " " + "WHERE callDesc= " + desc);
//sampleDB.execSQL("DELETE FROM calldetails WHERE callDesc='"+desc+"';");
Toast.makeText(getActivity(), "Row Deleted", Toast.LENGTH_LONG).show();
sampleDB.close();
new CallLogDetails().execute();
}
else
Toast.makeText(getActivity(), "This is a default object. You can not delete this.", Toast.LENGTH_LONG).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
arg0.cancel();
}
});
builder.show();
return false;
}
});
listView1.setAdapter(adapter);
}
#Override
protected Void doInBackground(Void... arg0) {
list.clear();
if(checkTable() == 0)
{
parseandStoreOpearation();
}
list = getList();
Log.v("ONMESSAGE", "Doing");
return null;
}
}
}
For an ArrayAdapter, notifyDataSetChanged() only works if you use the add, insert, remove, and clear functions on the Adapter.
Try following code:
public void refresh(ArrayList<Person>list)
{
data.clear();
data.addAll(list);
this.notifyDataSetChanged();
}
Do something like this inside activity
CallListViewCustomAdapter thadapter=new CallListViewCustomAdapter(MainActivity.this, R.layout.list,numAl);
NumberList.setAdapter(thadapter);
#Override
public void onClick(View v) {
thadapter.notifyDataSetChanged();
}
});
Call notifyDataSetChanged() and recall adapter
Call notifyDataSetChanged() method to the ListView adapter object.