How set text elements from 2 differents table in custom adapter? - android

There is my class with custom adapater
It's working with date and title.
Date and title are with table Page and textTag with Table Tag
public class MyAdapter extends ArrayAdapter <PageTag> {
Context context;
int ressource;
ArrayList<Page> data ;
TextView tvTitreList;
TextView tvDateList;
TextView tvTagList;
Page page;
public MyAdapter(Context context, ArrayList <PageTag> data ) {
super(context, 0, data);
}
My getView method.
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.activity_list_perso, parent, false);
}
tvTitreList = (TextView) convertView.findViewById(R.id.tvTitre);
tvDateList = (TextView) convertView.findViewById(R.id.tvDate);
tvTagList = (TextView) convertView.findViewById(R.id.tvTag);
tvTitreList.setText(getItem(position).getPage().titrePage);
tvDateList.setText(getItem(position).getPage().datePage.toString());
tvTagList.setText(getItem(position).getTag().texteTag);
return convertView;
}
}
My table PageTag
public class PageTag {
Page page ;
Tag tag ;
public PageTag ( Page page, Tag tag){
this.page = page;
this.tag = tag;
}
// with getter and setter
my ListPageActivity
pageMgr = new PageMgr(this);
lvList = (ListView) findViewById(R.id.listPage);
ArrayList<Page> listPage = pageMgr.getAllPageArray();
ArrayList<Tag> listTag = pageMgr.getAllTagArray();
ArrayList<PageTag> pageTag = new ArrayList<>();
for(int i = 0 ;i < listPage.size() ;i++){
Page page = listPage.get(i);
Tag tag = listTag.get(i);
(cannot resolve method) ==> pageTag.setPage(page);
==> pageTag.setTag(tag);
}
MyAdapter myAdapt = new MyAdapter(this,pageTag);
lvList.setAdapter(myAdapt);
getAllpageArray method
public ArrayList<Page> getAllPageArray(){
ArrayList <Page> listPageArray = new ArrayList <Page>();
String rqPage = " SELECT * FROM " + BaseSQLITE.TABLE_PAGE
+ " JOIN " + BaseSQLITE.TABLE_LIENS_TAG_PAGE
+ " ON " + BaseSQLITE.TABLE_PAGE+ "." + BaseSQLITE.COL_ID_PAGE + " = " + BaseSQLITE.TABLE_LIENS_TAG_PAGE+ "." + BaseSQLITE.COL_ID_PAGE_LTP
+ " JOIN " + BaseSQLITE.TABLE_TAG
+ " ON "+ BaseSQLITE.TABLE_TAG+ "." + BaseSQLITE.COL_ID_TAG + " = " + BaseSQLITE.TABLE_LIENS_TAG_PAGE+ "." + BaseSQLITE.COL_ID_TAG_LTP ;
Cursor cPage;
this.open();
cPage = bdd.rawQuery(rqPage,null);
Date date;
long l;
String titre;
while (cPage.moveToNext()){
String titrePage ;
Date datePage ;
l = cPage.getLong(2);
titrePage = cPage.getString(1);
datePage = new Date(l);
listPageArray.add(new Page(titrePage,datePage));
}
this.close();
return listPageArray;
}
same thing for getAllTagArray

Create a new Model class
class Result{
Page page;
Tag tag;
//getters and setters
}
Now loop your result and add it to List of Result
ArrayList<Result> result = new ArrayList<>();
for(int i=0 ;i < listPage.size() ;i++){
Page page = listPage.get(i);
Tag tag = tagList.get(i);
result.setPage(page);
result.setTag(tag);
}
In your adapter change Page to Result
tvTitreList.setText(getItem(position).getPage().getTitrePage());
tvDateList.setText(getItem(position).getPage().getDatePage().toString());
tvTagList.setText(getItem(position).getTag().getTextTag());

Finally it's ok with your method I have changed some code.
thanks to you #rajan ks
pageMgr = new PageMgr(this);
lvList = (ListView) findViewById(R.id.listPage);
ArrayList<Page> listPage = pageMgr.getAllPageArray();
ArrayList<Tag> listTag = pageMgr.getAllTagArray();
ArrayList<PageTag> pageTag = new ArrayList<>();
for(int i = 0 ;i < listPage.size() ;i++) {
Page page = listPage.get(i);
Tag tag = listTag.get(i);
PageTag pageT = new PageTag(page, tag);
pageTag.add(pageT);
}
MyAdapter myAdapt = new MyAdapter(this,pageTag);
lvList.setAdapter(myAdapt);

Related

When recall methods Fragment not attached to a context Error. What context should i send and receive?

At first my sendData method is working but when I call it from another activity it has 'not attached to a context.' error.
When I opened it looks work, but after i delete some data it wasn't work.
Here is my code.
DeleteDialog.java
public class DeleteDialog extends android.support.v4.app.DialogFragment {
private Context mContext;
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_delete_dialog, container, false);
mContext=this.getContext();
...
ok_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(editText.getText().toString().equals("")){
Toast.makeText(getContext(), "과목명을 입력해 주세요", Toast.LENGTH_SHORT).show();
}else{
dbHelper = new DBHelper(mContext);
db = dbHelper.getWritableDatabase();
dbHelper.deleteColum(editText.getText().toString());
timeTableFragment.sendData(mContext);
getDialog().dismiss();
}
}
});
TimeTableFragment.java
public class TimeTableFragment extends Fragment {
private Context mContext;
public void sendData(Context context) { //get data and draw to layout
dbHelper = new DBHelper(context);
db = dbHelper.getWritableDatabase();
dbHelper.onCreate(db);
String date = "", start = "", end = "", title = "", color = "";
ArrayList<SubjectItem> timetable_data;
timetable_data = dbHelper.getDataTimetable(); //get data from sql
SimpleDateFormat sf = new SimpleDateFormat("HHmm");
int resID = 0;
int mok;
Date a, b;
long diff, min;
View view = getView();
for (int i = 0; i < timetable_data.size(); i++) { // draw to layout
date = timetable_data.get(i).getSub_date();
start = timetable_data.get(i).getSub_start();
end = timetable_data.get(i).getSub_end();
title = timetable_data.get(i).getSub_title();
color = timetable_data.get(i).getSub_color();
if (date.substring(0, 2).equals("Th")) {
date = "h";
Log.d("ㄹㄹ","목요일 : " +date);
}
date = date.toLowerCase().substring(0, 1);
Log.d("ㄹㄹ","바깥의 데이터 : " +date);
start = start.replace(":", "");
end = end.replace(":", "");
try {
a = sf.parse(start);
b = sf.parse(end);
diff = b.getTime() - a.getTime();
min = (diff / (1000 * 60));
mok = (int) min / 30;
Log.d(TAG,"title " +title + " start : " + start +","+ a.getTime()+ " / end : " + end+","+b.getTime() + " date : " + date);
for (int k = 0; k < mok; k++) {
if (mok != 1) {
if (end.substring(2, 4).equals("30")) {
end = Integer.toString(Integer.parseInt(end) - 30);
if (end.length() == 3) end = "0" + end;
Log.d(TAG, " 그리기 title : " +title );
//Log.d(TAG , "콘텍스트 : " + getContext().getPackageName());
Error -> resID = getResources().getIdentifier(date + end, "id", getContext().getPackageName());
TextView textView = (TextView) view.findViewById(resID);
textView.setText(title);
paintTimetable(textView,color);
} else {
end = Integer.toString(Integer.parseInt(end) - 70);
if (end.length() == 3) end = "0" + end;
Log.d("Contxet " , "콘텍스트 : " + getContext().getPackageName());
resID = getResources().getIdentifier(date + end, "id", getContext().getPackageName());
TextView textView = (TextView) view.findViewById(resID);
textView.setText(title);
paintTimetable(textView,color);
Log.d(TAG, " 그리기 title : " +title);
}
} else {
Log.d("Contxet " , "콘텍스트 : " + getContext().getPackageName());
resID = getResources().getIdentifier(date + start, "id", getContext().getPackageName());
TextView textView = (TextView) view.findViewById(resID);
textView.setText(title);
paintTimetable(textView,color);
}
}
} catch (ParseException e) {
e.printStackTrace();
}
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try {
mContext=getContext();
} catch (ClassCastException e) {
Log.d(TAG, "Exception" + e.getMessage());
}
}
DBHelper.java
public class DBHelper extends SQLiteOpenHelper {
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
...
public void deleteColum(String name)
{
String DELETE = "DELETE FROM " + TABLE_TIMETABLE + " WHERE " + KEY_TITLE + "='" + name + "'";
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL(DELETE);
Log.d("dd", "sql deleted : " + name);
}
And Error message :
Fragment TimeTableFragment{f4aa844} not attached to a context.
In DB Insert, Delete are perfectly works but after call sendData method in DeleteDialog occurred 'not attached to a context'.
What context should I send and receive?
All database tasks should be done in async (another thread). It might take a while and after job is done you should come back to main thread and check if the view still exist, this way you will avoid memory leaks and error that you mentioned.
Use getApplicationContext() for initializing your DBHelper. This will ensure proper context of your app and does create the error you are receiving.
Addtional Info:
Make your DBHelper as Singleton it will optimize your app resources.

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

Android and delete items from ListView and sqlite database

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

Creating custom listview from pre-existing arraylist

I'm obviously missing something in making this custom adapter. Basically, I've got code that grabs JSON from the site, then breaks it down into a ArrayList. I can do a .toString() and spit it all out onto a listview just fine, but everything I find on the net for creating a custom adapter creates the list inside of it. Is there a way to just supply your pre-created list? I've yet to make any headway on getting the custom one to work...but, as I said I can get the string to work just fine, so I'll include that code.
Here's my classes:
public class JSONEvents {
String eid;
String bid;
private String bname;
private String valid;
#Override
public String toString() {
return "Events [eid=" + eid + ", bid=" + bid + ", bname=" + bname
+ ", start=" + start + ", end=" + end + ", points=" + points
+ ", title=" + title + ", description=" + description
+ ", cat=" + cat + ", type=" + type + ", subtype=" + subtype
+ ", valid=" + valid + "]";
}
public String getEventInfo(String field){
if("eid".equals(field)){return eid;}
else if("bid".equals(field)){return bid;}
else if("bname".equals(field)){return bname;}
else if("valid".equals(field)){return valid;}
return "none";
}
}
public class JSONAdventures {
private String aid;
private String bid;
private String start;
private String valid;
#Override
public String toString() {
return "Adventures [aid=" + aid + ", bid=" + bid + ", start=" + start
+ ", end=" + end + ", points=" + points + ", title=" + title
+ ", description=" + description + ", cat=" + cat + ", type="
+ type + ", subtype=" + subtype + ", steps_comp=" + steps_comp
+ ", total_steps=" + total_steps + ", valid=" + valid + "]";
}
public String getEventInfo(String field){
if("aid".equals(field)){return aid;}
else if("bid".equals(field)){return bid;}
else if("start".equals(field)){return start;}
else if("valid".equals(field)){return valid;}
return "none";
}
}
public class JSONEandA {
private ArrayList<JSONEvents> events;
private ArrayList<JSONAdventures> adventures;
#Override
public String toString() {
return "ResponseHolder [events=" + events + ", adventures="
+ adventures + "]";
}
public ArrayList<JSONEvents> getJSONEvents() {
return events;
}
public ArrayList<JSONAdventures> getJSONAdventures() {
return adventures;
}
}
For the code in m activity:
List<JSONEvents> eventlist = new ArrayList<JSONEvents>();
try {
Gson googleJson = new Gson();
JSONEandA rh = googleJson.fromJson(example,
JSONEandA.class);
for (JSONEvents e : rh.getJSONEvents()) {
eventlist.add(e);
//eventlist.addAll(e);
// System.out.println(e.toString());
System.out.println(e.getEventInfo("eid"));
System.out.println(e.toString());
}
final ListView listview = (ListView) findViewById(R.id.eventlistview);
String[] values = new String[eventlist.size()];
eventlist.toArray(values);
// String[] values = new String[] {e.toString()};
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(
Events.this,
android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
final View view, int position, long id) {
final String item = (String) parent
.getItemAtPosition(position);
list.remove(item);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(),
"Item Removed", Toast.LENGTH_LONG).show();
});
I've also pieced together an attempt at an adapter from various tutorials and such, but can't figure out how to tie it all together:
class EventAdapter extends ArrayAdapter<JSONEvents> {
private ArrayList<JSONEvents> items;
public EventAdapter(Context context, int textViewResourceId,
ArrayList<JSONEvents> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_events, null);
}
JSONEvents q = items.get(position);
if (q != null) {
TextView nameText = (TextView) v.findViewById(R.id.firstline);
TextView priceText = (TextView) v.findViewById(R.id.secondLine);
if (nameText != null) {
nameText.setText(q.getEventInfo("eid"));
}
if (priceText != null) {
priceText.setText(q.getEventInfo("bid"));
}
}
return v;
}
}
I would appreciate any help, thanks!
Did you put tha data into your adapter?
adapter.addAll(String[] data);
Or you could do it while creating adapter:
EventAdapter adapter = new EventAdapter(this, R.id.some_id, eventlist);

