I'm trying to get an item deleted from both my custom listview and from the database on button click. I got so far but from the code below you are likely to see my error. When the first item is deleted the positions change however the idarray info is not updated. Please help!
History Adapter:
package uk.co.rascagneres.clocking_app;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import java.util.ArrayList;
/**
* Created by Jacques on 08/08/2016.
*/
public class HistoryAdapter extends BaseAdapter implements ListAdapter{
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public ArrayList<String> idArray = new ArrayList<String>();
DatabaseHandler db;
public HistoryAdapter (ArrayList<String> list, Context context, ArrayList<String> idArray, DatabaseHandler db){
this.list = list;
this.context = context;
this.idArray = idArray;
this.db = db;
}
#Override
public int getCount(){
return list.size();
}
#Override
public Object getItem(int pos){
return list.get(pos);
}
#Override
public long getItemId(int pos){
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent){
View view = convertView;
if(view == null){
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.history_list, null);
}
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
System.out.println(list.get(position));
System.out.println(idArray.get(position));
System.out.print(idArray);
db.deleteRowID(Integer.parseInt(idArray.get(position)));
list.remove(position);
notifyDataSetChanged();
}
});
return view;
}
}
HistoryFragment:
package uk.co.rascagneres.clocking_app;
import android.app.Fragment;
import android.database.Cursor;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Jacques on 03/08/2016.
*/
public class HistoryFragment extends Fragment {
DatabaseHandler db;
View myView;
ArrayList<String> historyArray = new ArrayList<String>();
ArrayList<String> idArray = new ArrayList<String>();
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.history_layout, container, false);
db = new DatabaseHandler(getActivity());
ArrayList<String> list = insertData();
HistoryAdapter adapter = new HistoryAdapter(list, getActivity(), idArray, db);
ListView lView = (ListView)myView.findViewById(R.id.listView);
lView.setAdapter(adapter);
return myView;
}
public ArrayList<String> insertData(){
Cursor c = db.getAllData();
ArrayList<String> list = new ArrayList<String>();
while(c.moveToNext()) {
int id = c.getInt(0);
long in = c.getLong(1);
long out = c.getLong(2);
String outTime;
if(out == 0){
outTime = "N/A";
}else{
outTime = ClockingFragment.getDate(out, "HH:mm");
}
String date = ClockingFragment.getDate(in, "EEE, MMM d");
String inTime = ClockingFragment.getDate(in, "HH:mm");
historyArray.add(date + "\n Clocked In: " + inTime + "\n Clocked Out: " + outTime + "\n");
idArray.add(String.valueOf(id));
}
if (historyArray.isEmpty()){
historyArray.add("No History Available!");
}
return historyArray;
}
public ArrayList<String> getIdArray(){
System.out.println(idArray);
return idArray;
}
}
Section of Database Handler:
public void deleteRowID(int ID)
{
SQLiteDatabase db = this.getWritableDatabase();
String IDString = String.valueOf(ID);
try
{
db.delete(TABLE_NAME, "ID = ?", new String[] { IDString });
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
Related
I have a android studio project and use 'com.timehop.stickyheadersrecyclerview:library:0.4.3#aar'
library it works fine but when I create a new project using same code It show me the following error in line 26 StickyRecyclerHeadersAdapter<CustomAdapter.MyHeadingViewHolder> { of CustomAdapter class:
Type parameter 'com.vatexpress.service.CustomAdapter.MyHeadingViewHolder' is not within its bound; should extend 'android.support.v7.widget.RecyclerView.ViewHolder'
and also show me following error in line 75 recyclerView.addItemDecoration(new StickyRecyclerHeadersDecoration(customAdapter));of ManinActivity class:
Type parameter 'com.vatexpress.service.CustomAdapter.MyHeadingViewHolder' is not within its bound; should extend 'android.support.v7.widget.RecyclerView.ViewHolder'
Here is my CustomAdapter class:
package com.vatexpress.service;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.LinearLayout;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersAdapter;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyChildViewHolder>
implements Filterable,
StickyRecyclerHeadersAdapter<CustomAdapter.MyHeadingViewHolder> {
private Context context;
private Activity activity;
private ArrayList<Model> dataholder;
ArrayList<Model> backup;
MyDatabaseHelper obj = null;
String code, nature, name, sd, vat, vds, vat_ref, vds_ref, about;
public static final int CHILD_LIST = 1;
public static final int HEADER = 2;
CustomAdapter(Activity activity, Context context, ArrayList<Model> dataholder){
this.activity = activity;
this.context = context;
this.dataholder = dataholder;
backup=new ArrayList<>(dataholder);
}
#NonNull
#Override
public MyChildViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.my_row, parent, false);
return new MyChildViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull final MyChildViewHolder holder, final int position) {
// if (holder instanceof MyChildViewHolder) {
final Model temp=dataholder.get(position);
holder.service_code.setText(dataholder.get(position).getService_code());
holder.service_name.setText(dataholder.get(position).getService_name());
//Recyclerview onClickListener
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, DetailActivity.class);
obj = new MyDatabaseHelper(context);
Cursor cursor = obj.getData(temp.id);
if (cursor != null) {
if (cursor.moveToFirst()) {
do {
code = cursor.getString(0);
nature = cursor.getString(2);
name = cursor.getString(1);
sd = cursor.getString(3);
vat = cursor.getString(4);
vds = cursor.getString(5);
vat_ref = cursor.getString(6);
vds_ref = cursor.getString(7);
about = cursor.getString(8);
} while (cursor.moveToNext());
}
}
intent.putExtra("code", code);
intent.putExtra("nature", nature);
intent.putExtra("servicename", name);
intent.putExtra("sd", sd);
intent.putExtra("vat", vat);
intent.putExtra("vds", vds);
intent.putExtra("vat_ref", vat_ref);
intent.putExtra("vds_ref", vds_ref);
intent.putExtra("about", about);
activity.startActivityForResult(intent, 1);
}
});
// }
// else if(holder instanceof MyHeadingViewHolder) {
// MyHeadingViewHolder myHeadingViewHolder = (MyHeadingViewHolder) holder;
// myHeadingViewHolder.heading.setText(dataholder.get(position).service_heading);
// }
}
#Override
public long getHeaderId(int position) {
return dataholder.get(position).getSection();
}
#Override
public MyHeadingViewHolder onCreateHeaderViewHolder(ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.heading_layout, parent, false);
return new MyHeadingViewHolder(view);
}
#Override
public void onBindHeaderViewHolder(MyHeadingViewHolder myHeadingViewHolder, int i) {
myHeadingViewHolder.heading.setText(dataholder.get(i).getService_heading());
}
#Override
public int getItemCount() {
return dataholder.size();
}
#Override
public Filter getFilter() {
return filter;
}
Filter filter=new Filter() {
#Override
// background thread
protected FilterResults performFiltering(CharSequence keyword)
{
ArrayList<Model> filtereddata=new ArrayList<>();
if(keyword.toString().isEmpty())
filtereddata.addAll(backup);
else
{
for(Model obj : backup)
{
if(obj.getService_name().toString().toLowerCase().contains(keyword.toString().toLowerCase()))
filtereddata.add(obj);
}
}
FilterResults results=new FilterResults();
results.values=filtereddata;
return results;
}
#Override // main UI thread
protected void publishResults(CharSequence constraint, FilterResults results)
{
dataholder.clear();
dataholder.addAll((ArrayList<Model>)results.values);
notifyDataSetChanged();
}
};
// #Override
// public int getItemViewType(int position) {
// if (dataholder.get(position).typeHeading)
// {
// return HEADER;
// }
// else {
// return CHILD_LIST;
// }
// }
class MyChildViewHolder extends RecyclerView.ViewHolder {
TextView service_code, service_name;
LinearLayout mainLayout;
MyChildViewHolder(#NonNull View itemView) {
super(itemView);
service_code = itemView.findViewById(R.id.service_code);
service_name = itemView.findViewById(R.id.service_name);
mainLayout = itemView.findViewById(R.id.mainLayout);
//Animate Recyclerview
Animation translate_anim = AnimationUtils.loadAnimation(context, R.anim.translate_anim);
mainLayout.setAnimation(translate_anim);
}
}
class MyHeadingViewHolder extends RecyclerView.ViewHolder {
TextView heading;
public MyHeadingViewHolder(#NonNull View itemView) {
super(itemView);
heading = itemView.findViewById(R.id.heading_name);
}
}
}
Here is my MainActivity class:
package com.vatexpress.service;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
public final class MainActivity extends AppCompatActivity {
private static final int REQUEST_CODE_SPEECH_INPUT =1000 ;
RecyclerView recyclerView;
TextView noSearchResultsFoundText;
EditText editText;
ImageView clearQueryImageView ;
ImageView voiceSearchImageView;
MyDatabaseHelper myDB;
ArrayList<Model> dataholder;
CustomAdapter customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.search_list);
noSearchResultsFoundText = findViewById(R.id.no_search_results_found_text);
myDB = new MyDatabaseHelper(MainActivity.this);
try {
myDB.createDataBase();
} catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDB.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
storeDataInArrays();
recyclerView.setLayoutManager(new LinearLayoutManager(this));
customAdapter = new CustomAdapter(MainActivity.this,this, dataholder);
recyclerView.setAdapter(customAdapter);
recyclerView.addItemDecoration(new StickyRecyclerHeadersDecoration(customAdapter));
editText = (EditText) findViewById(R.id.search_edit_text);
editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
public void onTextChanged(CharSequence s, int start, int before, int count) {
customAdapter.getFilter().filter(s.toString());
if (editText.getText().toString().isEmpty()){
clearQueryImageView.setVisibility(View.GONE);
voiceSearchImageView.setVisibility(View.VISIBLE);
}else{
clearQueryImageView.setVisibility(View.VISIBLE);
voiceSearchImageView.setVisibility(View.GONE);
}
}
});
voiceSearchImageView = findViewById(R.id.voice_search_query);
//button clic to show speech to text dilog
voiceSearchImageView.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
speak();
}
} );
clearQueryImageView = findViewById(R.id.clear_search_query);
clearQueryImageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editText.setText("");
}
});
}
private void speak() {
//intent is show speech to text dialog
Intent intent= new Intent( RecognizerIntent.ACTION_RECOGNIZE_SPEECH );
intent.putExtra( RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra( RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault() );
intent.putExtra( RecognizerIntent.EXTRA_PROMPT, "HI speak something" );
// Start intent
try {
//in there was no errror
//show dilog
startActivityForResult( intent, REQUEST_CODE_SPEECH_INPUT);
}
catch(Exception e){
//show messageof error and show
Toast.makeText( this,""+e.getMessage(), Toast.LENGTH_SHORT ).show();
}
}
//recive voice input and handle it
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult( requestCode, resultCode, data );
switch (requestCode){
case REQUEST_CODE_SPEECH_INPUT:{
if(resultCode==RESULT_OK && null!=data){
//get text arry form voice intent
ArrayList<String> result=data.getStringArrayListExtra( RecognizerIntent.EXTRA_RESULTS );
//set to text view
editText.setText( result.get( 0 ) );
}
break;
}
}
}
public void storeDataInArrays(){
dataholder = new ArrayList<>();
String code = "";
boolean firstTime = true;
int section = 0, count = 0;
Cursor cursor = myDB.readAllData();
if(cursor.getCount() == 0){
noSearchResultsFoundText.setVisibility(View.VISIBLE);
}else{
while (cursor.moveToNext()){
if (firstTime) {
code = cursor.getString(1);
Model obj=new Model(cursor.getString(0),cursor.getString(1), cursor.getString(2), cursor.getString(3), true, section);
firstTime = false;
dataholder.add(obj);
}
else
{
if (!code.equals(cursor.getString(1))) {
section = count;
Model obj=new Model(cursor.getString(0),cursor.getString(1), cursor.getString(2), cursor.getString(3), true, section);
dataholder.add(obj);
code = cursor.getString(1);
}
else
{
Model obj=new Model(cursor.getString(0),cursor.getString(1), cursor.getString(2), cursor.getString(3), false, section);
dataholder.add(obj);
}
}
count++;
}
noSearchResultsFoundText.setVisibility(View.GONE);
}
}
}
Please gives me solution how can I solve this!
I am new to android development, and i'm trying to build a simple hymn book,
I'm using bottom navigation, i use fragments on each tab to display numbers and titles of each hymn.
In my favourite fragments i have a list of favourite songs displayed using recycler view fetch from the database.
I use on long click listener to delete songs from the favorite table in the database, but any time i delete a
song my favorite fragment doesn't get refreshed or undated with current items. Please, how can I refresh or update
my favourite fragment anytime i delete a song. thank you!
'''Favourite Adapter''
import android.app.FragmentManager;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import static android.content.Context.MODE_PRIVATE;
public class FavouriteAdapter extends RecyclerView.Adapter<FavouriteAdapter.ViewHolder> {
private Context favContext;
private ArrayList<String> favNumbers = new ArrayList<>();
private ArrayList<String> favTitles = new ArrayList<>();
public FavouriteAdapter(Context favContext, ArrayList<String> favNumbers, ArrayList<String> favTitles) {
this.favContext = favContext;
this.favNumbers = favNumbers;
this.favTitles = favTitles;
}
#Override
public FavouriteAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext())
.inflate(R.layout.favourite_list_items, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(final FavouriteAdapter.ViewHolder holder, final int position) {
holder.textViewFavNum.setText(favNumbers.get(position));
holder.textViewFavTitle.setText(favTitles.get(position));
final String hymn_no = favNumbers.get(position);
holder.itemView.setTag(favNumbers.get(position));
holder.favParentLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i;
i = new Intent(view.getContext(), Songs.class);
i.putExtra("numId", favNumbers.get(position));
i.putExtra("titleName", favTitles.get(position));
favContext.startActivity(i);
}
});
holder.favParentLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View view) {
new AlertDialog.Builder(view.getContext())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete from favorites?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
try{
SQLiteDatabase favHymns = favContext.openOrCreateDatabase("Songs", MODE_PRIVATE, null);
favHymns.execSQL("DELETE FROM favorites where hymnNum = '"+hymn_no+"'");
Toast.makeText(favContext.getApplicationContext(), "hymn deleted ", Toast.LENGTH_LONG).show();
}catch(Exception e){
e.printStackTrace();
}
}
})
.setNegativeButton("No", null)
.show();
return true;
}
});
}
#Override
public int getItemCount() {
return favNumbers.size();
}
#Override
public long getItemId(int position){
return position;
}
#Override
public int getItemViewType(int position){
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView textViewFavNum;
public TextView textViewFavTitle;
RelativeLayout favParentLayout;
public ViewHolder(View itemView) {
super(itemView);
textViewFavNum = (TextView) itemView.findViewById(R.id.textViewFavNum);
textViewFavTitle = (TextView) itemView.findViewById(R.id.textViewFavTitle);
favParentLayout = (RelativeLayout) itemView.findViewById(R.id.favParentLayout);
}
}
}
'''favourite fragment'''
import android.app.FragmentManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.logging.Handler;
import static android.content.Context.MODE_PRIVATE;
/**
* A simple {#link Fragment} subclass.
*/
public class Favourites extends Fragment {
private RecyclerView recyclerView;
private RecyclerView.Adapter adapter;
private ArrayList<String> favSongNumbers = new ArrayList<>();
private ArrayList<String> favSongTitles = new ArrayList<>();
private TextView favMessage;
public Favourites() {
// Required empty public constructor
}
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
if(view == null) {
view = inflater.inflate(R.layout.fragment_favourites, container, false);
favMessage = (TextView) view.findViewById(R.id.favMessage);
recyclerView = (RecyclerView) view.findViewById(R.id.favRecyclerView);
// adapter.setHasStableIds(true);
Toast.makeText(this.getActivity(), "Long press to delete hymns from favorites", Toast.LENGTH_LONG).show();
initFavSongs();
}
return view;
}
private void initFavSongs(){
try{
favMessage.setText("");
SQLiteDatabase favHymns = this.getActivity().openOrCreateDatabase("Songs", MODE_PRIVATE, null);
Cursor c = favHymns.rawQuery("SELECT hymnNum, hymnTitle FROM favorites", null);
int hymnNumIndex = c.getColumnIndex("hymnNum");
int hymnTitleIndex = c.getColumnIndex("hymnTitle");
if(c.moveToFirst()) {
while (c != null) {
favSongNumbers.add(Integer.toString(c.getInt(hymnNumIndex)) + ". ");
favSongTitles.add(" " + c.getString(hymnTitleIndex));
c.moveToNext();
}
}else{
favMessage.setText("Oops!No favorite songs added yet.");
}
}catch (Exception e){
e.printStackTrace();
}
initRecyclerView();
}
private void initRecyclerView(){
adapter = new FavouriteAdapter(this.getActivity(), favSongNumbers, favSongTitles);
recyclerView.setAdapter(adapter);
recyclerView.setLayoutManager(new LinearLayoutManager(this.getActivity()));
}
}
Pass a listener to the adapter and invoke it at the time of item delete from database. Then update your list and as well as your adapter.Like this way:
First create a listener:
public interface UpdateListener {
void onValueChangedListener();
}
Initialize the listener in Adapter class that comes from fragment.
private UpdateListener updateListener;
public FavouriteAdapter(Context favContext, ArrayList<String> favNumbers, ArrayList<String> favTitles,UpdateListener updateListener ) {
this.favContext = favContext;
this.favNumbers = favNumbers;
this.favTitles = favTitles;
this.updateListener=updateListener;
}
holder.favParentLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(final View view) {
new AlertDialog.Builder(view.getContext())
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Are you sure?")
.setMessage("Do you want to delete from favorites?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int which) {
try{
SQLiteDatabase favHymns = favContext.openOrCreateDatabase("Songs", MODE_PRIVATE, null);
favHymns.execSQL("DELETE FROM favorites where hymnNum = '"+hymn_no+"'");
Toast.makeText(favContext.getApplicationContext(), "hymn deleted ", Toast.LENGTH_LONG).show();
// when any item delete from database notify the fragment through this
// listener for updating your adapter
updateListener.onValueChangedListener();
}catch(Exception e){
e.printStackTrace();
}
}
})
.setNegativeButton("No", null)
.show();
return true;
}
});
// this method is needed for updating your adapter
public void update(ArrayList<String> favNumbers, ArrayList<String> favTitles){
this.favNumbers = favNumbers;
this.favTitles = favTitles;
}
Implement the listener in your fragment and reinitialize your list.
public class Favourites extends Fragment implements UpdateListener {
private void initRecyclerView(){
// pass listener
adapter = new FavouriteAdapter(this.getActivity(), favSongNumbers, favSongTitles,this);
}
private void updateFavSongs(){
favSongNumbers.clear;
favSongTitles.clear;
try{
favMessage.setText("");
SQLiteDatabase favHymns = this.getActivity().openOrCreateDatabase("Songs", MODE_PRIVATE, null);
Cursor c = favHymns.rawQuery("SELECT hymnNum, hymnTitle FROM favorites", null);
int hymnNumIndex = c.getColumnIndex("hymnNum");
int hymnTitleIndex = c.getColumnIndex("hymnTitle");
if(c.moveToFirst()) {
while (c != null) {
favSongNumbers.add(Integer.toString(c.getInt(hymnNumIndex)) + ". ");
favSongTitles.add(" " + c.getString(hymnTitleIndex));
c.moveToNext();
}
}else{
favMessage.setText("Oops!No favorite songs added yet.");
}
}catch (Exception e){
e.printStackTrace();
}
adapter.update(favSongNumbers,favSongTitles);
adapter.notifyDataSetChanged()
}
#Override
public void onValueChangedListener(){
updateFavSongs();
}
}
I am trying to delete a row or any row while by clicking on my custom listview adapter which extends Baseadapter. I have found many solutions on Google but none of them worked for me.I am successfully generating a listview with the help of this class but can't delete a row or any row.
Here is my code
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.BaseAdapter;
import com.brl.loverfreedatingapp.R;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import de.hdodenhof.circleimageview.CircleImageView;
public class WhoLikedMeAdapter extends BaseAdapter {
private Context context; //context
private ArrayList<String> masterID = new ArrayList<String>();
private ArrayList<String> slaveID = new ArrayList<String>();
private ArrayList<String> masterName = new ArrayList<String>();
private ArrayList<String> slaveName = new ArrayList<String>();
private ArrayList<String> slaveUrl = new ArrayList<String>();
public WhoLikedMeAdapter(Context context, ArrayList<String> masterID, ArrayList<String> slaveID, ArrayList<String> masterName, ArrayList<String> slaveName, ArrayList<String> slaveUrl) {
this.context = context;
this.masterID = masterID;
this.slaveID = slaveID;
this.masterName = masterName;
this.slaveName = slaveName;
this.slaveUrl = slaveUrl;
}
#Override
public int getCount() {
return masterID.size(); //returns total of items in the list
}
#Override
public Object getItem(int position) {
return masterID.get(position); //returns list item at the specified position
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// inflate the layout for each list row
if (convertView == null) {
convertView = LayoutInflater.from(context).
inflate(R.layout.wholikeme_row, parent, false);
}
CircleImageView profile_image = (CircleImageView) convertView.findViewById(R.id.profile_image);
TextView name = (TextView)convertView.findViewById(R.id.name);
ImageButton unlike = (ImageButton)convertView.findViewById(R.id.unlike);
ImageButton like = (ImageButton)convertView.findViewById(R.id.like);
name.setText(slaveName.get(position));
//--
if(slaveUrl.get(position).equals("")){
Picasso.with(context)
.load(R.drawable.image_placeholder)
//.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.placeholder(R.drawable.image_placeholder)
.into(profile_image);
}else {
Picasso.with(context)
.load(slaveUrl.get(position))
//.memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
.placeholder(R.drawable.image_placeholder)
.into(profile_image);
}
//-------------
like.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
masterID.remove(position);// not working
notifyDataSetChanged();
}
});
unlike.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
masterID.remove(position);// not working
notifyDataSetChanged();
}
});
// returns the view for the current row
return convertView;
}
}
Found the solution! I have to remove all the data in a row to remove a listview row. Previously I was trying with only 1 data (masterID).
masterID.remove(position);
slaveID.remove(position);
masterName.remove(position);
slaveName.remove(position);
slaveUrl.remove(position);
notifyDataSetChanged();
I am fairly new to Android Application Development. I've been working on an application that computes a person's college GPA. At the moment I am currently struggling to show the GPA a student gets for each Semester. I am only able to print out the results for the first semester.
DISPLAYALLSEMESTERACTIVITY.java
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import java.util.ArrayList;
import static com.example.govinpillai.ca2.R.id.listView1;
public class DISPLAYALLSEMESTERACTIVITY extends AppCompatActivity {
DataManager sqLiteHelper;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
GPAListAdapter listAdapter ;
ListView LISTVIEW;
String SEMHOLDER;
ArrayList<String> ID_Array;
ArrayList<String> GPA_Array;
ArrayList<String> SEMESTER_Array;
Intent intent;
ArrayList<String> ListViewClickItemArray = new ArrayList<String>();
String TempHolder ;
private String LOG_TAG;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_displayallsemesteractivity);
LISTVIEW = (ListView) findViewById(listView1);
intent = getIntent();
SEMHOLDER = intent.getStringExtra("SEM");
ID_Array = new ArrayList<String>();
GPA_Array = new ArrayList<String>();
SEMESTER_Array = new ArrayList<String>();
sqLiteHelper = new DataManager(this);
LISTVIEW.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
/* Intent intent = new
Intent(getApplicationContext(),DISPLAYONEGRADEACTIVITY.class);
intent.putExtra("ListViewClickedItemValue",
ListViewClickItemArray.get(position).toString());
startActivity(intent);*/
}
});
}
#Override
protected void onResume() {
ShowSQLiteDBdata() ;
super.onResume();
}
private void ShowSQLiteDBdata() {
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
cursor = sqLiteDatabase.rawQuery("SELECT id, sum(gcproduct)/sum(credit) AS Semestergpa , Semester FROM " + DataManager.TABLE_NAME +" group by Semester", null);
ID_Array.clear();
SEMESTER_Array.clear();
GPA_Array.clear();
if (cursor.moveToFirst()) {
do {
ID_Array.add(cursor.getString(cursor.getColumnIndex(DataManager.Table_Column_ID)));
//Inserting Column ID into Array to Use at ListView Click Listener Method.
/* ListViewClickItemArray.add(cursor.getString(cursor.getColumnIndex(DataManager.Table_Column_ID)));*/
GPA_Array.add(cursor.getString(cursor.getColumnIndex("Semestergpa")));
SEMESTER_Array.add(cursor.getString(cursor.getColumnIndex(DataManager.Table_Column_5_SEMESTER)));
while(!cursor.isAfterLast()) {
Log.e(LOG_TAG, DatabaseUtils.dumpCurrentRowToString(cursor));
cursor.moveToNext();
}
} while (cursor.moveToNext());
}
listAdapter = new GPAListAdapter(DISPLAYALLSEMESTERACTIVITY.this,
ID_Array,
GPA_Array,
SEMESTER_Array
);
LISTVIEW.setAdapter(listAdapter);
cursor.close();
}
}
GPAListAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class GPAListAdapter extends BaseAdapter {
Context context;
ArrayList<String> ID;
ArrayList<String> GPA;
ArrayList<String> SEMESTER;
public GPAListAdapter(
Context context2,
ArrayList<String> id,
ArrayList<String> gPA,
ArrayList<String> sEMESTER
)
{
this.context = context2;
this.ID = id;
this.SEMESTER = sEMESTER;
this.GPA = gPA;
}
public int getCount() {
// TODO Auto-generated method stub
return ID.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
public View getView(int position, View child, ViewGroup parent) {
Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.gpaitems, null);
holder = new Holder();
holder.IDTextView = (TextView) child.findViewById(R.id.textViewID);
holder.GPATextView = (TextView) child.findViewById(R.id.textViewGPA);
holder.SEMESTERTextView = (TextView) child.findViewById(R.id.textViewSEMESTER);
child.setTag(holder);
} else {
holder = (Holder) child.getTag();
}
holder.IDTextView.setText(ID.get(position));
holder.GPATextView.setText(GPA.get(position));
holder.SEMESTERTextView.setText(SEMESTER.get(position));
return child;
}
public class Holder {
TextView IDTextView;
TextView GPATextView;
TextView SEMESTERTextView;
}
}
My logcat output
[ 02-03 23:15:46.304 6376: 6376 E/ ]
0 {
id=2
Semestergpa=3.75
SEMESTER=1
}
[ 02-03 23:15:46.304 6376: 6376 E/ ]
1 {
id=4
Semestergpa=3
SEMESTER=2
}
Desired Output in Android Virtual Device
id=2
Semester=1
Semester GPA=3.75
id=4
Semester=2
Semester GPA=3
Actual Output in Android Virtual Device
id=2
Semester=1
Semester GPA=3.75
Could someone show me what have I done wrong and what I can do to fix it ?
In DISPLAYALLSEMESTERACTIVITY.java, my guess is you did cursor.moveToNext() twice, so it advances by 2 & skips one record each time.
For the cursor related code in ShowSQLiteDBdata(), can you try replacing it with the below code?
if (cursor.moveToFirst()) {
while (cursor.isAfterLast() == false) {
// do everything here first
ID_Array.add(....)
.....
.....
// only move to next cursor position at end of while loop
cursor.moveToNext();
}
}
Hope this help, good luck!
I am trying to get database from SQLite database and trying to populate the ListView and also adding data in ArrayList<String> . The ListView is populated nicely but problem is ArrayList<String> is not populated nicely.
Suppose I have data in database like:
A
B
C
D
E
F
G
H
I
J
K
L
M
N
........
My ListView Showing data in this way. But ArrayList<String> add the data this way:
A
B
C
D
E
F
A
B
C
D
E
F
G
H
......
That means my ArrayList<String> takes first 6 value then repeat it and then it takes next 6 value then again repeat it ..... . That means When I click item "H" from list view the ArrayList<String> shows me "B". I don't know why it is happening?
My Code, CustomList which extends CursorAdapter
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.TextView;
public class CustomList extends CursorAdapter {
CheckBox favoriteBox;
TextView cityName, countryName;
ArrayList<String> city_name;
ArrayList<String> country_name;
ArrayList<String> country_short;
ArrayList<CheckBox> check_box;
public CustomList(Context context, Cursor c, ArrayList<String> city_name,
ArrayList<String> country_name, ArrayList<String> country_short,
ArrayList<CheckBox> check_box) {
super(context, c, 0);
this.city_name = city_name;
this.country_name = country_name;
this.country_short = country_short;
this.check_box = check_box;
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.all_city_list, parent, false);
return retView;
}
#Override
public void bindView(final View view, Context context, Cursor cursor) {
cityName = (TextView) view.findViewById(R.id.cityName);
String cityS = cursor.getString(cursor.getColumnIndex("city_name"));
cityName.setText(cityS);
city_name.add(cityS);//adding value to ArrayList<String>
countryName = (TextView) view.findViewById(R.id.countryName);
String conS = cursor.getString(cursor.getColumnIndex("country_name"));
countryName.setText(conS);
country_name.add(conS);//adding value to ArrayList<String>
country_short.add(""
+ cursor.getString(cursor.getColumnIndex("country_short")));//adding value to ArrayList<String>
favoriteBox = (CheckBox) view.findViewById(R.id.favoriteCheckBox);
check_box.add(favoriteBox);
if (cursor.getInt(cursor.getColumnIndex("favorite")) == 0) {
favoriteBox.setChecked(false);
} else {
favoriteBox.setChecked(true);
}
}
}
Class AllCityListFragment which extends Fragment
import java.io.IOException;
import java.util.ArrayList;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;
public class AllCityListFragment extends Fragment {
private CustomList customAdapter;
private DatabaseHelper databaseHelper;
ArrayList<String> city_name = new ArrayList<String>();
ArrayList<String> country_name = new ArrayList<String>();
ArrayList<String> country_short = new ArrayList<String>();
ArrayList<CheckBox> check_box = new ArrayList<CheckBox>();
public static final String ARG_OS = "OS";
int pos;
String sql = "";
ListView list;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = inflater.inflate(R.layout.all_city_layout, null);
databaseHelper = new DatabaseHelper(view.getContext());
try {
databaseHelper.createDataBase();
databaseHelper.openDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(view.getContext(), "Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
list = (ListView) view.findViewById(R.id.citylist);
list.setFocusable(false);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View myview,
int position, long id) {
Toast.makeText(getActivity(),
position + " " + city_name.get(position),
Toast.LENGTH_LONG).show();
}
});
sql = "SELECT _id, city_name, country_name, country_short, favorite FROM city order by country_name asc;";
new Handler().post(new Runnable() {
#Override
public void run() {
customAdapter = new CustomList(getActivity(), databaseHelper
.getResult(sql), city_name, country_name,
country_short, check_box);
list.setAdapter(customAdapter);
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
In this picture I clicked "Shirajganj" but the Toast shows me "230 Thakurgaon" position =230 is correct but city_name.get(230) should be "Shirajganj" . I think it is doing wrong when I am trying to add value to ArrayList<String> in binView in CustomList. How can I solve this problem?
It's not a good idea to fill that array in bindView method. The Android doesn't create separate view for each row in the list, it's utilize already created ones, that's why you will always receive unexpected results in your arraylist. The better is to fill the array in your activity, instead of the adapter. Just query your database for the same result like this:
Cursor cursor = getContentResolver().query(
uri,
projection,
selectionClause
selectionArgs,
sortOrder);
while (cursor.moveToNext ()){
arrayList.add(cursor.getAsString(cursor.getColumnIndex('column_name')));
}
cursor.close()