Android and delete items from ListView and sqlite database - android

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();
}
});

Related

Update textview data sqlite Android

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());

How do I get the ID item in the database?

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

transfer checked items in list-view to another list-view on button click in android

I have a listview with data using customAdapter.class now what i want is that to transfer checked items in listview to secondActivity on button click...
btest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
ArrayList<Model> mylist = new ArrayList<Model>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
// listView = new ArrayList<Model>();
mylist.add(String.valueOf(adapter.getItem(position)));
}
String[] output = new String[mylist.size()];
for (int i = 0; i < mylist.size(); i++) {
output[i] = (mylist.get(i));
}
Intent intent = new Intent(getApplicationContext(), ResultActivity.class);
Bundle b = new Bundle();
b.putStringArray("selectedItems", output);
// b.putStringArrayList("SelectedItems: ",list);
// b.putString("selectedItems", String.valueOf(output));
intent.putExtras(b);
startActivity(intent);*/
}
});
and this is the second activity where i am getting that data in another listview
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result);
Bundle b = getIntent().getExtras();
String[] result = b.getStringArray("selectedItems");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, result);
lv.setAdapter(adapter);
}
The method you followed to send custom list to another activity will not work. In order to transfer your custom list between activities you need to create Parcelable List and send it through intent.
Android Intents does not support custom list.
Custom list can be passed in two ways, Serialization and Parcelable.
But Parcelable is more Efficient and Simple to implement.
Refer this link to send custom list between activities through Parcelable
This link will give you much better idea to implement Parcelable.
Updated Code: Change your Model Code like below.
public class Model implements Parcelable{
private String name;
private int selected;
public Model(String name){
this.name = name;
selected = 0;
}
public String getName(){
return name;
}
public int isSelected(){
return selected;
}
public void setSelected(boolean selected){
this.selected = selected;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
/**
* Storing the Student data to Parcel object
**/
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(name);
dest.writeInt(selected);
}
private Model (Parcel in){
this.name = in.readString();
this.selected = in.readInt();
}
public static final Parcelable.Creator<Model> CREATOR = new Parcelable.Creator<Model>() {
#Override
public Student createFromParcel(Parcel source) {
return new Student(source);
}
#Override
public Model[] newArray(int size) {
return new Model[size];
}
};
}
Then in the MainActivity do this..
Intent next = new Intent(MainActivity , ResultActivity.class);
next.putParcelableArrayListExtra("model_data", (ArrayList<? extends Parcelable>) selectedItems);
startActivity(next);
In the ResultActivity do this.
ArrayList<Model> his = getIntent().getParcelableArrayListExtra("model_data");
Try the above code..
Good Luck..!!
i solve by saving checked items from listview to sqlite on button click. another button to open new activity and call selected items sqlite this way...
oncheckchange add and remove items in an arraylist and call this in onbutton click like this way...
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder view = null;
Support support = (Support) this.getItem(position);
if (convertView == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.view_items, null);
view = new ViewHolder();
view.tvInfo = (TextView) convertView.findViewById(R.id.tvInfo);
view.cb = (CheckBox) convertView.findViewById(R.id.cb);
convertView.setTag(view);
view.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
CheckBox cb = (CheckBox) buttonView;
Support support = (Support) cb.getTag();
support.setSelected(cb.isChecked());
if (isChecked){
selList.add(support.status);
selID.add(support.id);
selType.add(support.type);
// Toast.makeText(CustomAdapter.this, "Clicked on Checkbox: " + cb.getText() + " is " + cb.isChecked(), Toast.LENGTH_LONG).show();
}else {
selList.remove(support.status);
selID.remove(support.id);
selType.remove(support.type);
}
}
});
}else{
view = (ViewHolder) convertView.getTag();
view.cb = view.getCb();
view.tvInfo = view.getTvInfo();
}
view.cb.setTag(support);
support = list.get(position);
String id = support.getId();
String status = support.getStatus();
String type = support.getType();
view.cb.setChecked(support.isSelected());
// view.tvInfo.setText(id + "," + status + "," + type);
view.tvInfo.setText(status);
return convertView;
}
this is button coding to add to db
btest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handler.addSelected(adapter.selList, adapter.selID, adapter.selType);
and this is how to insert to sqlite..
public void addSelected(ArrayList<String> selList, ArrayList<String> selID, ArrayList<String> selType) {
int size = selID.size();
SQLiteDatabase db = getWritableDatabase();
try{
for (int i = 0; i < size ; i++){
ContentValues cv = new ContentValues();
// cv.put(KEY_ID, selID.get(i).toString());
cv.put(KEY_ID, selID.get(i));
cv.put(KEY_STATUS, selList.get(i));
cv.put(KEY_TYPE, selType.get(i));
Log.d("Added ",""+ cv);
db.insertOrThrow(TABLE_SELECTED, null, cv);
}
db.close();
}catch (Exception e){
Log.e("Problem", e + " ");
}
}
and get back from db like this
public ArrayList<String> getSelected() {
SQLiteDatabase db = this.getReadableDatabase();
ArrayList<String> result = null;
try{
result = new ArrayList<String>();
// String query = "SELECT * FROM " + TABLE_SELECTED;
String query = "SELECT " + KEY_ID + " FROM " + TABLE_SELECTED;
Cursor c = db.rawQuery(query, null);
if (!c.isLast()){
if (c.moveToFirst()){
do{
String sel_name = c.getString(c.getColumnIndex("_id"));
result.add(sel_name);
Log.d("Added ", sel_name);
}while (c.moveToNext());
}
}
c.close();
db.close();
}catch (Exception e){
Log.e("Nothing is to show", e + " ");
}
return result;
}

