I am new to android development and must take the value of the id in the clicked item database.
Already searched several posts but not found the answer .
Below is my code Listview :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.seleciona_jogador_act);
final BancoController bc = new BancoController(this);
final ArrayList<JogadorEntidade> jogadorEntidade = bc.arrayJogador(this);
listView = (ListView) findViewById(R.id.lvSelecionar);
final SelecionaAdapter adapter = new SelecionaAdapter(this, R.layout.adapter_seleciona, jogadorEntidade);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setBackgroundTintList(ColorStateList.valueOf(background));
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
alertInserirJogador(SelecionaJogadorAct.this);
}
});
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//I NEED THIS CODE
Context context = getApplicationContext();
CharSequence text = "ID: " + ", Posicao: " + position;
int duration = Toast.LENGTH_SHORT;
Toast.makeText(context, text, duration).show();
//bc.deletaRegistro(id_player);
Intent intent = getIntent();
SelecionaJogadorAct.this.finish();
startActivity(intent);
}
});
}
My Adapter:
public class SelecionaAdapter extends ArrayAdapter<JogadorEntidade> {
Context context;
int layoutID;
ArrayList<JogadorEntidade> alJogador;
public SelecionaAdapter(Context context, int layoutID, ArrayList<JogadorEntidade> alJogador){
super(context, layoutID, alJogador);
this.context = context;
this.alJogador = alJogador;
this.layoutID = layoutID;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
View row = convertView;
PlayerHolder holder = null;
if (row == null){
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutID, parent, false);
holder = new PlayerHolder();
holder.txtNome = (TextView)row.findViewById(R.id.txtNomeSelecionar);
holder.txtVitorias = (TextView)row.findViewById(R.id.txtVitóriasSelecionar);
holder.txtDerrotas = (TextView)row.findViewById(R.id.txtDerrotasSelecionar);
row.setTag(holder);
}else {
holder = (PlayerHolder)row.getTag();
}
JogadorEntidade jogadorEntidade = alJogador.get(position);
holder.txtNome.setText(jogadorEntidade.getNome());
holder.txtVitorias.setText("V: " + jogadorEntidade.vitórias);
holder.txtDerrotas.setText("D: " + jogadorEntidade.derrotas);
return row;
}
static class PlayerHolder{
TextView txtNome;
TextView txtVitorias;
TextView txtDerrotas;
}
JogadorEntidade:
public class JogadorEntidade {
public String nome;
public Integer id_jogador;
public String vitórias;
public String derrotas;
public Integer getId_jogador() {
return id_jogador;
}
public void setId_player(int id_player) {
this.id_jogador = id_player;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getVitórias() {
return vitórias;
}
public void setVitórias(String vitórias) {
this.vitórias = vitórias;
}
public String getDerrotas() {
return derrotas;
}
public void setDerrotas(String derrotas) {
this.derrotas = derrotas;
}
public JogadorEntidade(String nome, String vitórias, String derrotas){
super();
this.nome = nome;
this.vitórias = vitórias;
this.derrotas = derrotas;
}
public JogadorEntidade(){}
public void insereJogador(JogadorEntidade jogadorEntidade) {
db = banco.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(banco.NOME_JOGADOR, jogadorEntidade.getNome());
values.put(banco.VITORIAS, jogadorEntidade.getVitórias());
values.put(banco.DERROTAS, jogadorEntidade.getDerrotas());
db.insert(CriaBanco.TABELA_JOGADOR, null, values);
db.close();
}
public Cursor carregaJogador() {
Cursor cursor;
String[] campos = {banco.NOME_JOGADOR, banco.VITORIAS, banco.DERROTAS};
db = banco.getReadableDatabase();
cursor = db.query(banco.TABELA_JOGADOR, campos, null, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
db.close();
return cursor;
}
public void deletaRegistro(int id){
String where = CriaBanco.ID_JOGADOR + "=" + id;
db = banco.getReadableDatabase();
db.delete(CriaBanco.TABELA_JOGADOR, where, null);
db.close();
}
public ArrayList<JogadorEntidade> arrayJogador(Context context) {
ArrayList<JogadorEntidade> al = new ArrayList<JogadorEntidade>();
BancoController bancoController = new BancoController(context);
Cursor cursor;
cursor = bancoController.carregaJogador();
if (cursor != null) {
if (cursor.moveToFirst()) {
String nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
String vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
String derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
JogadorEntidade jogadorEntidade = new JogadorEntidade(nome, vitorias, derrotas);
al.add(jogadorEntidade);
while (cursor.moveToNext()) {
nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
jogadorEntidade = new JogadorEntidade(nome, vitorias, derrotas);
al.add(jogadorEntidade);
}
}
}
return al;
}
First you need to request the id when making the query (if the id is the one created in the database the column mame is _id or you can use tablename._id or whatever you need):
String[] campos = {"_id", banco.NOME_JOGADOR, banco.VITORIAS, banco.DERROTAS};
Then you need to add the id to the object when you read the cursor:
public ArrayList<JogadorEntidade> arrayJogador(Context context) {
ArrayList<JogadorEntidade> al = new ArrayList<JogadorEntidade>();
BancoController bancoController = new BancoController(context);
Cursor cursor;
cursor = bancoController.carregaJogador();
if (cursor != null) {
if (cursor.moveToFirst()) {
String nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
String vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
String derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
long id = cursor.getLong(cursor.getColumnIndex("_id",0));
JogadorEntidade jogadorEntidade = new JogadorEntidade(id, nome, vitorias, derrotas);
al.add(jogadorEntidade);
while (cursor.moveToNext()) {
nome = cursor.getString(cursor.getColumnIndex(banco.NOME_JOGADOR));
vitorias = cursor.getString(cursor.getColumnIndex(banco.VITORIAS));
derrotas = cursor.getString(cursor.getColumnIndex(banco.DERROTAS));
long id = cursor.getLong(cursor.getColumnIndex("_id",0));
jogadorEntidade = new JogadorEntidade(id, nome, vitorias, derrotas);
al.add(jogadorEntidade);
}
}
}
return al;
}
Anyway this is not the way to go in android. You should read all the list and then show it. You should use the viewholder pattern and only load the player when you are going to show it. Also instead of using a list you should move to recyclerviews. Listviews can be consider deprecated at this point. See the tutorial: http://developer.android.com/training/material/lists-cards.html
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);
This is structure of my json respose :
{
"data": [
{
"id": 23,
"title": "this is title",
"description": " this is desc",
"date": "21/2/16",
"authorname": "john smith",
"authorpic": "http://xtryz.com/users/1462862047com.yahoo.mobile.client.android.yahoo_128x128.png",
"filename": "1463770591.MP4",
"downloadlink": "http://xyrgz.com/download.zip",
"downloadcnt": "24"
},
...
]
And with clicking one Buton in each row of RecyclerView I save that json row In the Database . Know for some work I need to know is this json row exist in the Database or no ? for doing this work , I Want to use the id in the database and id of the json . and if id of the database same to id of the json , doing some work and else .
This is the QuestionDatabaseAdapter :
public class QuestionDatabaseAdapter {
private Context context;
private SQLiteOpenHelper sqLiteOpenHelper;
private static final int DATABASE_VERSION = 1;
//private SQLiteDatabase database = null;
public QuestionDatabaseAdapter(Context context) {
this.context = context;
sqLiteOpenHelper = new SQLiteOpenHelper(context, "database.db", null, DATABASE_VERSION) {
#Override
public void onCreate(SQLiteDatabase db) {
String sql = "CREATE TABLE tbl_questions ( id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL UNIQUE, question_id VARCHAR( 255 ) NOT NULL , title VARCHAR( 255 ) NOT NULL, [desc] TEXT NOT NULL, Date VARCHAR( 50 ) NOT NULL, authorName VARCHAR( 255 ) NOT NULL , authorPic VARCHAR( 255 ) NOT NULL, downLink VARCHAR( 255 ) NOT NULL )";
db.execSQL(sql);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
};
}
//================== SAVE QUESTION IN DATABASE ==========================
public long saveQuestion(ModelQuestion modelQuestion) {
String question_id = modelQuestion.getQuestionId();
String title = modelQuestion.getQuestionTitle();
String desc = modelQuestion.getQuestionDesc();
String date = modelQuestion.getQuestionDate();
String authorName = modelQuestion.getQuestionAuthorName();
String authorPic = modelQuestion.getQuestionAuthorPic();
String downloadLink = modelQuestion.getQuestionDownLink();
SQLiteDatabase database = null;
long id = -1;
try {
ContentValues values = new ContentValues();
values.put("question_id", question_id);
values.put("title", title);
values.put("desc", desc);
values.put("date", date);
values.put("authorName", authorName);
values.put("authorPic", authorPic);
values.put("downLink", downloadLink);
database = sqLiteOpenHelper.getWritableDatabase();
id = database.insert("tbl_questions", null, values);
} catch (Exception ex) {
Log.i("DATABASE SAVE EX", ex.getMessage());
} finally {
if (database != null && database.isOpen()) {
database.close();
}
}
return id;
}
//=================== READ ALL QUESTION IN DATABASE=========================
public ArrayList<ModelQuestion> readAllQuestions() {
ArrayList<ModelQuestion> questions = null;
String[] columns = new String[]{"*"};
String selection = null;
String[] selectionArgs = null;
String groupBy = null;
String having = null;
String orderBy = null;
String limit = null;
String favorite = null;
SQLiteDatabase database = null;
try {
database = sqLiteOpenHelper.getReadableDatabase();
Cursor cursor = database.query("tbl_questions", columns, selection, selectionArgs, groupBy, having, orderBy, limit);
if (cursor != null && cursor.moveToFirst()) {
questions = new ArrayList<ModelQuestion>();
int indexQuestionId = 0;
int indexTitle = 1;
int indexDesc = 2;
int indexDate = 3;
int indexAuthorName = 4;
int indexAuthorPic = 5;
int indexDownloadLink = 6;
int indexFavorite = 7;
do {
String questionId = cursor.getString(indexQuestionId);
String questionTitle = cursor.getString(indexTitle);
String questionDesc = cursor.getString(indexDesc);
String questionDate = cursor.getString(indexDate);
String questionAuthorName = cursor.getString(indexAuthorName);
String questionAuthorPic = cursor.getString(indexAuthorPic);
String questionDownloadLink = cursor.getString(indexDownloadLink);
ModelQuestion question = new ModelQuestion();
question.setQuestionId(questionId);
question.setQuestionTitle(questionTitle);
question.setQuestionDesc(questionDesc);
question.setQuestionDate(questionDate);
question.setQuestionAuthorName(questionAuthorName);
question.setQuestionAuthorPic(questionAuthorPic);
question.setQuestionDownLink(questionDownloadLink);
questions.add(question);
} while (cursor.moveToNext());
}
} catch (Exception ex) {
Log.i("DATABASE READ ALL EX", ex.getMessage());
} finally {
if (database != null && database.isOpen()) {
database.close();
}
}
return questions;
}
//=================== DELETE ONE QUESTION IN DATABASE=========================
public int deletePerson(long id) {
int noOfDeletedRecords = 0;
String whereClause = "id=?";
String[] whereArgs = new String[]{String.valueOf(id)};
SQLiteDatabase database = null;
try {
database = sqLiteOpenHelper.getWritableDatabase();
noOfDeletedRecords = database.delete("tbl_questions", whereClause, whereArgs);
} catch (Exception ex) {
Log.i("DATABASE DELETE EX", ex.getMessage());
} finally {
if (database != null && database.isOpen()) {
database.close();
}
}
return noOfDeletedRecords;
}
}
And this is The adapterRecyclerQuestion :
public class AdapterRecyclerQuestion extends RecyclerView.Adapter<AdapterRecyclerQuestion.ViewHolder> {
private Context context;
private ArrayList<ModelQuestion> questionha;
//constructor
public AdapterRecyclerQuestion(Context context, ArrayList<ModelQuestion> questionha) {
this.context = context;
this.questionha = questionha;
}
//viewholder
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView txtTitle;
private TextView txtDesc;
private TextView txtCntDown;
private ImageView imgAuthorPic;
private TextView txtAuthorName;
private TextView txtDate;
private Button btnDownload;
private ImageView imgAddFav;
public ViewHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
txtTitle = (TextView) itemView.findViewById(R.id.txt_title_question);
txtDesc = (TextView) itemView.findViewById(R.id.txt_desc_question);
txtCntDown = (TextView) itemView.findViewById(R.id.txt_cnt_down_question_dy);
imgAuthorPic = (ImageView) itemView.findViewById(R.id.img_author_pic_question);
txtAuthorName = (TextView) itemView.findViewById(R.id.txt_author_name_question);
txtDate = (TextView) itemView.findViewById(R.id.txt_date_question);
btnDownload = (Button) itemView.findViewById(R.id.btn_down_question);
imgAddFav = (ImageView) itemView.findViewById(R.id.img_add_to_fav);
}
#Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "Hello" + txtTitle.getText(), Toast.LENGTH_SHORT).show();
}
}
//oncreateviewholder
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.question_row, parent, false);
return new ViewHolder(view);
}
//onbindviewholder
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
QuestionDatabaseAdapter questionDatabaseAdapter = new QuestionDatabaseAdapter(holder.itemView.getContext());
questionDatabaseAdapter.readAllQuestions();
holder.txtTitle.setText(questionha.get(position).getQuestionTitle());
holder.txtDesc.setText(questionha.get(position).getQuestionDesc());
holder.txtCntDown.setText(questionha.get(position).getQuestionDownCnt());
holder.txtAuthorName.setText(questionha.get(position).getQuestionAuthorName());
Glide.with(holder.itemView.getContext()).load(questionha.get(position).getQuestionAuthorPic()).into(holder.imgAuthorPic);
holder.txtDate.setText(questionha.get(position).getQuestionDate());
//============= IMG ADD TO FAV ON CLICK LISTENER =========================
holder.imgAddFav.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
QuestionDatabaseAdapter databaseAdapter = new QuestionDatabaseAdapter(v.getContext());
ModelQuestion question = new ModelQuestion();
question.setQuestionId(questionha.get(position).getQuestionId());
question.setQuestionTitle(questionha.get(position).getQuestionTitle());
question.setQuestionDesc(questionha.get(position).getQuestionDesc());
question.setQuestionDate(questionha.get(position).getQuestionDate());
question.setQuestionAuthorName(questionha.get(position).getQuestionAuthorName());
question.setQuestionAuthorPic(questionha.get(position).getQuestionAuthorPic());
question.setQuestionDownLink(questionha.get(position).getQuestionDownLink());
databaseAdapter.saveQuestion(question);
Toast.makeText(v.getContext(), "اضافه شد", Toast.LENGTH_SHORT).show();
}
});
//=============BTN DOWNLOAD CLICK LISTENER =========================
holder.btnDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(questionha.get(position).getQuestionDownLink()));
request.setTitle(questionha.get(position).getQuestionTitle());
request.setDescription("در حال دانلود");
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, questionha.get(position).getQuestionDownFileName());
long enqueueId = downloadManager.enqueue(request);
}
});
}
//getitemcount
#Override
public int getItemCount() {
return questionha.size();
}
}
And this is Database Structure :
(question_id is the id of question)
Now i need to compare id of database and id of the json in adapter . but i don't know how can i do this .
private ArrayList<ModelQuestion> questionha;
private ArrayList<ModelQuestion> jsonArrList;
//pass your json arraylist too in constructor from your main activity
public AdapterRecyclerQuestion(Context context, ArrayList<ModelQuestion> questionha,ArrayList<ModelQuestion> jsonArrList) {
this.context = context;
this.questionha = questionha;
this.jsonArrList = jsonArrList;
}
#Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
for(int i=0;i<jsonArrList.size();i++)
{
//Check your id here
if(jsonArrList.get(i).getId().equalsIgnoreCase(questionha.get(position).getId()))
}
}
I need to get all contacts that have at least a phone number. Android contacts may be picked from many accounts like gmail,skype,vibe etc. I made the classes i need to get the contacts i need. My problem that it gets anyway contacts that don't have at least 1 phone number and shows just their name and avatar. Can any1 say what I am doing wrong in my code? My code source is shared below.
ContactsActivity.class
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
selectionString = edtSearch.getText().toString();
String[] selectionArgs = {"%" + selectionString + "%", selectionString + "%", "%" + selectionString};
String selection = ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? OR "
+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? OR "
+ ContactsContract.Contacts.DISPLAY_NAME + " LIKE ? AND "
+ ContactsContract.Contacts.HAS_PHONE_NUMBER + "=='1'";
return new CursorLoader(this,
ContactsContract.Contacts.CONTENT_URI, // URI
null, // projection fields
selection, // the selection criteria
selectionArgs, // the selection args
ContactsContract.Contacts.DISPLAY_NAME + " ASC" // the sort order
);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
ContactsAdapter.createCheckedContacts(data.getCount());
contactsAdapter.setCursor(data);
contactsAdapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
contactsAdapter.swapCursor(null);
}
ContactsAdapter.class
public class ContactsAdapter extends CursorAdapter {
static boolean status = true;
private static boolean[] checkedContacts;
private static Context context;
private static Cursor cursor;
public ContactsAdapter(Context context, Cursor c) {
super(context, c, 0);
this.context = context;
}
public static void setCursor(Cursor cursor) {
ContactsAdapter.cursor = cursor;
}
public static void createCheckedContacts(int count) {
checkedContacts = new boolean[count];
}
public static void saveSelectedContacts(ClientDao contactDao) {
for (int i = 0; i < checkedContacts.length; i++) {
if (checkedContacts[i]) {
cursor.moveToPosition(i);
DatabaseHelper.getInstance().saveClient(ContactUtils.cursorToContact(cursor, context), status);
status = !status;
}
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View convertView = ((Activity) context).getLayoutInflater().inflate(R.layout.contact_item, parent, false);
ViewHolder holder = new ViewHolder(convertView);
convertView.setTag(holder);
return convertView;
}
#Override
public void bindView(View convertView, final Context context, final Cursor cursor) {
final ViewHolder holder = (ViewHolder) convertView.getTag();
final Contact contact = ContactUtils.cursorToContact(cursor, context);
holder.tvName.setText(contact.getDisplayName());
if (isFirst(cursor)) {
holder.tvLetter.setVisibility(View.VISIBLE);
String letter = String.valueOf(Character.toUpperCase(contact.getDisplayName().charAt(0)));
holder.tvLetter.setText(letter);
} else {
holder.tvLetter.setVisibility(View.INVISIBLE);
}
convertView.setTag(convertView.getId(), contact);
if (!TextUtils.isEmpty(contact.getPhotoUri())) {
new ImageLoaderUtils.ContactImage(contact, convertView, holder.ivUserImage, context).execute();
} else {
holder.ivUserImage.setImageResource(R.drawable.ic_profile);
}
holder.inviteBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ContactInvitationActivity_.class);
intent.putExtra("contact", contact);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
context.startActivity(intent);
}
});
}
private boolean isFirst(Cursor cursor) {
Contact c1 = ContactUtils.cursorToContact(cursor, context);
if (cursor.getPosition() == 0)
return true;
cursor.moveToPrevious();
Contact c2 = ContactUtils.cursorToContact(cursor, context);
if (c1.getDisplayName() == null || c2.getDisplayName() == null)
return false;
if (Character.toUpperCase(c1.getDisplayName().charAt(0)) != Character.toUpperCase(c2.getDisplayName().charAt(0)))
return true;
return false;
}
private static class ViewHolder {
TextView tvName;
TextView tvLetter;
ImageView ivUserImage;
Button inviteBtn;
RelativeLayout rlContact;
private ViewHolder(View convertView) {
tvName = (TextView) convertView.findViewById(R.id.tvContactsName);
tvLetter = (TextView) convertView.findViewById(R.id.tvLetter);
ivUserImage = (ImageView) convertView.findViewById(R.id.ivUserIcon);
inviteBtn = (Button) convertView.findViewById(R.id.inviteBtn);
rlContact = (RelativeLayout) convertView.findViewById(R.id.rlContact);
}
}
}
ContactUtil.class
public class ContactUtils {
public static Contact cursorToContact(Cursor c, Context context) {
if (c == null || c.getPosition() < 0) return null;
Contact contactObj = new Contact();
try {
contactObj.setID(c.getString(c.getColumnIndex(ContactsContract.Contacts._ID)));
contactObj.setDisplayName(c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
contactObj.setPhotoUri(c.getString(c.getColumnIndex(ContactsContract.Contacts.PHOTO_URI)));
contactObj.setPhoneNumber("");
contactObj.setEmail("");
setPhoneNumber(c, contactObj, context);
setEmail(contactObj, context);
} catch (Exception e) {
e.printStackTrace();
}
return contactObj;
}
public static void setPhoneNumber(Cursor c, Contact contactObj, Context context) {
if (Integer.parseInt(c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
// Query phone here. Covered next
Cursor phones = context.getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactObj.getID(), null, null);
phones.moveToFirst();
String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.i("Number", phoneNumber);
contactObj.setPhoneNumber(phoneNumber);
phones.close();
}
}
public static void setEmail(Contact contactObj, Context context) {
Cursor emailCur = context.getContentResolver().query(
ContactsContract.CommonDataKinds.Email.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?",
new String[]{contactObj.getID()}, null);
while (emailCur.moveToNext()) {
// This would allow you get several email addresses
// if the email addresses were stored in an array
String email = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(
emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
contactObj.setEmail(email);
}
emailCur.close();
}
}
I'm trying to remove items from listView and the database, but I can not cope. I throw the code, and I hope to help. I throw code with showList on screen and save to database sqlite. Any idea? I am also a beginner any help would be greatly appreciated. I was looking at tutorials and removal does not work for me. I have no idea why. And how do though to purge my list after exiting application? Because when I go to the application's data in listView are still visible.
public class PropertyListAdapter extends BaseAdapter {
Context context;
ArrayList<Property> propertyList;
public PropertyListAdapter(Context context, ArrayList<Property> list) {
this.context = context;
propertyList = list;
}
#Override
public int getCount() {
return propertyList.size();
}
#Override
public Object getItem(int position) {
return propertyList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup arg2) {
View vi = convertView;
Property propertyListItems = propertyList.get(position);
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
vi = inflater.inflate(R.layout.property_list_row, null);
}
TextView tvSlNo = (TextView) convertView.findViewById(R.id.tv_slno);
tvSlNo.setText(String.valueOf(propertyListItems.getId()));
TextView tvName1 = (TextView) convertView.findViewById(R.id.tv_name1);
tvName1.setText(propertyListItems.getType());
TextView tvName = (TextView) convertView.findViewById(R.id.tv_name);
tvName.setText(propertyListItems.getAddress());
TextView tvPhone = (TextView) convertView.findViewById(R.id.tv_phone);
tvPhone.setText(String.valueOf(propertyListItems.getValue()));
TextView tvPhone1 = (TextView) convertView.findViewById(R.id.tv_phone1);
tvPhone1.setText(String.valueOf(propertyListItems.getDebt()));
TextView tvName2 = (TextView) convertView.findViewById(R.id.tv_name2);
tvName2.setText(propertyListItems.getNotes());
Button deletePropertyItem = (Button) vi.findViewById(R.id.DeletePropertyListItem);
deletePropertyItem.setTag(position);
deletePropertyItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer)v.getTag();
propertyList.remove(position);
notifyDataSetChanged();
}
});
return vi;
}
db = new MeetingsDataBaseHelper(this);
showList();
add1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Double value1, debt;
String editValueDb1,editDebtDb1;
final Integer idEncounterToPass = AppMainScreen.getMeetingListClickedItem().getEncounter_id();
String type = editTextTypeProperty.getText().toString();
String address = editAddresse1.getText().toString();
// Double value1 = Double.valueOf(editValue1.getText().toString());
String editValue1String = ReportMainScreen.editValue1.getText().toString();
if (editValue1String.length() > 0)
{
value1 = Double.valueOf(editValue1String);
} else {
value1 = Double.valueOf("0.00");
}
// Double debt = editViewDebt1.getText().toString();
String editDebtString = ReportMainScreen.editViewDebt1.getText().toString();
if (editDebtString.length() > 0)
{
debt = Double.valueOf(editDebtString);
} else {
debt = Double.valueOf("0.00");
}
String notes = editNotesProperty.getText().toString();
String encounter_id = String.valueOf(idEncounterToPass);
String posted = "0";
String query = "INSERT INTO property(type,address,value,debt,notes,encounter_id,posted) values ('"
+ type + "','" + address + "','" + value1 + "','" + debt + "','" + notes + "','" + encounter_id + "','" + posted + "')";
db.executeQuery(query);
showList();
editTextTypeProperty.setText("");
editAddresse1.setText("");
editValue1.setText("");
editViewDebt1.setText("");
editNotesProperty.setText("");
}
});
private void showList() {
ArrayList<Property> propertyList = new ArrayList<Property>();
propertyList.clear();
String query = "SELECT * FROM property ";
Cursor c1 = db.selectQuery(query);
if (c1 != null && c1.getCount() != 0) {
if (c1.moveToFirst()) {
do {
Property propertyListItems = new Property();
propertyListItems.setId(Integer.valueOf(c1.getString(c1.getColumnIndex("id"))));
propertyListItems.setType(c1.getString(c1.getColumnIndex("type")));
propertyListItems.setAddress(c1.getString(c1.getColumnIndex("address")));
propertyListItems.setValue(Double.valueOf(c1.getString(c1.getColumnIndex("value"))));
propertyListItems.setDebt(Double.valueOf(c1.getString(c1.getColumnIndex("debt"))));
propertyListItems.setNotes(c1.getString(c1.getColumnIndex("notes")));
propertyList.add(propertyListItems);
} while (c1.moveToNext());
}
}
c1.close();
PropertyListAdapter propertyListAdapter = new PropertyListAdapter(ReportMainScreen.this, propertyList);
first_list_view.setAdapter(propertyListAdapter);
propertyListAdapter.notifyDataSetChanged(); // TODO check this reg. clearing subtables
// propertyList.remove(propertyListAdapter);
}
Delete on db
private void DeleteItemFormList() {
Property property = new Property();
ArrayList<Property> propertyList = new ArrayList<Property>();
propertyList.clear();
int id = property.getId();
String delQuery = "DELETE FROM Property WHERE id='"+id+"' ";
db.executeQuery(delQuery);
showList();
PropertyListAdapter propertyListAdapter = new PropertyListAdapter(ReportMainScreen.this, propertyList);
first_list_view.setAdapter(propertyListAdapter);
propertyListAdapter.notifyDataSetChanged(); // TODO check this reg. clearing subtables
// propertyList.remove(propertyListAdapter);
}
I think You need to pass Id which is autoIncreament instead of possition.
ie.
int index=propertyList.get(position).get(Id);
Button deletePropertyItem = (Button) vi.findViewById(R.id.DeletePropertyListItem);
deletePropertyItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
propertyList.remove(index);
notifyDataSetChanged();
}
});