ArrayAdapter error when database is empty - android

I'm trying to adapt my data from my SQLite database to my ListView, when the table has some lines, there is no problem, but when I delete all the inserts from the table, I have an error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toString()' on a null object reference
My adapter's code:
public class AdapterTop extends ArrayAdapter<Top> {
private LayoutInflater mInflat;
private ArrayList<Top> top = new ArrayList<Top>();
private int mVRessId;
public AdapterTop (Context context, int ressId, ArrayList<Top> topu){
super(context,ressId,topu);
this.top =topu;
mInflat = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mVRessId =ressId;
}
public View getView(int position, View convertedView, ViewGroup parents){
convertedView = mInflat.inflate(mVRessId,null);
Top topu = top.get(position);
if (topu != null) {
TextView name = (TextView) convertedView.findViewById(R.id.txtnomp);
TextView nbre = (TextView) convertedView.findViewById(R.id.txtnbre);
if (name != null) {
name.setText("" + topu.getNom() + ": " + topu.getPrenom());
}
if (nbre != null) {
nbre.setText(String.valueOf(+topu.getNum()));
}
}
return convertedView;
}
}
The function used to return the cursor:
public Cursor topuser(){
SQLiteDatabase db = this.getReadableDatabase();;
Cursor data = db.rawQuery("Select U." +KEY_NOM+ ", U." +KEY_PRENOM+ ", count (A." +KEY_MATRICULE+ " ) FROM " +TABLE_ANSWER+ " A, "+TABLE_USER+ " U where U." +KEY_MATRICULE+ " = A." +KEY_MATRICULE+ " LIMIT 3",null );
return data;
}
My main java code:
ArrayList<Top> users;
Top top;
mCsr = openhelper.topuser();
int rows = mCsr.getCount();
if (rows == 0) {
Toast.makeText(Kpis.this, "no users", Toast.LENGTH_LONG).show();
} else {
while (mCsr.moveToNext()) {
top = new Top(mCsr.getString(0).toString(), mCsr.getString(1).toString(), mCsr.getInt(2));
users.add(top);
}
AdapterTop adapttop = new AdapterTop(this, R.layout.activity_template_top_users, users);
mListView.setAdapter(adapttop);
}
Is there any problem with that? I did the condition if (rows == 0) tu avoid this but still have the same problem.
The Top classe is made like that:
public class Top {
private String nom;
private String prenom;
private int num;
public Top(String nom, String prenom, int num) {
this.nom = nom;
this.prenom = prenom;
this.num = num;
}
public String getNom() {
return nom;
}
public String getPrenom() {
return prenom;
}
public int getNum() {
return num;
}
}
I tried to initiate the top when creating it but didn't work.

I did the condition if (rows == 0) tu avoid this but still have the same problem.
It'll prevent you getting an out of bounds exception, but probably when you saved your data, the columns were nullable. So do you have records, but this record have some field null.
At this point:
top = new Top(mCsr.getString(0).toString(), mCsr.getString(1).toString(), mCsr.getInt(2));
You are calling toString() on something you do know what.
So the easy way to handle this error would be:
String noum = "";
if(mCsr.getString(0) != null){
noum = mCsr.getString(0).toString()
}
String preNoum = "";
if(mCsr.getString(1) != null){
preNoum = mCsr.getString(1).toString()
}
top = new Top(noum, preNoum, mCsr.getInt(2));
You could improve your code with some patterns, but it'll do the trick.

Related

My DBHelper and Fragment don't get along argument at index 1 because the index is out of range. The statement has 0 parameters