Display Data from a database in a listview with a arrayadapter

Hy guys!
I've got a problem. My app should display all routes in a listview. But there is something wrong with the arrayadapter. If i try my arrayadapter like this:
ArrayAdapter<DefineRoute> adapter = new ArrayAdapter<DefineRoute>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
it works, but it only display the objectname of DefineRoute and i wanna display the output of the cursor.
Ithink i should try:
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
But here comes the error: Cannot resolve constructor ArrayAdapter
Here is my Acticity:
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated constructor stub
super.onCreate(savedInstanceState);
setContentView(R.layout.planausgabelayout);
//Aufruf der TextViews
TextView txtStart = (TextView)findViewById(R.id.txtAusgabeStart);
TextView txtZiel = (TextView)findViewById(R.id.txtAusgabeZiel);
TextView txtZeit = (TextView)findViewById(R.id.txtAusgabeZeit);
intent = getIntent();
txtStart.setText(intent.getStringExtra("StartHaltestelle"));
txtZiel.setText(intent.getStringExtra("ZielHaltestelle"));
txtZeit.setText(intent.getStringExtra("Zeit"));
getRoute();
}
public void getRoute() {
lvList = (ListView)findViewById(R.id.lvList);
Verbindungen verbindungen = new Verbindungen(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
this, android.R.layout.simple_list_item_1,verbindungen.getVerbindungen());
lvList.setAdapter(adapter);
}
Here is my Activity Define Route:
public class DefineRoute {
private String abfahrtszeit;
private String ankunftszeit;
private String dauer;
private String umstieg;
public DefineRoute(String abfahrtszeit, String ankunftszeit, String dauer, String umstieg)
{
this.abfahrtszeit = getAbfahrtszeit();
this.ankunftszeit = getAnkunftszeit();
this.dauer = getDauer();
this.umstieg = getUmstieg();
}
public String getAbfahrtszeit() {
return abfahrtszeit;
}
public String getAnkunftszeit() {
return ankunftszeit;
}
public String getDauer() {
return dauer;
}
public String getUmstieg() {
return umstieg;
}
}
Here is my Activity Verbindungen:
public class Verbindungen {
SQLiteDatabase db;
LinkedList<DefineRoute> route;
DefineRoute[] routeArray;
Context context;
DatabaseHelper myDbHelper = null;
public Verbindungen(Context context) {
route = new LinkedList<DefineRoute>();
this.context = context;
myDbHelper = new DatabaseHelper(context);
}
public DefineRoute[] getVerbindungen() {
try {
myDbHelper.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
}catch(SQLException sqle){
throw sqle;
}
db = myDbHelper.getReadableDatabase();
// Alle Daten der Datenbank abrufen mithilfe eines Cursors
Cursor cursor = db.rawQuery("SELECT strftime('%H:%M', f.abfahrt) AS Abfahrt," +
"strftime('%H:%M', f.ankunft) AS Ankunft," +
"strftime('%H:%M', strftime('%s',f.ankunft)- strftime('%s',f.abfahrt), 'unixepoch') AS Dauer," +
"r.name AS Route," +
"count(u.fahrt_id) AS Umstiege " +
"FROM scotty_fahrt f " +
"JOIN scotty_haltestelle start ON f.start_id = start.id " +
"JOIN scotty_haltestelle ziel ON f.ziel_id = ziel.id " +
"JOIN scotty_route r ON f.route_id = r.id " +
"LEFT OUTER JOIN scotty_umstiegsstelle u ON f.id = u.fahrt_id " +
"WHERE start.name = 'Linz/Donau Hbf (Busterminal)' " +
"AND ziel.name = 'Neufelden Busterminal (Schulzentrum)' " +
"GROUP BY u.fahrt_id",null);
cursor.moveToFirst();
int i=0;
while (cursor.moveToNext()){
//in this string we get the record for each row from the column "name"
i++;
}
routeArray = new DefineRoute[i];
cursor.moveToFirst();
int k =0;
while (cursor.moveToNext())
{
routeArray[k] = new DefineRoute(cursor.getString(0),cursor.getString(1),cursor.getString(2),
cursor.getString(3));
k++;
}
//here we close the cursor because we do not longer need it
//}
cursor.close();
myDbHelper.close();
return routeArray;
}
please help me.
Now i am creating a ArrayAdapter class where i define my ouput in the listview with:
public class RouteAdapter extends ArrayAdapter<DefineRoute>{
Activity context;
DefineRoute[] defineroute;
public RouteAdapter(Activity context, DefineRoute[] defineroute){
super(context, R.layout.layoutausgabe, defineroute);
this.defineroute = defineroute;
this.context = context;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = context.getLayoutInflater();
View row = inflater.inflate(R.layout.layoutausgabe,null);
TextView txZeit = (TextView)row.findViewById(R.id.txZeit);
TextView txDauer = (TextView)row.findViewById(R.id.txDauer);
TextView txUmstieg = (TextView)row.findViewById(R.id.txUmstieg);
DefineRoute defineRoute = defineroute[position];
txZeit.setText(defineRoute.getAbfahrtszeit() + " - " + defineRoute.getAnkunftszeit());
txDauer.setText(defineRoute.getDauer());
txUmstieg.setText(defineRoute.getUmstieg());
return row;
}
}
How should i continue?
and what should my adapter look like?
Your ArrayAdapter<String> is type of String so pass String list to it's constructor instead of verbindungen.getVerbindungen() list of objects.
ArrarAdapter < T > is any type of class you can use
in your case ArrayAdapter so you need override toString method of DefineRoute class
in your case
#Override
public String toString() {
return ankunftszeit+" "+ankunftszeit;
//or what ever you want to displat
}
or there is other Solution is Create your Own adapter extending by BaseAdapter Class.

Categories

Resources