unable to update single column in sqlite in android . Need to store the edit text values in db

I want to store the edit text value every time into my data base when giving a value into the edit text. I dnt know how to update my table. Every time edit text value changes here edit text indicates the quantity of the recipes I want to calculate amount based on the quantity so for that I want to store quantity value in db. please help me. how to store particular row value into db i can write update query but overall table updation happened there.
Thanks in advance
import java.util.ArrayList;
import java.util.List;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class YourOrder extends HelperActivity {
private ListView list;
private DataBaseHandler db;
ArrayList<Contact> imageArry = new ArrayList<Contact>();
OrdersImageAdapter adapter;
public static TextView toatalamount;
EditText qtyView,quantityt;
int total;
double recipeamount=0;
public static Button payment;
public Integer id = null;
public String name = null;
public Integer price = null;
public int quantiy;
public String quan;
double ordercount = 0;
private Double orderTotal = 0.00;
static String ordertotalval;
public String setvaluefinal;
int dbcount = 0;
public double editcount=0;
int count = NewBreakfastItems.getVariable();
ImageHolder holder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.yourorders);
list = (ListView) findViewById(R.id.listView1);
toatalamount = (TextView) findViewById(R.id.rupees);
db = new DataBaseHandler(this);
payment = (Button) findViewById(R.id.buy);
// Reading all contacts from database
List<Contact> contacts = db.getAllContacts();
Log.d("", "------DATABASE CONTACTS-------" + db.getAllContacts());
for (Contact cn : contacts) {
String log = "ID:" + cn.getID() + " Name: " + cn.getName()
+ " ,Image: " + cn.getImage() + "Price :" + cn.getprice();
Log.d("Name: ", log);
Log.i("", "-----ID-------" + cn.getID());
Log.i("", "-----ID-------" + cn.getName());
Log.i("----recipe price---", "-----price----" + cn.getprice());
id = cn.getID();// Here i am getting the id no...
name = cn.getName();
price = cn.getprice();
ordercount = ordercount + price;
Log.e("---ordercount---", "----ordercount----" + ordercount);
toatalamount.setText(String.valueOf(ordercount));
/*
* count=count+price; Log.i("---count----", "-----count----"+count);
*/
// Writing Contacts to log
Log.e("Result:========== ", "=====LOG=====" + log);
imageArry.add(cn);
}
Log.d("", "-----ID-------" + id);
Log.d("", "-----ID-------" + name);
adapter = new OrdersImageAdapter(this, R.layout.orderscart, imageArry);
list.setAdapter(adapter);
dbcount = db.getContactsCount();
Log.e("----dbcount----", "-----dbcount---" + dbcount);
payment.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(getApplicationContext(),
Payment.class);
//intent.putExtra("count", count);
intent.putExtra("ordertotalval", ordertotalval);
intent.putExtra("name", name);
startActivity(intent);
}
});
footerBlock();
}
public class OrdersImageAdapter extends ArrayAdapter<Contact> {
// Contact contact;
Context context;
public int dltcount;
int layoutResourceId;
int adaptercount = 0;
public int extPrice;
ArrayList<Contact> data = new ArrayList<Contact>();
public OrdersImageAdapter(Context context, int layoutResourceId,
ArrayList<Contact> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
this.data = new ArrayList<Contact>();
this.data.addAll(data);
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
DecimalFormat df = new DecimalFormat("0.00##");
Contact product = data.get(position);
View row = convertView;
holder = null;
Contact lContact = (Contact) list.getItemAtPosition(position);
db = new DataBaseHandler(getContext());
if (row == null) {
LayoutInflater inflater = ((Activity) context)
.getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
EditText quantity = (EditText) row.findViewById(R.id.quantity);
//attach the TextWatcher listener to the EditText
quantity.addTextChangedListener(new MyTextWatcher(row));
holder = new ImageHolder();
holder.txtTitle = (TextView) row.findViewById(R.id.txtTitle);
holder.imgIcon = (ImageView) row.findViewById(R.id.imgIcon);
holder.dlttxt = (TextView) row.findViewById(R.id.dlt);
holder.quantity = (EditText) row.findViewById(R.id.quantity);
holder.recipeprice=(TextView) row. findViewById(R.id.recipeprice);
row.setTag(holder);
} else {
holder = (ImageHolder) row.getTag();
}
quantityt = (EditText) row.findViewById(R.id.quantity);
quantityt.setTag(product);
if(product.getQuantity() != 0){
quantityt.setText(String.valueOf(product.getQuantity()));
}
else {
quantityt.setText("");
}
TextView ext = (TextView) row.findViewById(R.id.setprice);
if(product.getQuantity() != 0){
ext.setText("$" + df.format(product.getExt()));
}
else {
ext.setText("");
}
holder.recipeprice.setText(String.valueOf(lContact.getprice()+"X"));
/* ====DELETING RECIPE ITEMS==== */
holder.dlttxt.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Log.e("---pos---", "----position----" + position);
Contact lContact = (Contact) list
.getItemAtPosition(position);
Log.e("---pos---", "----position----" + lContact);
Log.e("TAG", "" + lContact.getID());
db.deleteContact(lContact.getID());
// db.deleteContact(pos);
Log.e("", "======deleted=====" + lContact.getID());
Log.e("", "====NAME====" + lContact.getName());
quan = lContact.getName();
Log.e("---lcontact price---", "------lcntact price----"
+ lContact.getprice());
adaptercount = lContact.getprice();
Log.e("","quantity---"+quantityt.getText());
Toast.makeText(
getContext(), lContact.getName() + ":"
+ "Deleted Sucessfully", Toast.LENGTH_SHORT)
.show();
//setvaluefinal=qtyView.getText().toString();
//ordercount=Integer.parseInt(setvaluefinal);
Log.e("", "-----order count----"+ordercount);
//editcount=adaptercount * ordercount;
Log.e("", "----edit count----"+editcount);
//Log.e("", "----order total value----"+orderTotal);
//recipeamount=orderTotal-editcount;
//Log.e("", "------recipe amount-------"+recipeamount);
imageArry.remove(lContact);
adapter.notifyDataSetChanged();// updating adapter
count = db.getContactsCount();
Log.d("", "----updated count----" + db.getContactsCount());
HelperActivity.num.setText(String.valueOf(count));
//toatalamount.setText(String.valueOf(recipeamount));
// YourOrder.toatalamount.setText();
}
});
holder.quantity.setText("1");
Contact picture = data.get(position);
holder.txtTitle.setText(picture._name);
// convert byte to bitmap take from contact class
byte[] outImage = picture._image;
ByteArrayInputStream imageStream = new ByteArrayInputStream(
outImage);
Bitmap theImage = BitmapFactory.decodeStream(imageStream);
holder.imgIcon.setImageBitmap(theImage);
// db.deleteContact(null);
return row;
}
public class ImageHolder {
ImageView imgIcon;
TextView txtTitle;
TextView dlttxt;
EditText quantity;
TextView recipeprice;
}
private class MyTextWatcher implements TextWatcher{
private View view;
private MyTextWatcher(View view) {
this.view = view;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//do nothing
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
//do nothing
}
public void afterTextChanged(Editable s) {
DecimalFormat df = new DecimalFormat("0.00##");
String qtyString = s.toString().trim();
int quantity = qtyString.equals("") ? 0:Integer.valueOf(qtyString);
qtyView = (EditText) view.findViewById(R.id.quantity);
// here i am getting the quantity value i want to store thid value into db
Contact contact = (Contact) qtyView.getTag();
// quantityt.setText(qtyView.getText());
if(contact.getQuantity() != quantity){
int currPrice = contact.getExt();
extPrice = quantity * contact.getprice();
Double priceDiff = Double.valueOf(df.format(extPrice - currPrice));
contact.setQuantity(quantity);
contact.setExt(extPrice);
TextView setprice = (TextView) view.findViewById(R.id.setprice);
if(contact.getQuantity() != 0){
setprice.setText("$" + df.format(contact.getExt()));
}
else {
setprice.setText("");
}
if(contact.getQuantity() != 0){
qtyView.setText(String.valueOf(contact.getQuantity()));
}
else {
qtyView.setText("");
}
orderTotal += priceDiff;
toatalamount.setText(df.format(orderTotal));
ordertotalval=toatalamount.getText().toString();
Log.e("----total value----", "------total value-----"+ordertotalval);
}
}
}
}
}
you can update using update method in sqlite,
ContentValues values=new ContentValues();
values.put(update_column_name, value_of_update_column);
db.update(DATABASE_TABLE_NAME, values, condition_field_name+" =?", new String[] {condition_value_});
However to update row you are having id for it in your table. In Where condition use that id for updating particular row.
Try like this
public SQLiteDatabase db;
String UpdateVAlue = editText.getText().toString(); // Getting edittext value
ContentValues updateValues = new ContentValues();
updateValues.put("ColomnFieldName", UpdateVAlue); // adding thevalues in Content view
db.update("TABLE_NAME", updateValues, WHERE,new String[] {
String.valueOf(ConditionValue) });