First time ask here, so please be strict to me. :)
So many times the questions was asked but I still can't get a clue what is wrong in my case.
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.hfad.mydic, PID: 4481
java.lang.IllegalArgumentException: Cannot bind argument at index 1 because the index is out of range. The statement has 0 parameters.
at android.database.sqlite.SQLiteProgram.bind(SQLiteProgram.java:212)
at android.database.sqlite.SQLiteProgram.bindString(SQLiteProgram.java:166)
at android.database.sqlite.SQLiteProgram.bindAllArgsAsStrings(SQLiteProgram.java:200)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:49)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1408)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1347)
at com.hfad.mydic.DBHelper.getSentence(DBHelper.java:100)
at com.hfad.mydic.DetailFragment.onViewCreated(DetailFragment.java:61)
...
Here my DBHelper
public ArrayList<String> getSentence(int dicType) {
String tableName = getTableName(dicType);
String q = " SELECT * FROM " + tableName;
Cursor result = mDB.rawQuery(q, null);
ArrayList<String> source = new ArrayList<>();
while (result.moveToNext()) {
source.add(result.getString(result.getColumnIndex(COL_text)));
}
return source;
}
public Sentence getSentence(String id, int dicType) {
String tableName = getTableName(dicType);
String q = " SELECT * FROM " + tableName + " WHERE upper([id])=upper('?')";
Cursor result = mDB.rawQuery(q, new String[]{id}); //What is wrong here?
Sentence sentence = new Sentence();
while (result.moveToNext()) {
sentence.id = result.getString(result.getColumnIndex(COl_id));
sentence.textlanguage = result.getString(result.getColumnIndex(COL_text));
}
return sentence;
}
DetailFragment
public class DetailFragment extends Fragment {
private String DFvalue = "";
private TextView tvWord;
private ImageButton btnBookmark, btnVolume;
private WebView tvWordTranslate;
private DBHelper mDBHelper;
private int mDicType;
public DetailFragment() {
// Required empty public constructor
}
public static DetailFragment getNewInstance(String value, DBHelper dbHelper, int dicType) {
DetailFragment fragment = new DetailFragment();
fragment.DFvalue = value;
fragment.mDBHelper = dbHelper;
fragment.mDicType = dicType;
return fragment;
}
...
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tvWord = view.findViewById(R.id.tvWord);
tvWordTranslate = view.findViewById(R.id.tvWordTranslate);
btnBookmark = view.findViewById(R.id.btnBookmark);
btnVolume = view.findViewById(R.id.btnVolume);
Sentence sentence = mDBHelper.getSentence(DFvalue, mDicType); //What is wrong here?
tvWord.setText(sentence.id);
tvWordTranslate.loadDataWithBaseURL(null, sentence.textlanguage, "text/html", "utf-8", null);
Sentence bookmarkSentence = mDBHelper.getSentenceFromBookmark(DFvalue);
int isMark = bookmarkSentence == null ? 0 : 1;
btnBookmark.setTag(isMark);
int icon = bookmarkSentence == null ? R.drawable.ic_bookmark_border : R.drawable.ic_bookmark_fill;
btnBookmark.setImageResource(icon);
btnBookmark.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int i = (int) btnBookmark.getTag();
if (i == 0) {
btnBookmark.setImageResource(R.drawable.ic_bookmark_fill);
btnBookmark.setTag(1);
} else if (i == 1) {
btnBookmark.setImageResource(R.drawable.ic_bookmark_border);
btnBookmark.setTag(0);
}
}
});
}
Parameters like ? should not be in quotes. '?' is a literal question mark string, ?denotes a parameter.

Skip duplicated entries on Call Log

