I would like to update a single listview item and it works fine until I scroll down to items that are not visible and seems that there is an item (which was not visible) getting updated as well (I see this when I scroll down)
The image above describes the issue, when i update listview item in position 0, the item in position 5 (not visible until i scroll) also updates (it should not) and if i do the same for pos 1 then pos 6 is also updated and so on and so on even vice-versa, eg: when i update pos 7 and scroll up pos 2 will be updated as well, how can I prevent this and only have the listview update the item that i click on (and not update the listview item which is not visible until scroll)?
public class TestActivity extends ListActivity {
private SQLiteDatabase db;
private Cursor cursor;
private int correctAnswers;
private int incorrectAnswers;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
correctAnswers = 0;
incorrectAnswers = 0;
try{
DingDongDatabaseHelper coffeinaDatabaseHelper = new DingDongDatabaseHelper(this);
db = coffeinaDatabaseHelper.getReadableDatabase();
cursor = db.query("BPIE", new String[]{"_id", "QUESTION", "ANSWER1", "ANSWER2", "ANSWER3", "ANSWER4", "CORRECT"},null, null, null, null,null);
Random rand = new Random();
CursorAdapter listAdapter = new SimpleCursorAdapter(this, R.layout.test_adapter, cursor, new String[]{ "QUESTION", "ANSWER1", "ANSWER2", "ANSWER3", "ANSWER4"}, new int[]{R.id.text_test_question, R.id.radio_answer1, R.id.radio_answer2, R.id.radio_answer3, R.id.radio_answer4}, 0);
}
setListAdapter(listAdapter);
}catch(SQLException e){
Toast toast = Toast.makeText(this, "Błąd",Toast.LENGTH_SHORT);
toast.show();
}
}
protected void onListItemClick(ListView l, View item, int position, long id) {
RadioButton radio1 = (RadioButton)item.findViewById(R.id.radio_answer1);
RadioButton radio2 = (RadioButton)item.findViewById(R.id.radio_answer2);
RadioButton radio3 = (RadioButton)item.findViewById(R.id.radio_answer3);
RadioButton radio4 = (RadioButton)item.findViewById(R.id.radio_answer4);
radio1.setBackgroundColor(Color.WHITE);
radio2.setBackgroundColor(Color.WHITE);
radio3.setBackgroundColor(Color.WHITE);
radio4.setBackgroundColor(Color.WHITE);
String correctAnswer="";
String selectedAnswer="";
if(item != null){
RadioGroup radioGroup = (RadioGroup)item.findViewById(R.id.radio_group);
RadioButton selectedButton = (RadioButton)item.findViewById(radioGroup.getCheckedRadioButtonId());
if(selectedButton!=null){
if(cursor.moveToPosition(position)) {
correctAnswer = cursor.getString(6);
}
selectedAnswer = String.valueOf(selectedButton.getText());
if(correctAnswer.equals(selectedAnswer)){
selectedButton.setBackgroundColor(Color.GREEN);
correctAnswers++;
}
else
{
incorrectAnswers++;
selectedButton.setBackgroundColor(Color.RED);
if(correctAnswer.equals(radio1.getText()))radio1.setBackgroundColor(Color.GREEN);
else if(correctAnswer.equals(radio2.getText()))radio2.setBackgroundColor(Color.GREEN);
else if(correctAnswer.equals(radio3.getText()))radio3.setBackgroundColor(Color.GREEN);
else if(correctAnswer.equals(radio4.getText()))radio4.setBackgroundColor(Color.GREEN);
}
Toast toast = Toast.makeText(TestActivity.this, "CORRECT: " + correctAnswer + "\nSELECTED: " + selectedAnswer, Toast.LENGTH_LONG);
toast.show();
}
}
}
}
Try this:
AnsweredQuestion.java:
public class AnsweredQuestion {
int selectedAnswerViewId;
int correctAnswerViewId;
public AnsweredQuestion(int selectedAnswerViewId, int correctAnswerViewId) {
this.selectedAnswerViewId = selectedAnswerViewId;
this.correctAnswerViewId = correctAnswerViewId;
}
}
TestActivity.java:
public class TestActivity extends ListActivity {
private SQLiteDatabase db;
private Cursor cursor;
private int correctAnswers;
private int incorrectAnswers;
private ArrayList<Integer> answeredQuestions = new ArrayList<>();
private HashMap<Integer, AnsweredQuestion> answeredQuestionHashMap = new HashMap<>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
correctAnswers = 0;
incorrectAnswers = 0;
try{
DingDongDatabaseHelper coffeinaDatabaseHelper = new DingDongDatabaseHelper(this);
db = coffeinaDatabaseHelper.getReadableDatabase();
cursor = db.query("BPIE", new String[]{"_id", "QUESTION", "ANSWER1", "ANSWER2", "ANSWER3", "ANSWER4", "CORRECT"},null, null, null, null,null);
Random rand = new Random();
CursorAdapter listAdapter = new SimpleCursorAdapter(this, R.layout.test_adapter, cursor, new String[]{ "QUESTION", "ANSWER1", "ANSWER2", "ANSWER3", "ANSWER4"}, new int[]{R.id.text_test_question, R.id.radio_answer1, R.id.radio_answer2, R.id.radio_answer3, R.id.radio_answer4}, 0){
#Override
public void bindView(View view, Context context, Cursor cursor) {
super.bindView(view, context, cursor);
int position = cursor.getPosition();
RadioButton radio1 = (RadioButton)view.findViewById(R.id.radio_answer1);
RadioButton radio2 = (RadioButton)view.findViewById(R.id.radio_answer2);
RadioButton radio3 = (RadioButton)view.findViewById(R.id.radio_answer3);
RadioButton radio4 = (RadioButton)view.findViewById(R.id.radio_answer4);
radio1.setBackgroundColor(Color.WHITE);
radio2.setBackgroundColor(Color.WHITE);
radio3.setBackgroundColor(Color.WHITE);
radio4.setBackgroundColor(Color.WHITE);
if(answeredQuestions.contains(position)){
AnsweredQuestion answeredQuestion = answeredQuestionHashMap.get(position);
RadioButton selectedAnswer = view.findViewById(answeredQuestion.selectedAnswerViewId);
RadioButton correctAnswer = view.findViewById(answeredQuestion.correctAnswerViewId);
selectedAnswer.setBackgroundColor(Color.RED);
correctAnswer.setBackgroundColor(Color.GREEN);
}
}
};
setListAdapter(listAdapter);
}catch(SQLException e){
Toast toast = Toast.makeText(this, "Błąd",Toast.LENGTH_SHORT);
toast.show();
}
}
protected void onListItemClick(ListView l, View item, int position, long id) {
RadioButton radio1 = (RadioButton)item.findViewById(R.id.radio_answer1);
RadioButton radio2 = (RadioButton)item.findViewById(R.id.radio_answer2);
RadioButton radio3 = (RadioButton)item.findViewById(R.id.radio_answer3);
RadioButton radio4 = (RadioButton)item.findViewById(R.id.radio_answer4);
radio1.setBackgroundColor(Color.WHITE);
radio2.setBackgroundColor(Color.WHITE);
radio3.setBackgroundColor(Color.WHITE);
radio4.setBackgroundColor(Color.WHITE);
String correctAnswer="";
String selectedAnswer="";
if(item != null){
RadioGroup radioGroup = (RadioGroup)item.findViewById(R.id.radio_group);
RadioButton selectedButton = (RadioButton)item.findViewById(radioGroup.getCheckedRadioButtonId());
RadioButton correctButton = null;
if(selectedButton!=null){
if(cursor.moveToPosition(position)) {
correctAnswer = cursor.getString(6);
}
selectedAnswer = String.valueOf(selectedButton.getText());
if(correctAnswer.equals(selectedAnswer)){
selectedButton.setBackgroundColor(Color.GREEN);
correctAnswers++;
correctButton = selectedButton;
}
else
{
incorrectAnswers++;
selectedButton.setBackgroundColor(Color.RED);
if(correctAnswer.equals(radio1.getText())) correctButton = radio1;
else if(correctAnswer.equals(radio2.getText())) correctButton = radio2;
else if(correctAnswer.equals(radio3.getText())) correctButton = radio3;
else if(correctAnswer.equals(radio4.getText())) correctButton = radio4;
correctButton.setBackgroundColor(Color.GREEN);
}
Toast toast = Toast.makeText(TestActivity.this, "CORRECT: " + correctAnswer + "\nSELECTED: " + selectedAnswer, Toast.LENGTH_LONG);
toast.show();
if(!answeredQuestions.contains(position)) answeredQuestions.add(position);
AnsweredQuestion answeredQuestion = new AnsweredQuestion(selectedButton.getId(), correctButton.getId());
answeredQuestionHashMap.put(position, answeredQuestion);
}
}
}
}
Hope that helps!
Related
I was working on an app where the user will input text through an editText, and it will be stored into listView and DataBase.
But when I ran the code, the Item refused to delete.
InputContract.java
public class InputContract {
public static final String DB_NAME = "com.dobleu.peek.db";
public static final int DB_VERSION = 1;
public class TaskEntry implements BaseColumns {
public static final String TABLE = "tasks";
public static final String COL_TASK_TITLE = "title";
}
}
InputDbHelper.java
public class InputDbHelper extends SQLiteOpenHelper {
public InputDbHelper(Context context) {
super(context, InputContract.DB_NAME, null, InputContract.DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + InputContract.TaskEntry.TABLE + " ( " +
InputContract.TaskEntry._ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
InputContract.TaskEntry.COL_TASK_TITLE + " TEXT NOT NULL);";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + InputContract.TaskEntry.TABLE);
onCreate(db);
}
}
MainActivity.java
public class MainActivity extends AppCompatActivity {
ListView list;
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
ConstraintLayout l1;
ConstraintLayout l2;
TextView displayText;
TextView amt;
TextView itms;
private static int TIME = 1000;
private InputDbHelper mHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams. FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
init();
mHelper = new InputDbHelper(this);
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
setupListViewListener();
}
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{"Name of entry you want deleted"});
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
public void init(){
ActionBar ab = getSupportActionBar();
assert ab != null;
ab.hide();
list = (ListView)findViewById(R.id.list);
displayText = (TextView)findViewById(R.id.displayText);
amt = (TextView)findViewById(R.id.amt);
itms = (TextView)findViewById(R.id.itms);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
list.setAdapter(itemsAdapter);
l1 = (ConstraintLayout)findViewById(R.id.one);
l2 = (ConstraintLayout)findViewById(R.id.two);
Typeface regular = Typeface.createFromAsset(getAssets(), "fonts/regular.ttf");
Typeface bold = Typeface.createFromAsset(getAssets(), "fonts/bold.ttf");
amt.setTypeface(bold);
itms.setTypeface(regular);
displayText.setTypeface(regular);
}
public void add(View v){
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
LayoutInflater inflater = this.getLayoutInflater();
final View dialogView = inflater.inflate(R.layout.dialog, null);
dialogBuilder.setView(dialogView);
final EditText edt = (EditText) dialogView.findViewById(R.id.edit1);
dialogBuilder.setTitle("Add Item");
dialogBuilder.setMessage("Enter text below");
dialogBuilder.setPositiveButton("Done", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String txt = edt.getText().toString();
items.add(txt);
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(InputContract.TaskEntry.COL_TASK_TITLE, txt);
db.insertWithOnConflict(InputContract.TaskEntry.TABLE, null, values, SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
int no = list.getAdapter().getCount();
amt.setText("" + no);
}
});
dialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//pass
}
});
AlertDialog b = dialogBuilder.create();
b.show();
}
public void play(View v){
Animation fadeOut = AnimationUtils.loadAnimation(this, abc_fade_out);
Animation fadeIn = AnimationUtils.loadAnimation(this, abc_fade_in);
l1.startAnimation(fadeOut);
l1.setVisibility(View.GONE);
l2.setVisibility(View.VISIBLE);
l2.startAnimation(fadeIn);
String[] array = new String[items.size()];
final String[] mStringArray = items.toArray(array);
final android.os.Handler handler = new android.os.Handler();
handler.post(new Runnable() {
int i = 0;
#Override
public void run() {
displayText.setText(mStringArray[i]);
i++;
if (i == mStringArray.length) {
handler.removeCallbacks(this);
} else {
handler.postDelayed(this, TIME);
}
}
});
}
public void one(View v){TIME = 1000;}
public void three(View v){TIME = 3000;}
public void five(View v){TIME = 5000;}
public void seven(View v){TIME = 7000;}
public void ten(View v){TIME = 10000;}
private void updateUI() {
ArrayList<String> taskList = new ArrayList<>();
SQLiteDatabase db = mHelper.getReadableDatabase();
Cursor cursor = db.query(InputContract.TaskEntry.TABLE,
new String[]{InputContract.TaskEntry._ID, InputContract.TaskEntry.COL_TASK_TITLE},
null, null, null, null, null);
while (cursor.moveToNext()) {
int idx = cursor.getColumnIndex(InputContract.TaskEntry.COL_TASK_TITLE);
taskList.add(cursor.getString(idx));
}
if (itemsAdapter== null) {
itemsAdapter= new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
taskList);
list.setAdapter(itemsAdapter);
} else {
itemsAdapter.clear();
itemsAdapter.addAll(taskList);
itemsAdapter.notifyDataSetChanged();
}
cursor.close();
db.close();
}
}
In MainActivity.java, specifically in setupListViewListener(), when the listView is held, it is supposed to delete the item that is being held. But the list only vibrates and remains the same. How can I fix this?
I suspect that your issue is that you have hard coded the TASK_TITLE to be deleted as "Name of entry you want deleted" as opposed to getting the TASK_TITLE from the item that was long clicked.
So try using :-
private void setupListViewListener() {
list.setOnItemLongClickListener(
new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter,
View item, int pos, long id) {
String title_of_row_to_delete = list.getItemAtPosition(i).toString(); //<<<<<<<<
// Remove the item within array at position
items.remove(pos);
// Refresh the adapter
SQLiteDatabase db = mHelper.getWritableDatabase();
db.delete(InputContract.TaskEntry.TABLE,
InputContract.TaskEntry.COL_TASK_TITLE + " = ?",
new String[]{title_of_row_to_delete}); //<<<<<<<<
db.close();
updateUI();
itemsAdapter.notifyDataSetChanged();
// Return true consumes the long click event (marks it handled)
return true;
}
});
}
This will extract the TASK_TITLE from the list and then use that as the argument to find the row to be deleted.
//<<<<<<<< indicates changed lines.
I am working on a simple Grading app project with 3 activities, the first one is storing some data in a database and i am replicating that data in both the first activity and the third activity.
The second activity is doing an average calculation and showing the results on that same page, but i want that result to also be shown on the third page. I tried using intents but when i click the button to go to the third page it forces close. What am i doing wrong.
I am trying to show this results in a textview
This is the Second Activity code:
public class AverageActivity extends AppCompatActivity {
EditText editmanner, editinstances, editshortstance, editstrikes, editboxingskills, editknocks, editkicks, editResults;
Button btnResults, btnnewresults;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.average_page);
editmanner = (EditText) findViewById(R.id.editText8);
editinstances = (EditText) findViewById(R.id.editText9);
editshortstance = (EditText) findViewById(R.id.editText10);
editstrikes = (EditText) findViewById(R.id.editText11);
editboxingskills = (EditText) findViewById(R.id.editText12);
editknocks = (EditText) findViewById(R.id.editText13);
editkicks = (EditText) findViewById(R.id.editText14);
editResults = (EditText) findViewById(R.id.editText15);
btnResults = (Button) findViewById(R.id.button10);
btnnewresults = (Button) findViewById(R.id.botonresultnuevo);
btnResults.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int first;
if (editmanner.getText().toString().equals("")) {
first = 0;
} else {
first = Integer.valueOf(editmanner.getText().toString());
}
int second;
if (editinstances.getText().toString().equals("")) {
second = 0;
} else {
second = Integer.valueOf(editinstances.getText().toString());
}
int third;
if (editshortstance.getText().toString().equals("")) {
third = 0;
} else {
third = Integer.valueOf(editshortstance.getText().toString());
}
int fourth;
if (editstrikes.getText().toString().equals("")) {
fourth = 0;
} else {
fourth = Integer.valueOf(editstrikes.getText().toString());
}
int fifth;
if (editboxingskills.getText().toString().equals("")) {
fifth = 0;
} else {
fifth = Integer.valueOf(editboxingskills.getText().toString());
}
int sixth;
if (editknocks.getText().toString().equals("")) {
sixth = 0;
} else {
sixth = Integer.valueOf(editknocks.getText().toString());
}
int seventh;
if (editkicks.getText().toString().equals("")) {
seventh = 0;
} else {
seventh = Integer.valueOf(editkicks.getText().toString());
}
int results;
first = Integer.parseInt(editmanner.getText().toString());
second = Integer.parseInt(editinstances.getText().toString());
third = Integer.parseInt(editshortstance.getText().toString());
fourth = Integer.parseInt(editstrikes.getText().toString());
fifth = Integer.parseInt(editboxingskills.getText().toString());
sixth = Integer.parseInt(editknocks.getText().toString());
seventh = Integer.parseInt(editkicks.getText().toString());
results = (first + second + third + fourth + fifth + sixth + seventh) / 7;
editResults.setText(String.valueOf(results));
}
});
}
public void knowtheresults(View view) {
switch (view.getId()) {
case R.id.botonresultnuevo:
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
Bundle miBundle = new Bundle();
miBundle.putString("nombre", editResults.getText().toString());
miintent.putExtras(miBundle);
startActivity(miintent);
break;
}
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Summary")) {
Intent intent = new Intent(this, ResultActivity.class);
startActivity(intent);
}
}
}
And This is the Third activity code:
public class ResultActivity extends Activity {
TextView texto;
DatabaseHelper mDatabaseHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.result_page);
texto = (TextView) findViewById(R.id.editText15);
Bundle mibundle=this.getIntent().getExtras();
if(mibundle!=null){
String dato = mibundle.getString("nombre");
texto.setText(dato);
}
mDatabaseHelper = new DatabaseHelper(this);
displayDatabaseInfo();
}
private void displayDatabaseInfo() {
// To access our database, we instantiate our subclass of SQLiteOpenHelper
// and pass the context, which is the current activity.
DatabaseHelper mDbHelper = new DatabaseHelper(this);
// Create and/or open a database to read from it
SQLiteDatabase db = mDbHelper.getReadableDatabase();
// Perform this raw SQL query "SELECT * FROM pets"
// to get a Cursor that contains all rows from the pets table.
Cursor cursor = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
TextView displayView = findViewById(R.id.textViewR1);
try {
displayView.setText("The Student...\n\n");
displayView.append(COL1 + "--" +
COL2 + "--" +
COL4 +
"\n");
// Figure out the index
int idColumnIndex = cursor.getColumnIndex(COL1);
int nameColumnIndex = cursor.getColumnIndex(COL2);
int rankColumnIndex = cursor.getColumnIndex(COL4);
while (cursor.moveToNext()) {
int currentID = cursor.getInt(idColumnIndex);
String currentName = cursor.getString(nameColumnIndex);
String currenRank = cursor.getString(rankColumnIndex);
displayView.append(currentID + "--" +
currentName + "--" +
currenRank + "\n");
}
} finally {
// Always close the cursor when you're done reading from it. This releases all its
// resources and makes it invalid.
cursor.close();
}
}
public void knowtheresults(View view) {
String button_text;
button_text = ((Button) view).getText().toString();
if (button_text.equals("Start Page")) {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
} else if (button_text.equals("Back...")) {
Intent intent = new Intent(this, AverageActivity.class);
startActivity(intent);
}
}
}
Remove Bundle from your code and use following code
Intent miintent = new Intent(AverageActivity.this, ResultActivity.class);
miintent.putString("nombre", editResults.getText().toString());
startActivity(miintent);
In you third Activity
String number = getIntent().getStringExtra("nombre");
I have an RecycleView. i take an ArrayList for Fetch all my Category that i inserted in mySqliteDatabase. and finally i set this ArrayList into RecycleView using its Adapter.
Problem:
(1) First Open CategoryActivity. (no categories)
(2) Add First Category, Second, Third no one is Refreshing.
(3) but after Adding First if i go back. and come again in that Activity. and if now i am insert Second categories then all [next items] are getting refresh.
My Problem is whenever i insert 1st Category. it insert successfully but it is not shown in my RecycleView or an ArrayList [means Recycleview not refreshing].
but my Main Problem is my RecycleView is not Refreshing only FirstCategory on My ArrayList.. After adding First item my next all Arraylist item is getting Refreshed.
Below is my All Code.
CategoryAdapter
public class CategoryAdapter extends RecyclerView.Adapter<CategoryAdapter.MyViewHolder> implements Filterable {
private ArrayList<CategoryModel> dataList;
class MyViewHolder extends RecyclerView.ViewHolder {
TextView tvCategoryItem;
MyViewHolder(View view) {
super(view);
tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
}
}
CategoryAdapter(ArrayList<CategoryModel> dataSet) {
this.dataList = dataSet;
this.filterList = dataSet;
}
// I used this method too. but same problem.
void refreshAdapter(ArrayList<CategoryModel> dataSet) {
dataList.clear();
dataList.addAll(dataSet);
notifyDataSetChanged();
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(parent.getContext())
.inflate(R.layout.rv_row_category_list, parent, false);
return new MyViewHolder(itemView);
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position) {
CategoryModel categoryModel = dataList.get(position);
holder.tvCategoryItem.setText(categoryModel.getCategoryName());
}
#Override
public int getItemCount() {
return dataList.size();
}
}
CategoryListActivity
MyDatabase myDb;
CategoryModel categoryModel;
RecyclerView recyclerCategory;
RecyclerView.LayoutManager layoutManager;
CategoryAdapter adapter;
ArrayList<CategoryModel> allCategory;
int CategoryType;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_category);
myDb = new MyDatabase(this);
recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);
CategoryType = CaseActivity.CategoryType;
Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);
allCategory = myDb.getCategoryByType(CategoryType);
if (allCategory.size() == 0) {
Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
}
adapter = new CategoryAdapter(allCategory);
recyclerCategory.setAdapter(adapter);
layoutManager = new LinearLayoutManager(this);
recyclerCategory.setLayoutManager(layoutManager);
recyclerCategory.setItemAnimator(new DefaultItemAnimator());
recyclerCategory.setHasFixedSize(true);
recyclerCategory.addOnItemTouchListener(new RecyclerItemClickListener(this, recyclerCategory,
new RecyclerItemClickListener.OnItemTouchListener() {
#Override
public void onItemClick(View view, int position) {
TextView tvCategoryItem = (TextView) view.findViewById(R.id.tvCategoryName);
String CategoryName = tvCategoryItem.getText().toString();
Intent intent = new Intent();
CategoryId = allCategory.get(+position).getCategoryId();
intent.putExtra("CategoryId", String.valueOf(CategoryId));
Log.e("Clicked Cat Id is ", "" + CategoryId);
intent.putExtra("CategoryName", CategoryName);
setResult(Activity.RESULT_OK, intent);
finish();
}
#Override
public void onLongItemClick(View view, int position) {
}
}
));
}
private void openAlert() {
final EditText etCategoryName = new EditText(this);
CustomAlertDialog dialog1 = new CustomAlertDialog(this);
dialog1.setTitle("Add Category");
dialog1.setView(etCategoryName);
dialog1.setCancelable(true);
dialog1.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
final String CategoryName = etCategoryName.getText().toString().trim();
final String storedCategoryName = myDb.ExistCategory(CategoryName);
if (CategoryName.equals("") && CategoryName.length() == 0) {
Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Enter Category Name");
builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
} else {
if (CategoryName.equals(storedCategoryName)) {
Builder builder1 = GlobalConstant.createAlert(CategoryListActivity.this, "Warning", "Category Already Exists");
builder1.setPositiveButton("Back", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
} else {
dialogInterface.dismiss();
categoryModel = new CategoryModel(CategoryName, String.valueOf(CategoryType));
myDb.createCategory(categoryModel);
Toast.makeText(CategoryListActivity.this, "CategoryName " + CategoryName
+ "\nCategoryType " + CategoryType, Toast.LENGTH_SHORT).show();
allCategory.clear();
allCategory = myDb.getCategoryByType(CategoryType);
adapter.notifyDataSetChanged();
}
}
}
});
dialog1.show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add:
openAlert();
default:
return super.onOptionsItemSelected(item);
}
}
}
my createCategory() method.
public long createCategory(CategoryModel categoryModel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CATEGORY_NAME, categoryModel.getCategoryName());
values.put(CATEGORY_TYPE, categoryModel.getCategoryType());
long CategoryId = db.insert(TABLE_CATEGORY, null, values);
db.close();
return CategoryId;
}
and Finally my getCategoryByType() method on My Database.
public ArrayList<CategoryModel> getCategoryByType(int CategoryType) {
ArrayList<CategoryModel> Categories = new ArrayList<>();
// String selectQuery = "SELECT " + CATEGORY_NAME + " FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType;
String selectQuery = "SELECT * FROM " + TABLE_CATEGORY + " WHERE " + CATEGORY_TYPE + " = " + CategoryType + " ORDER BY CategoryId DESC";
Log.e(DB_LOG, selectQuery);
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
CategoryModel categoryModel = new CategoryModel();
categoryModel.setCategoryId(cursor.getInt(cursor.getColumnIndex(CATEGORY_ID)));
categoryModel.setCategoryName(cursor.getString(cursor.getColumnIndex(CATEGORY_NAME)));
categoryModel.setCategoryType(cursor.getString(cursor.getColumnIndex(CATEGORY_TYPE)));
Categories.add(categoryModel);
} while (cursor.moveToNext());
}
cursor.close();
}
return Categories;
}
Any Type of Help, Suggestion is much Appreciated.....Thanks in advance
Below is Screenshot after adding First Item.
First Item Inserted but not shown in RecycleView
My LogCat Screenshot is below.
Logcat Screenshot
change your onCreate in this way
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_category);
myDb = new MyDatabase(this);
recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);
CategoryType = CaseActivity.CategoryType;
Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);
allCategory = myDb.getCategoryByType(CategoryType);
if (allCategory.size() == 0) {
Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
}
adapter = new CategoryAdapter(allCategory);
recyclerCategory.setAdapter(adapter);
layoutManager = new LinearLayoutManager(this);
recyclerCategory.setLayoutManager(layoutManager);
recyclerCategory.setItemAnimator(new DefaultItemAnimator());
recyclerCategory.setHasFixedSize(true);
}
and now you can use adapter.notifyDataSetChanged(); without recreation of adapter and set them to RecyclerView
if you make in setPositiveButton allCategory = myDb.getCategoryByType(CategoryType); then your reference to allCategory is lost.
you need instead
allCategory.clear();
allCategory.addAll(myDb.getCategoryByType(CategoryType));
Change your Activity onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_category);
myDb = new MyDatabase(this);
recyclerCategory = (RecyclerView) findViewById(R.id.recyclerCategory);
CategoryType = CaseActivity.CategoryType;
Log.d(GlobalConstant.KEY_CATEGORY_TYPE, "" + CategoryType);
allCategory = new ArrayList<>();
adapter = new CategoryAdapter(allCategory);
layoutManager = new LinearLayoutManager(this);
recyclerCategory.setLayoutManager(layoutManager);
recyclerCategory.setItemAnimator(new DefaultItemAnimator());
recyclerCategory.setHasFixedSize(true);
recyclerCategory.setAdapter(adapter);
allCategory = myDb.getCategoryByType(CategoryType);
adapter.notifyDataSetChange();
if (allCategory.size() == 0) {
Toast.makeText(this, "No Category", Toast.LENGTH_SHORT).show();
}
}
and inside setPositiveButton, replace
adapter = new CategoryAdapter(allCategory);
recyclerCategory.setAdapter(adapter);
adapter.notifyDataSetChanged();
with
adapter.notifyDataSetChanged();
Also replace
allCategory = myDb.getCategoryByType(CategoryType);
with
allCategory.addAll(myDb.getCategoryByType(CategoryType));
And try to run your program again.
I have a table layout where rows are dynamically added. I want 30 data to be shown in one page.pages should be automatically added with increasing data. This is my code.
int increment = 0;
public int TOTAL_LIST_ITEMS;
public int NUM_ITEMS_PAGE = 50;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.frag_tab1, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
tableLayout = (TableLayout) view.findViewById(R.id.tableLay);
buttonNext = (Button) view.findViewById(R.id.next);
listView = (ListView) view.findViewById(R.id.list);
title = (TextView) view.findViewById(R.id.text);
buttonPrev = (Button) view.findViewById(R.id.prev);
buttonPrev.setEnabled(false);
// data = new ArrayList<String>();
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment++;
loadList(increment);
Toast.makeText(getActivity(),"the page is"+increment,Toast.LENGTH_LONG).show();
checkEnable();
}
});
buttonPrev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
increment--;
loadList(increment);
Toast.makeText(getActivity(),"the page is"+increment,Toast.LENGTH_LONG).show();
checkEnable();
}
});
db = getActivity().openOrCreateDatabase("hitechData.db", Context.MODE_PRIVATE, null);
DBHelper dh = new DBHelper(getActivity(), "hitechData.db", null, 1);
tableLayout.setColumnStretchable(0, true);
tableLayout.setColumnStretchable(2, true);
tableLayout.setStretchAllColumns(true);
tableLayout.bringToFront();
db = getActivity().openOrCreateDatabase("hitechData.db", SQLiteDatabase.CREATE_IF_NECESSARY, null);
db.setVersion(1);
db.setLocale(Locale.getDefault());
dh.onCreate(db);
db.setLockingEnabled(true);
String query = "SELECT * FROM leadData3 Order by id DESC";
Cursor cur;
cur = db.rawQuery(query, null);
TOTAL_LIST_ITEMS = cur.getCount();
data=TOTAL_LIST_ITEMS;
int val = TOTAL_LIST_ITEMS % NUM_ITEMS_PAGE;
val = val == 0?0:1;
pageCount = TOTAL_LIST_ITEMS / NUM_ITEMS_PAGE;
if (cur != null && cur.getCount() > 0) {
if (cur.moveToFirst()) {
try {
while (cur.isAfterLast() == false ){
TableRow tr = new TableRow(getActivity().getBaseContext());
final TextView compName = new TextView(getActivity().getBaseContext());
compName.setBackgroundResource(R.drawable.borderr);
final TextView firstName = new TextView(getActivity().getBaseContext());
firstName.setBackgroundResource(R.drawable.borderr);
final TextView midName = new TextView(getActivity().getBaseContext());
midName.setBackgroundResource(R.drawable.borderr);
final TextView lastName = new TextView(getActivity().getBaseContext());
lastName.setBackgroundResource(R.drawable.borderr);
compName.append(cur.getString(1));
compName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
compName.setPadding(30, 0, 0, 0);
firstName.append(cur.getString(21));
firstName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
firstName.setPadding(30, 0, 0, 0);
midName.append(cur.getString(22));
midName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
midName.setPadding(30, 0, 0, 0);
lastName.append(cur.getString(23));
lastName.setTextColor(this.getResources().getColor(R.color.colorPrimary));
lastName.setPadding(30, 0, 0, 0);
// String name =firstName.getText().toString()+midName.getText().toString()+lastName.getText().toString();
firstName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String nameValue = firstName.getText().toString();
String companyValue = compName.getText().toString();
Intent intent = new Intent(getActivity().getApplicationContext(), ShowDetailData.class);
intent.putExtra("name", nameValue);
intent.putExtra("accNo", companyValue);
Toast.makeText(getActivity().getApplicationContext(), nameValue, Toast.LENGTH_LONG).show();
startActivity(intent);
}
});
tr.addView(firstName);
tr.addView(compName);
tableLayout.addView(tr);
cur.moveToNext();
/* count++;
nextPage++;
Toast.makeText(getActivity().getApplicationContext(), "count is : " + count, Toast.LENGTH_LONG).show();*/
//cur.close();
}
} finally {
cur.close();
db.close();
}
} else {
Toast.makeText(getActivity().getApplicationContext(), "no Data", Toast.LENGTH_LONG).show();
}
}
}
/*
*/
/*
buttonNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nextPage++;
Toast.makeText(getActivity(), "next page is"+nextPage, Toast.LENGTH_SHORT).show();
}
});*/
private void loadList(int number){
ArrayList<String> sort = new ArrayList<String >();
title.setText("Page "+(number+1+" of " +pageCount));
int start = number * NUM_ITEMS_PAGE;
for (int i=start; i<(start)+NUM_ITEMS_PAGE; i++)
{
if(i<data)
{
sort.add(String.valueOf(data));
}
else {
break;
}
// adapter = new ArrayAdapter<String>(getActivity(), //android.R.layout.simple_list_item_1,sort);
// tablerow.setAdapter(adapter);
//implement table row in adapter
}}
private void checkEnable(){
if(increment+1 == pageCount)
{
buttonNext.setEnabled(false);
}
else if(increment == 0){
buttonPrev.setEnabled(false);
}
else {
buttonPrev.setEnabled(true);
buttonNext.setEnabled(true);
}
}
}
I want to know how can i change the page after no. of rows exceeds 30. I am unable to do pagination.
Currently i am using Sqlite and all the filled data is appearing on the first page.
I want to divide the data and want it appear in set of 30 after click of previous and next.
I am running into an issue where my app crashes and I am given an error that reads
04-28 15:08:32.378: E/AndroidRuntime(27229): FATAL EXCEPTION: main
04-28 15:08:32.378: E/AndroidRuntime(27229): Process: com.example.datetracker, PID: 27229
04-28 15:08:32.378: E/AndroidRuntime(27229): java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0
04-28 15:08:32.378: E/AndroidRuntime(27229): at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
I can successfully remove an item from the lstEvents arraylist and I can also remove the event object from the database, but I can't seem to have it disappear from the screen. No matter what I do it seems to keep refreshing the listview with the same contents.
What am I doing wrong? I keep getting this IndexOutOfBoundsException, and I am pretty sure it is because the view is not updating properly and it continues to allow me to swipe-to-dismiss which is in return trying to delete objects which eventually are not going to be there.
MainActivity
public class MainActivity extends FragmentActivity implements OnClickListener {
ListView listView;
int lastIndex = -1;
ArrayList<Event> lstEvents = new ArrayList<Event>();
ArrayList<Event> templstEvents = new ArrayList<Event>();
// detail view
TextView tvTitle, tvTime, tvDate;
ImageView ivPic;
View vw_master;
boolean _isBack = true;
ImageButton add;
String title;
String date;
String time;
int resId;
Context context;
static final int PICK_CONTACT_REQUEST = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
// // get detail controls
tvTitle = (TextView) findViewById(R.id.textViewTitle);
tvDate = (TextView) findViewById(R.id.textViewDate);
tvTime = (TextView) findViewById(R.id.textViewTime);
ivPic = (ImageView) findViewById(R.id.imageView1);
add = (ImageButton) findViewById(R.id.add);
add.setOnClickListener(this);
// ///////////////////////////////LISTVIEW////////////////////////////////////////
// Create the adapter to convert the array to views
EventAdapter adapter = new EventAdapter(this, lstEvents);
// attach adapter to a list view
listView = (ListView) findViewById(R.id.listViewFragment);
listView.setAdapter(adapter);
context = this;
SwipeDismissListViewTouchListener touchListener = new SwipeDismissListViewTouchListener(
listView,
new SwipeDismissListViewTouchListener.DismissCallbacks() {
EventAdapter adapter = new EventAdapter(context, lstEvents);
DatabaseHandler db = new DatabaseHandler(context);
#Override
public boolean canDismiss(int position) {
return true;
}
#Override
public void onDismiss(ListView listView,
int[] reverseSortedPositions) {
for (int position : reverseSortedPositions) {
if (lstEvents.isEmpty()){
Log.e("EMPTYLIST","THELISTISEMPTY");
}
else
db.deleteEvent(lstEvents.get(position));
lstEvents.remove(position);
//adapter.remove(adapter.getItem(position));
}
adapter.notifyDataSetChanged();
}
});
listView.setOnTouchListener(touchListener);
// Setting this scroll listener is required to ensure that during
// ListView scrolling,
// we don't look for swipes.
listView.setOnScrollListener(touchListener.makeScrollListener());
// /////////////////////////////DATABASE/////////////////////////////////////////////
DatabaseHandler db = new DatabaseHandler(this);
// /////////////////////////////DATABASE/////////////////////////////////////////////
lstEvents = db.getAllContacts();
adapter.addAll(lstEvents);
adapter.notifyDataSetChanged();
}
// #Override
// protected void onResume() {
// // TODO Auto-generated method stub
// super.onResume();
// //
// /////////////////////////////DATABASE/////////////////////////////////////////////
// DatabaseHandler db = new DatabaseHandler(this);
// //
// /////////////////////////////DATABASE/////////////////////////////////////////////
//
// lstEvents = db.getAllContacts();
// EventAdapter adapter = new EventAdapter(this, lstEvents);
// adapter.addAll(lstEvents);
// adapter.notifyDataSetChanged();
// }
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.add:
Intent intent = new Intent(this, CreateActivity.class);
startActivityForResult(intent, 100);
break;
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// /////////////////////////////DATABASE/////////////////////////////////////////////
DatabaseHandler db = new DatabaseHandler(this);
// /////////////////////////////DATABASE/////////////////////////////////////////////
// Create the adapter to convert the array to views
EventAdapter adapter = new EventAdapter(this, lstEvents);
// attach adapter to a list view
listView = (ListView) findViewById(R.id.listViewFragment);
listView.setAdapter(adapter);
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
Bundle b = data.getExtras();
title = b.getString("TITLE");
time = b.getString("TIME");
date = b.getString("DATE");
Bitmap bitmap = b.getParcelable("BITMAP");
// ///CONVERTING A BITMAP TO A BYTE[]
byte[] image = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
image = bos.toByteArray();
// ///////
// /////////////////////////////DATABASE/////////////////////////////////////////////
/**
* CRUD OPERATIONS
*/
Log.e("Insert: ", "Inserting ..");
db.addEvent(new Event((int) Math.floor(Math.random() * 101),
title, time, date, image));
// Reading all contacts
Log.e("Reading: ", "Reading all contacts..");
lstEvents = db.getAllContacts();
adapter.addAll(lstEvents);
adapter.notifyDataSetChanged();
// logging all events
for (Event ev : lstEvents) {
String log = "Id: " + ev.get_Id() + " ,Title: "
+ ev.get_title() + " ,Date: " + ev.get_date()
+ " ,RESOURCEID: " + ev.get_image();
// Writing Contacts to log
Log.e("Name: ", log);
}
// /////////////////////////////DATABASE/////////////////////////////////////////////
}
}
}
}
SwipeDismissListViewTouchListener
public class SwipeDismissListViewTouchListener implements View.OnTouchListener {
// Cached ViewConfiguration and system-wide constant values
private int mSlop;
private int mMinFlingVelocity;
private int mMaxFlingVelocity;
private long mAnimationTime;
// Fixed properties
private ListView mListView;
private DismissCallbacks mCallbacks;
private int mViewWidth = 1; // 1 and not 0 to prevent dividing by zero
// Transient properties
private List<PendingDismissData> mPendingDismisses = new ArrayList<PendingDismissData>();
private int mDismissAnimationRefCount = 0;
private float mDownX;
private boolean mSwiping;
private VelocityTracker mVelocityTracker;
private int mDownPosition;
private View mDownView;
private boolean mPaused;
/**
* The callback interface used by {#link SwipeDismissListViewTouchListener} to inform its client
* about a successful dismissal of one or more list item positions.
*/
public interface DismissCallbacks {
/**
* Called to determine whether the given position can be dismissed.
*/
boolean canDismiss(int position);
/**
* Called when the user has indicated they she would like to dismiss one or more list item
* positions.
*
* #param listView The originating {#link ListView}.
* #param reverseSortedPositions An array of positions to dismiss, sorted in descending
* order for convenience.
*/
void onDismiss(ListView listView, int[] reverseSortedPositions);
}
/**
* Constructs a new swipe-to-dismiss touch listener for the given list view.
*
* #param listView The list view whose items should be dismissable.
* #param callbacks The callback to trigger when the user has indicated that she would like to
* dismiss one or more list items.
*/
public SwipeDismissListViewTouchListener(ListView listView, DismissCallbacks callbacks) {
ViewConfiguration vc = ViewConfiguration.get(listView.getContext());
mSlop = vc.getScaledTouchSlop();
mMinFlingVelocity = vc.getScaledMinimumFlingVelocity() * 16;
mMaxFlingVelocity = vc.getScaledMaximumFlingVelocity();
mAnimationTime = listView.getContext().getResources().getInteger(
android.R.integer.config_shortAnimTime);
mListView = listView;
mCallbacks = callbacks;
}
/**
* Enables or disables (pauses or resumes) watching for swipe-to-dismiss gestures.
*
* #param enabled Whether or not to watch for gestures.
*/
public void setEnabled(boolean enabled) {
mPaused = !enabled;
}
/**
* Returns an {#link android.widget.AbsListView.OnScrollListener} to be added to the {#link
* ListView} using {#link ListView#setOnScrollListener(android.widget.AbsListView.OnScrollListener)}.
* If a scroll listener is already assigned, the caller should still pass scroll changes through
* to this listener. This will ensure that this {#link SwipeDismissListViewTouchListener} is
* paused during list view scrolling.</p>
*
* #see SwipeDismissListViewTouchListener
*/
public AbsListView.OnScrollListener makeScrollListener() {
return new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView absListView, int scrollState) {
setEnabled(scrollState != AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL);
}
#Override
public void onScroll(AbsListView absListView, int i, int i1, int i2) {
}
};
}
/**
* Manually cause the item at the given position to be dismissed (trigger the dismiss
* animation).
*/
public void dismiss(int position) {
dismiss(getViewForPosition(position), position, true);
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (mViewWidth < 2) {
mViewWidth = mListView.getWidth();
}
switch (motionEvent.getActionMasked()) {
case MotionEvent.ACTION_DOWN: {
if (mPaused) {
return false;
}
// TODO: ensure this is a finger, and set a flag
// Find the child view that was touched (perform a hit test)
Rect rect = new Rect();
int childCount = mListView.getChildCount();
int[] listViewCoords = new int[2];
mListView.getLocationOnScreen(listViewCoords);
int x = (int) motionEvent.getRawX() - listViewCoords[0];
int y = (int) motionEvent.getRawY() - listViewCoords[1];
View child;
for (int i = 0; i < childCount; i++) {
child = mListView.getChildAt(i);
child.getHitRect(rect);
if (rect.contains(x, y)) {
mDownView = child;
break;
}
}
if (mDownView != null) {
mDownX = motionEvent.getRawX();
mDownPosition = mListView.getPositionForView(mDownView);
if (mCallbacks.canDismiss(mDownPosition)) {
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(motionEvent);
} else {
mDownView = null;
}
}
view.onTouchEvent(motionEvent);
return true;
}
case MotionEvent.ACTION_UP: {
if (mVelocityTracker == null) {
break;
}
float deltaX = motionEvent.getRawX() - mDownX;
mVelocityTracker.addMovement(motionEvent);
mVelocityTracker.computeCurrentVelocity(1000);
float velocityX = mVelocityTracker.getXVelocity();
float absVelocityX = Math.abs(velocityX);
float absVelocityY = Math.abs(mVelocityTracker.getYVelocity());
boolean dismiss = false;
boolean dismissRight = false;
if (Math.abs(deltaX) > mViewWidth / 2) {
dismiss = true;
dismissRight = deltaX > 0;
} else if (mMinFlingVelocity <= absVelocityX && absVelocityX <= mMaxFlingVelocity
&& absVelocityY < absVelocityX) {
// dismiss only if flinging in the same direction as dragging
dismiss = (velocityX < 0) == (deltaX < 0);
dismissRight = mVelocityTracker.getXVelocity() > 0;
}
if (dismiss) {
// dismiss
dismiss(mDownView, mDownPosition, dismissRight);
} else {
// cancel
mDownView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
break;
}
case MotionEvent.ACTION_CANCEL: {
if (mVelocityTracker == null) {
break;
}
if (mDownView != null) {
// cancel
mDownView.animate()
.translationX(0)
.alpha(1)
.setDuration(mAnimationTime)
.setListener(null);
}
mVelocityTracker.recycle();
mVelocityTracker = null;
mDownX = 0;
mDownView = null;
mDownPosition = ListView.INVALID_POSITION;
mSwiping = false;
break;
}
case MotionEvent.ACTION_MOVE: {
if (mVelocityTracker == null || mPaused) {
break;
}
mVelocityTracker.addMovement(motionEvent);
float deltaX = motionEvent.getRawX() - mDownX;
if (Math.abs(deltaX) > mSlop) {
mSwiping = true;
mListView.requestDisallowInterceptTouchEvent(true);
// Cancel ListView's touch (un-highlighting the item)
MotionEvent cancelEvent = MotionEvent.obtain(motionEvent);
cancelEvent.setAction(MotionEvent.ACTION_CANCEL |
(motionEvent.getActionIndex()
<< MotionEvent.ACTION_POINTER_INDEX_SHIFT));
mListView.onTouchEvent(cancelEvent);
cancelEvent.recycle();
}
if (mSwiping) {
mDownView.setTranslationX(deltaX);
mDownView.setAlpha(Math.max(0.15f, Math.min(1f,
1f - 2f * Math.abs(deltaX) / mViewWidth)));
return true;
}
break;
}
}
return false;
}
private void dismiss(final View view, final int position, boolean dismissRight) {
++mDismissAnimationRefCount;
if (view == null) {
// No view, shortcut to calling onDismiss to let it deal with adapter
// updates and all that.
mCallbacks.onDismiss(mListView, new int[] { position });
return;
}
view.animate()
.translationX(dismissRight ? mViewWidth : -mViewWidth)
.alpha(0)
.setDuration(mAnimationTime)
.setListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
performDismiss(view, position);
}
});
}
private View getViewForPosition(int position) {
int index = position
- (mListView.getFirstVisiblePosition() - mListView.getHeaderViewsCount());
return (index >= 0 && index < mListView.getChildCount())
? mListView.getChildAt(index)
: null;
}
class PendingDismissData implements Comparable<PendingDismissData> {
public int position;
public View view;
public PendingDismissData(int position, View view) {
this.position = position;
this.view = view;
}
#Override
public int compareTo(PendingDismissData other) {
// Sort by descending position
return other.position - position;
}
}
private void performDismiss(final View dismissView, final int dismissPosition) {
// Animate the dismissed list item to zero-height and fire the dismiss callback when
// all dismissed list item animations have completed. This triggers layout on each animation
// frame; in the future we may want to do something smarter and more performant.
final ViewGroup.LayoutParams lp = dismissView.getLayoutParams();
final int originalHeight = dismissView.getHeight();
ValueAnimator animator = ValueAnimator.ofInt(originalHeight, 1).setDuration(mAnimationTime);
animator.addListener(new AnimatorListenerAdapter() {
#Override
public void onAnimationEnd(Animator animation) {
--mDismissAnimationRefCount;
if (mDismissAnimationRefCount == 0) {
// No active animations, process all pending dismisses.
// Sort by descending position
Collections.sort(mPendingDismisses);
int[] dismissPositions = new int[mPendingDismisses.size()];
for (int i = mPendingDismisses.size() - 1; i >= 0; i--) {
dismissPositions[i] = mPendingDismisses.get(i).position;
}
mCallbacks.onDismiss(mListView, dismissPositions);
ViewGroup.LayoutParams lp;
for (PendingDismissData pendingDismiss : mPendingDismisses) {
// Reset view presentation
pendingDismiss.view.setAlpha(1f);
pendingDismiss.view.setTranslationX(0);
lp = pendingDismiss.view.getLayoutParams();
lp.height = originalHeight;
pendingDismiss.view.setLayoutParams(lp);
}
mPendingDismisses.clear();
}
}
});
animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator valueAnimator) {
lp.height = (Integer) valueAnimator.getAnimatedValue();
dismissView.setLayoutParams(lp);
}
});
mPendingDismisses.add(new PendingDismissData(dismissPosition, dismissView));
animator.start();
}
}
DatabaseHandler
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "scheduleManager";
// Contacts table name
private static final String TABLE_EVENTS = "events";
// Contacts Table Columns names
private static final String KEY_ID = "id";
private static final String KEY_TITLE = "title";
private static final String KEY_TIME = "time";
private static final String KEY_DATE = "date";
private static final String KEY_IMAGE = "image";
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_EVENTS_TABLE = "CREATE TABLE " + TABLE_EVENTS + "("
+ KEY_ID + " INTEGER," + KEY_TITLE + " TEXT,"
+ KEY_TIME + " TEXT," + KEY_DATE + " TEXT," + KEY_IMAGE + " BLOB" + ")";
db.execSQL(CREATE_EVENTS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_EVENTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
//adding an event (NEEDS TO ADD DRAWABLE)
public void addEvent(Event event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_ID, event.get_Id()); //Event ID
values.put(KEY_TITLE, event.get_title()); // Event Title
values.put(KEY_TIME, event.get_time()); // Event Time
values.put(KEY_DATE, event.get_date()); // Event Date
values.put(KEY_IMAGE, event.get_image()); // Event RESOURCEID
// Inserting Row
db.insert(TABLE_EVENTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
public Event getEvent(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_EVENTS, new String[] { KEY_ID,
KEY_TITLE, KEY_TIME, KEY_DATE, KEY_IMAGE }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Event event = new Event(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getBlob(4));
// return contact
return event;
}
// Getting All Contacts
public ArrayList<Event> getAllContacts() {
ArrayList<Event> eventList = new ArrayList<Event>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_EVENTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Event event = new Event();
event.set_Id(Integer.parseInt(cursor.getString(0)));
event.set_title(cursor.getString(1));
event.set_time(cursor.getString(2));
event.set_date(cursor.getString(3));
event.set_image(cursor.getBlob(4));
eventList.add(event);
} while (cursor.moveToNext());
}
// return contact list
return eventList;
}
// Getting event Count
public int getEventsCount() {
String countQuery = "SELECT * FROM " + TABLE_EVENTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
// Updating single contact
public int updateEvent(Event event) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TITLE, event.get_title());
values.put(KEY_TIME, event.get_time());
values.put(KEY_DATE, event.get_date());
// updating row
return db.update(TABLE_EVENTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(event.get_Id()) });
}
// Deleting single contact
public void deleteEvent(Event event) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_EVENTS, KEY_ID + " = ?",
new String[] { String.valueOf(event.get_Id()) });
db.close();
}
}
EventAdapter
public class EventAdapter extends ArrayAdapter<Event> {
// View lookup cache
private static class ViewHolder {
//adding drawable to imageview
ImageView img;
TextView title;
TextView time;
TextView date;
}
public EventAdapter(Context context, ArrayList<Event> objects) {
super(context, R.layout.date_detail);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Event event = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.date_detail, null);
viewHolder.title = (TextView) convertView
.findViewById(R.id.textViewTitle);
viewHolder.time = (TextView) convertView
.findViewById(R.id.textViewTime);
viewHolder.date = (TextView) convertView
.findViewById(R.id.textViewDate);
//adding drawable to imageview
viewHolder.img = (ImageView) convertView
.findViewById(R.id.imageView1);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
// Populate the data into the template view using the data object
viewHolder.title.setText(event._title);
viewHolder.time.setText(event._time);
viewHolder.date.setText(event._date);
//convert from byte array to bitmap
Bitmap bitmap = convertByteArrayToBitmap(event._image);
// CONVERT BITMAP TO DRAWABLE
viewHolder.img.setImageBitmap(bitmap);
// Return the completed view to render on screen
return convertView;
}
public static Bitmap convertByteArrayToBitmap(
byte[] byteArrayToBeCOnvertedIntoBitMap)
{
Bitmap bitmap = BitmapFactory.decodeByteArray(
byteArrayToBeCOnvertedIntoBitMap, 0,
byteArrayToBeCOnvertedIntoBitMap.length);
return bitmap;
}
}
You are trying to remove the first item from an empty list. It says so in the exception text.
The problem was solved by removing the following lines of code in the swipeDismissViewListener and the OnActivityResult.
DatabaseHandler db = new DatabaseHandler(context);
EventAdapter adapter = new EventAdapter(context, db.getAllContacts());