edittext value changes position while scrolling in custom listview in android

I have created a custom list view with 6 colomns. Each row is populated.
the first 3 fields are textviews,which are filled from db. Then a spinner and the last two edittexts.
i want to enter values to edittexts and spinner.. this much is ok.
The problem is when i enter values in edittext and after that if i scroll the list, the values entered in edittext changes in position. if i entered in first row, after scrolling it will be in last row or any other.. how i can solve this.. Need help pls..
My adapter class is given below.
public class CustomTransAdapter extends BaseAdapter {
public ArrayList<retrieveTrans> ret_arrArrayList;
private List<retrieveTrans> ret_translist;
private LayoutInflater inflater;
ArrayAdapter<String> adapterspin;
String time, currntdate, status;
String Maxcramnt, balamount;
double Mamount, Bamount, actualamnt;
String idpref, str_agent_id2, accno;
int trcheck;
int d = 0;
String tramnt = "", remarks = "";
Context context;
int count;
public CustomTransAdapter(NewTransactionSheet newTransactionSheet,
int transListPop, List<retrieveTrans> translist) {
// TODO Auto-generated constructor stub
super();
this.ret_translist = translist;
inflater = LayoutInflater.from(newTransactionSheet);
this.ret_arrArrayList = new ArrayList<retrieveTrans>();
this.ret_arrArrayList.addAll(translist);
this.context = newTransactionSheet;
String[] items = new String[] { "Type", "credit", "debit" };
final ArrayAdapter<String> adapterspin = new ArrayAdapter<String>(
newTransactionSheet, android.R.layout.simple_spinner_item,
items);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return ret_translist.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return ret_translist.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
class ViewHolder {
TextView acc_txt, name_txt, balAmnt_txt;
Spinner trans_spinner;
EditText transAmnt_edittxt, remarks_edittxt;
Button save;
}
#Override
public View getView(final int pos, View cv, ViewGroup arg2) {
// TODO Auto-generated method stub
try {
final ViewHolder holder;
View row = cv;
int p = pos;
Log.e("position of getview:", "" + p);
if (cv == null) {
cv = inflater.inflate(R.layout.trans_pop_list, null);
holder = new ViewHolder();
holder.acc_txt = (TextView) cv
.findViewById(R.id.txtTransAccNo_pop);
holder.name_txt = (TextView) cv
.findViewById(R.id.txtTransName_pop);
holder.balAmnt_txt = (TextView) cv
.findViewById(R.id.txtTransBalAmnt_pop);
holder.trans_spinner = (Spinner) cv
.findViewById(R.id.spinTrans_Type);
holder.transAmnt_edittxt = (EditText) cv
.findViewById(R.id.editTransAmnt_pop);
holder.save = (Button) cv.findViewById(R.id.save);
holder.remarks_edittxt = (EditText) cv
.findViewById(R.id.editRemarks_pop);
cv.setTag(holder);
} else {
holder = (ViewHolder) cv.getTag();
}
holder.acc_txt.setText("" + ret_translist.get(pos).getRetAccNo());
String hari = holder.acc_txt.getText().toString();
holder.name_txt.setText("" + ret_translist.get(pos).getRetName());
holder.balAmnt_txt.setText(""
+ ret_translist.get(pos).getRetBalAmnt());
String[] items = new String[] { "Type", "credit", "debit" };
final ArrayAdapter<String> adapterspin = new ArrayAdapter<String>(
context, android.R.layout.simple_spinner_item, items);
final String haris = holder.name_txt.getText().toString();
holder.trans_spinner.setAdapter(adapterspin);
/* ******************* Save button Click **************** */
holder.save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int position = pos;
final String accno = holder.acc_txt.getText().toString();
final String tramnt = holder.transAmnt_edittxt.getText()
.toString();
String remarks = holder.remarks_edittxt.getText()
.toString();
final String spinner = holder.trans_spinner
.getSelectedItem().toString();
Log.e("accno:", "" + accno);
Log.e("name :", "" + tramnt);
Log.e("position:", "" + position);
Log.e("remark:", "" + remarks);
Log.e("spinner:", "" + spinner);
/****************** time and date **********************/
// ----------Time----------
Calendar c = Calendar.getInstance();
time = (c.get(Calendar.HOUR) + ":" + c.get(Calendar.MINUTE)
+ ":" + c.get(Calendar.SECOND));
Log.e("Current Time", " " + time);
// -----------Date---------
Date now = new Date();
Date alsoNow = Calendar.getInstance().getTime();
currntdate = new SimpleDateFormat("M-d-yyyy").format(now);
Log.e("Date ", " " + currntdate);
status = new String("y");
if (tramnt.equals("")) {
Toast.makeText(arg0.getContext(),
"enter Transaction amount", 5000).show();
Log.e("if cndition", " " + tramnt);
} else if (spinner.equals("type")) {
Toast.makeText(arg0.getContext(),
"enter Transaction type", 5000).show();
Log.e("if cndition", " " + tramnt);
}
else {
if (remarks.equals("")) {
remarks = "null";
}
/************ declaration for dbcall *********************/
AccountDBAdapter db = new AccountDBAdapter(context);
NewTransactionSheet ts = new NewTransactionSheet();
try {
db.open();
String accid = db.getAccID(accno);
String Maxcramnt = db.getMaxCrAmnt(accno);
db.close();
Mamount = Double.parseDouble(Maxcramnt);
Bamount = Double.parseDouble(tramnt);
actualamnt = Mamount - Bamount;
balamount = "" + actualamnt;
db.open();
db.close();
/* Log.e("c value", " " +actualamnt); */
Log.e("tramnt", " " + tramnt);
Log.e("if cndition out", " " + tramnt);
db.open();
db.update_MaxCrAmnt(balamount, accid);
db.close();
actualamnt = 0;
db.open();
String userId = "" + 2;
db.insertTransactionTable(accid.toString(),
currntdate.toString(), spinner.toString(),
tramnt.toString(), userId.toString(),
time.toString(), remarks.toString(),
status.toString());
db.close();
holder.save.setText("SAVED");
holder.save.setBackgroundColor(Color.DKGRAY);
// }
} catch (Exception e) {
Log.e("error", e.getMessage());
}
}
}
});
} catch (Exception c) {
Log.e("adapter error", "" + c.getMessage());
}
return cv;
}
}
Working on this for many days... need help.. Thanks in advance.

Categories

Resources