I'm developing an Android Auto like app, where I want to show the call log using recyclerview and cards.
This is working fine, but the call log is showing all the logs. Lets say that if I have received 3 calls from Peter, I don't want to see 3 entries showing this, with one entry enought. This will be like doing something like "most recent contacts" or something like that.
When using the recyclerview and cards, I've created 3 classes to hold the contacts info: The custom adapter, the contact info, and the custom view holder.
This is the ContactInfo class:
public class ContactInfo {
public int id;
public String name;
public String type;
public static final String ID_PREFIX = "ID_";
public static final String NAME_PREFIX = "Name_";
public static final String TYPE_PREFIX = "Type_";
}
Then, in the fragment where I show the call log, this is what I do to display the logs:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.phone_layout, container, false);
...
ContactAdapter contactAdapter = new ContactAdapter(DisplayCallLog());
...
return view;
}
private ArrayList<ContactInfo> DisplayCallLog() {
ArrayList<ContactInfo> data = new ArrayList<ContactInfo>();
int contactID = 0;
String contactNumber = null;
int logType = 0;
String contactName = null;
String contactType = null;
ContactInfo cI;
int resultLimit = 0;
//Check access to Call Log
if (ActivityCompat.checkSelfPermission(this.getActivity(), Manifest.permission.READ_CALL_LOG) == PackageManager.PERMISSION_GRANTED) {
//Get phone numbers from call log
Cursor cursorCallLog = getActivity().getContentResolver().query(CallLog.Calls.CONTENT_URI,
null, null, null, CallLog.Calls.DATE + " DESC");
while (cursorCallLog.moveToNext() && resultLimit<6) {
contactNumber = cursorCallLog.getString(cursorCallLog.getColumnIndex(CallLog.Calls.NUMBER));
//We also get the call type: Incoming, Outgoing, missed
logType = cursorCallLog.getInt(cursorCallLog.getColumnIndex(CallLog.Calls.TYPE));
resultLimit++;
//With the phone number we search the ID
String number = Uri.encode(contactNumber);
Cursor cursorContactLookup = getActivity().getContentResolver().query(
Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
number),
new String[]{ContactsContract.PhoneLookup.DISPLAY_NAME, ContactsContract.PhoneLookup._ID},
null, null, null);
while (cursorContactLookup.moveToNext()) {
contactID = cursorContactLookup
.getInt(cursorContactLookup
.getColumnIndexOrThrow(ContactsContract.PhoneLookup._ID));
//Get the contact name and phone type
Cursor cursorContactDetails = getActivity().getContentResolver().query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[] {
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Phone.TYPE,
},
ContactsContract.Data.CONTACT_ID + "=?",
new String[] {String.valueOf(contactID)}, null);
while (cursorContactDetails.moveToNext()) {
contactName = cursorContactDetails
.getString(cursorContactDetails
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
int type = cursorContactDetails
.getInt(cursorContactDetails
.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.TYPE));
switch (type) {
case ContactsContract.CommonDataKinds.Phone.TYPE_HOME:
contactType = "Home";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_WORK:
contactType = "Work";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE:
contactType = "Mobile";
break;
case ContactsContract.CommonDataKinds.Phone.TYPE_OTHER:
contactType = "Other";
break;
}
//Call contactinfo class and save into list
cI = new ContactInfo();
cI.id = contactID;
cI.name = contactName;
cI.type = contactType;
//cI.logType = logType;
//HERE: CHECK IF LIST DOES NOT CONTAIN CURRENT CONTACT
if (!data.contains(cI)) {
data.add(cI);
}
}
cursorContactDetails.close();
}
cursorContactLookup.close();
}
cursorCallLog.close();
}
return data;
}
The problem I'm having is that cI shows a string like this:
I/CONTACT_INFO: com.example_infodash.phone.ContactInfo#41c9e198
Where the last numbers are allways diferent even if the contact saved is the same. So it never finds the same contact in the list, even if is duplicated.
So my question is, how could I check if the contact saved is already in the list? I guess that the trouble in this case is because of the use of a custom class like ContactInfo.
The problem I'm having is that cI shows a string like this:
I/CONTACT_INFO: com.example_infodash.phone.ContactInfo#41c9e198
Solution for this problem: Override toString method in ContactInfo
public class ContactInfo {
public int id;
public String name;
public String type;
public static final String ID_PREFIX = "ID_";
public static final String NAME_PREFIX = "Name_";
public static final String TYPE_PREFIX = "Type_";
#Override
public String toString() {
return "{name: " + name + ", type: " + type + "}";
}
}
For ArrayList 'contains' problem, you have to override equals() in ContactInfo. Like this:
public class ContactModel {
public String name;
public String phone;
public ContactModel(String name, String phone) {
this.name = name;
this.phone = phone;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ContactModel that = (ContactModel) o;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
return phone != null ? phone.equals(that.phone) : that.phone == null;
}
}
If you are in Android Studio you can create it automatically. Go to ContactInfo class, right click in it, choose:
Generate... -> equals() and hashCode()
Your equals() method:
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ContactInfo that = (ContactInfo) o;
if (that.name.equals(name) && that.id == id) return true;
else return false;
}

Check Row_id in database with other value in RecyclerView Adapter

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

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

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