I user LoaderManager and CursorLoader to load the data from my database using a ContentProvider.
Now, the initial load is fine. I have a ListView that display all the rows from the DB(only the names-String adapter).
Now, when I add/delete a row from the database, I want to refresh the ListView so it will display the recent changes.
Currently I just restart the loader with the method "restartLoader" whenever a change is commited but I want to ask if there is another way of doing this without restarting the loader.
Here is my activity class code:
package com.silverfix.phony.activities;
import java.util.ArrayList;
import com.silverfix.phony.R;
import com.silverfix.phony.contentprovider.PhonyContentProvider;
import com.silverfix.phony.database.RingtonesTable;
import android.app.Activity;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.ContentValues;
import android.content.CursorLoader;
import android.content.Intent;
import android.content.Loader;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.view.View.OnCreateContextMenuListener;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class RingtonesActivity extends Activity implements LoaderCallbacks<Cursor>{
private final int PICK_RINGTONE_CODE = 1;
private final int CURSOR_LOADER_ID = 1;
private final int EDIT_ID = 1;
private final int DELETE_ID = 2;
private String[] ContextCommands;
private ArrayAdapter<String> adapter;
private ArrayList<String> ringtones;
private ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ringtones);
listview = (ListView) findViewById(R.id.list);
Button add = (Button) findViewById(R.id.add_ringtone);
add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_RINGTONE_CODE);
}
});
fillData();
}
#Override
protected void onActivityResult(int arg0, int arg1, Intent arg2) {
super.onActivityResult(arg0, arg1, arg2);
switch (arg0) {
case 1: // PICK_RINGTONE_CODE
if (arg1 == RESULT_OK) {
Uri ringtoneURI = arg2.getData();
String[] projection = { MediaStore.MediaColumns.DISPLAY_NAME };
Cursor cursor = getContentResolver().query(ringtoneURI,
projection, null, null, null);
cursor.moveToFirst();
int column = cursor
.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME);
String displayName = cursor.getString(column);
addRingtone(ringtoneURI, displayName);
cursor.close();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.ringtones, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void fillData() {
getLoaderManager().initLoader(CURSOR_LOADER_ID, null, this);
ringtones = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, ringtones);
ContextCommands = getResources().getStringArray(R.array.commands);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
editRingtone();
}
});
registerForContextMenu(listview);
listview.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
if (v.getId()==R.id.list) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)menuInfo;
menu.setHeaderTitle(ContextCommands[info.position]);
String[] menuItems = getResources().getStringArray(R.array.commands);
menu.add(Menu.NONE, EDIT_ID, 0, menuItems[0]);
menu.add(Menu.NONE, DELETE_ID, 0, menuItems[1]);
}
}
});
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch(item.getItemId()) {
case EDIT_ID:
editRingtone();
return true;
case DELETE_ID:
String name = adapter.getItem(((AdapterContextMenuInfo) item.getMenuInfo()).position);
getContentResolver().delete(PhonyContentProvider.RINGTONES_URI, RingtonesTable.COLUMN_NAME
+ "='" + name + "'", null);
return true;
default:
return super.onContextItemSelected(item);
}
}
private void editRingtone() {
Intent i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, PICK_RINGTONE_CODE);
}
private void addRingtone(Uri uri, String name) {
String[] projection = { RingtonesTable.COLUMN_NAME };
Cursor cursor = getContentResolver().query(
PhonyContentProvider.RINGTONES_URI, projection,
RingtonesTable.COLUMN_NAME + "='"+name+"'", null, null);
if (cursor.getCount() == 0) {
ContentValues values = new ContentValues();
values.put(RingtonesTable.COLUMN_NAME, name);
values.put(RingtonesTable.COLUMN_URI, uri.toString());
getContentResolver().insert(PhonyContentProvider.RINGTONES_URI,
values);
getLoaderManager().restartLoader(CURSOR_LOADER_ID, null, this);
} else {
Toast.makeText(this, "You already picked that ringtone!",
Toast.LENGTH_LONG).show();
cursor.close();
}
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String[] projection = {RingtonesTable.COLUMN_ID, RingtonesTable.COLUMN_NAME, RingtonesTable.COLUMN_URI};
return new CursorLoader(this, PhonyContentProvider.RINGTONES_URI, projection, null, null, null);
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
swapCursor(null);
}
private void swapCursor(Cursor cursor) {
if(cursor != null) {
cursor.moveToFirst();
ringtones.clear();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
int column = cursor.getColumnIndex(RingtonesTable.COLUMN_NAME);
ringtones.add(cursor.getString(column));
}
adapter.notifyDataSetChanged();
cursor.close();
return;
}
ringtones.clear();
adapter.notifyDataSetChanged();
}
}
Since you already have access to the loader, you may not expect that much of a change, but another way of implementing this is by having the cursor setting PhonyContentProvider.RINGTONES_URI as its notification uri and notifying the uri whenever the database data changes.
Relevant methods:
setNotificationUri
notifyChange
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 have custom list view and my data is coming from sqlite database. Now I want to change specific listview item's background color according to the id. First, I check the id if exist in database, then change particular item row background color according to the id.
My problem is that it checks successfully, but when I tried to change background color it changes whole listview background color. Here is picture and code of my data. Then you'll get my point, what actually I want to say you!
My db:
Whole listview color change:
My code:
package bible.swordof.God;
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.opengl.Visibility;
import android.os.Vibrator;
import android.preference.PreferenceManager;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.amulyakhare.textdrawable.TextDrawable;
import com.amulyakhare.textdrawable.util.ColorGenerator;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import es.dmoral.toasty.Toasty;
import petrov.kristiyan.colorpicker.ColorPicker;
import static android.content.Context.MODE_PRIVATE;
import static android.database.sqlite.SQLiteDatabase.CONFLICT_NONE;
import static android.icu.lang.UCharacter.GraphemeClusterBreak.V;
import static android.support.constraint.Constraints.TAG;
import static android.support.v4.content.ContextCompat.createDeviceProtectedStorageContext;
import static android.support.v4.content.ContextCompat.startActivity;
public class FullverseAdopter extends ArrayAdapter<String> {
private ALLVERSE activity;
private List<String> versenumber;
private List<String>verseid;
private List<String> verselist;
private List<String> refernce;
TextToSpeech textToSpeech;
private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;
private boolean highlight=false;
LinearLayout linearLayout;
public String ex="switch";
//check for availabe language
int result;
public FullverseAdopter(ALLVERSE context, int resource, List<String> versenumber, List<String> verselist, List<String> refernce, List<String>verseid) {
super(context, resource, versenumber);
this.activity = context;
this.versenumber = versenumber;
this.verselist = verselist;
this.refernce = refernce;
this.verseid=verseid;
}
#Override
public int getCount() {
return versenumber.size();
}
#Override
public String getItem(int position) {
return versenumber.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
// If holder not exist then locate all view from UI file.
if (convertView == null) {
// inflate UI from XML file
convertView = inflater.inflate(R.layout.versedisplayrow, parent, false);
// get all UI view
holder = new ViewHolder(convertView);
// set tag for holder
holder.versenumber = (TextView) convertView.findViewById(R.id.versenumber);
holder.verselist = (TextView) convertView.findViewById(R.id.verse);
holder.addfavoruite=(ToggleButton)convertView.findViewById(R.id.adbookmark);
//check if id is exits in db
if(CheckIsDataAlreadyInDBorNot("t_asv","id","1001001"))
{
holder.linearLayout.setBackgroundColor(Color.parseColor("#008577"));
}
convertView.setTag(holder);
} else {
// if holder created, get tag from view
holder = (ViewHolder) convertView.getTag();
}
holder.versenumber.setText(versenumber.get(position));
holder.verselist.setText(verselist.get(position));
holder.linearLayout.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
//Toasty.success(activity, "PICK COLOR", Toast.LENGTH_SHORT, true).show();
Vibrator vibe = (Vibrator)activity.getSystemService(Context.VIBRATOR_SERVICE);
vibe.vibrate(100);
Toast.makeText(activity, ""+verseid.get(position), Toast.LENGTH_SHORT).show();
/* ColorPicker colorPicker = new ColorPicker(activity);
ArrayList<String>colors=new ArrayList<>();
colors.add("#e0e0eb");
colors.add("#ccffff");
colors.add("#ffe6ff");
colors.add("#ffffcc");
colors.add("#ccffcc");
colors.add("#e6f2ff");
colorPicker.setColors(colors).setColumns(4).setTitle("HIGHLIGHT VERSE").setRoundColorButton(true).setOnChooseColorListener(new ColorPicker.OnChooseColorListener() {
#Override
public void onChooseColor(int position, int color) {
// holder.linearLayout.setBackgroundColor(color);
}
#Override
public void onCancel() {
}
}).show();*/
return false;
}
});
/*holder.verselist.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
holder.verselist.setBackgroundColor(Color.parseColor("#e0e0eb"));
return false;
}
});*/
//verselist highlight
/*holder.verselist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});*/
//share verse
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toasty.info(activity, "Sharing a verse.", Toast.LENGTH_SHORT, true).show();
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, refernce.get(position) + ":" + versenumber.get(position) + '\n' + verselist.get(position));
sendIntent.setType("text/plain");
activity.startActivity(sendIntent);
}
});
//add in favourite
holder.addfavoruite.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
ContentValues contentValues=new ContentValues();
contentValues.put("id",verseid.get(position));
contentValues.put("bookname",refernce.get(position));
contentValues.put("versenumber",versenumber.get(position));
contentValues.put("verse",verselist.get(position));
long check=mDb.insert("favourite",null,contentValues);
Log.d("MY_TAG","DB IS NOW "+check);
Toasty.success(activity, "Added in favouite", Toast.LENGTH_SHORT, true).show();
}else {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getWritableDatabase();
long delete= mDb.delete("favourite","id=?",new String[]{verseid.get(position)});
Toasty.error(activity, "Remove in favouite", Toast.LENGTH_SHORT, true).show();
}
}
});
/* textToSpeech = new TextToSpeech(activity, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
result = textToSpeech.setLanguage(Locale.ENGLISH);
} else {
Toast.makeText(activity, "YOUR DEVICE NOT SUPPORTED", Toast.LENGTH_SHORT).show();
}
}
});
*/
//My toggle button
/* holder.speakverse.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(activity, "I AM CLICKED", Toast.LENGTH_SHORT).show();
if (result == TextToSpeech.LANG_NOT_SUPPORTED || result == TextToSpeech.LANG_MISSING_DATA) {
Toast.makeText(activity, "Language not supported or Missing", Toast.LENGTH_SHORT).show();
} else {
textToSpeech.speak(verselist.get(position), TextToSpeech.QUEUE_FLUSH, null);
}
}
});*/
return convertView;
}
static class ViewHolder {
private TextView versenumber;
private TextView verselist;
private ImageView share;
private ToggleButton addfavoruite;
private ImageView speakverse;
private LinearLayout linearLayout;
public ViewHolder(View v) {
versenumber = (TextView) v.findViewById(R.id.versenumber);
verselist = (TextView) v.findViewById(R.id.verse);
share = (ImageView) v.findViewById(R.id.share);
/*speakverse = (ImageView) v.findViewById(R.id.speakverse);*/
addfavoruite=(ToggleButton)v.findViewById(R.id.adbookmark);
linearLayout=(LinearLayout)v.findViewById(R.id.layout);
}
}
public boolean CheckIsDataAlreadyInDBorNot(String TableName, String dbfield, String fieldValue) {
mDBHelper = new DatabaseHelper(activity);
mDb = mDBHelper.getReadableDatabase();
String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
Cursor cursor = mDb.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursor.close();
Toast.makeText(activity, "false", Toast.LENGTH_SHORT).show();
return false;
}else {
Toast.makeText(activity, "TRUE", Toast.LENGTH_SHORT).show();
}
cursor.close();
return true;
}
public void opecolorpicker(){
}
}
Assuming you store the IDs in private List<String>verseid;, you can use it to check the ID of current ListView item.
The current item position is passed to you in final int position parameter.
So to check and apply color:
Remove
if(CheckIsDataAlreadyInDBorNot("t_asv","id","1001001"))
{
holder.linearLayout.setBackgroundColor(Color.parseColor("#008577"));
}
from if (convertView == null) {
Then add this code right outside that if:
if("1001001".equals(verseid.get(position))) {
//change the color
} else {
//set the color to default
}
Note that due to the way the ListView works (recycling items) you have to set the default color inside else.
I am working on a sql listview , however I want to display the listview which is in an activity class (CountryListActivity.java) as a fragment in a tablayout . dbManager=newDBManager(this) gives an error when I change it to getActivity , how do I fix this?
package com.trinitytabnavigationdrawer;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.widget.SimpleCursorAdapter;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.TextView;
public class CountryListActivity extends ActionBarActivity {
private DBManager dbManager;
private ListView listView;
private SimpleCursorAdapter adapter;
final String[] from = new String[] {
DatabaseHelper._ID,
DatabaseHelper.SUBJECT, DatabaseHelper.DESC
};
final int[] to = new int[] {
R.id.id, R.id.title, R.id.desc
};
#
Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_emp_list);
dbManager = new DBManager(this);
dbManager.open();
Cursor cursor = dbManager.fetch();
listView = (ListView) findViewById(R.id.list_view);
listView.setEmptyView(findViewById(R.id.empty));
adapter = new SimpleCursorAdapter(this, R.layout.activity_view_record, cursor, from, to, 0);
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
// OnCLickListiner For List Items
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {#
Override
public void onItemClick(AdapterView <? > parent, View view, int position, long viewId) {
TextView idTextView = (TextView) view.findViewById(R.id.id);
TextView titleTextView = (TextView) view.findViewById(R.id.title);
TextView descTextView = (TextView) view.findViewById(R.id.desc);
String id = idTextView.getText().toString();
String title = titleTextView.getText().toString();
String desc = descTextView.getText().toString();
Intent modify_intent = new Intent(getApplicationContext(), ModifyCountryActivity.class);
modify_intent.putExtra("title", title);
modify_intent.putExtra("desc", desc);
modify_intent.putExtra("id", id);
startActivity(modify_intent);
}
});
}
#
Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#
Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.add_record) {
Intent add_mem = new Intent(this, AddCountryActivity.class);
startActivity(add_mem);
}
return super.onOptionsItemSelected(item);
}
}
And the database manager class is as follows :
package com.trinitytabnavigationdrawer;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class DBManager {
private DatabaseHelper dbHelper;
private Context context;
private SQLiteDatabase database;
public DBManager(Context c) {
context = c;
}
public DBManager open() throws SQLException {
dbHelper = new DatabaseHelper(context);
database = dbHelper.getWritableDatabase();
return this;
}
public void close() {
dbHelper.close();
}
public void insert(String name, String desc) {
ContentValues contentValue = new ContentValues();
contentValue.put(DatabaseHelper.SUBJECT, name);
contentValue.put(DatabaseHelper.DESC, desc);
database.insert(DatabaseHelper.TABLE_NAME, null, contentValue);
}
public Cursor fetch() {
String[] columns = new String[] {
DatabaseHelper._ID, DatabaseHelper.SUBJECT, DatabaseHelper.DESC
};
Cursor cursor = database.query(DatabaseHelper.TABLE_NAME, columns, null, null, null, null, null);
if (cursor != null) {
cursor.moveToFirst();
}
return cursor;
}
public int update(long _id, String name, String desc) {
ContentValues contentValues = new ContentValues();
contentValues.put(DatabaseHelper.SUBJECT, name);
contentValues.put(DatabaseHelper.DESC, desc);
int i = database.update(DatabaseHelper.TABLE_NAME, contentValues, DatabaseHelper._ID + " = " + _id, null);
return i;
}
public void delete(long _id) {
database.delete(DatabaseHelper.TABLE_NAME, DatabaseHelper._ID + "=" + _id, null);
}
}
Please I have no clue what else to do ! Been trying for a week now , sorry I'm not good at this , just following some tutorials ! :(
Initialize the dbManager and other objects which require context inside onAttach (Context context) rather than onCreateView() method of Fragment.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I need to add the share feature to my Android app (The app is for writing notes and store them in a SQLite database) (The share button only shares the body of the note). I did it, but when I press "Share" button, it shows FC (Force Close) and the app stops.
The code of the share feature (It's in the MainActivity class):
...
#Override
public boolean onContextItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
String shareBody = NotesModel.actualNote.body;
Intent shareIntent = new Intent("android.intent.action.SEND");
shareIntent.setType("text/plain");
shareIntent.putExtra("android.intent.extra.TEXT", shareBody);
startActivity(shareIntent);
return true;
...
The whole MainActivity class:
package com.twitter.i_droidi.mynotesdonation;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
import com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton;
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener, View.OnClickListener {
ListView lv;
NotesDataSource nDS;
List<NotesModel> notesList;
String[] notes;
int i;
ArrayAdapter<String> adapter;
FloatingActionButton actionButton;
public static final String floatingButtonTag = "";
CheckBox checkBox;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View checkBoxView = View.inflate(this, R.layout.checkbox, null);
checkBox = (CheckBox) checkBoxView.findViewById(R.id.checkboxDialog);
checkBox.setOnClickListener(this);
loadSavedPreferences();
checkBox.setText(R.string.do_not_show_this_again);
final Context context = this;
AlertDialog.Builder mainDialog = new AlertDialog.Builder(context);
mainDialog.setTitle(R.string.thanks);
mainDialog.setMessage(R.string.main_dialog_body);
mainDialog.setIcon(R.drawable.my_notes);
mainDialog.setView(checkBoxView);
mainDialog.setPositiveButton(R.string.welcome, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Do Not Do Anything.
}
});
AlertDialog alertDialog = mainDialog.create();
if (checkBox.isChecked() == false) {
alertDialog.show();
}
ImageView icon = new ImageView(this);
icon.setImageDrawable(getResources().getDrawable(R.drawable.ic_action_new));
actionButton = new FloatingActionButton.Builder(this)
.setContentView(icon)
.setBackgroundDrawable(R.drawable.the_selector)
.build();
actionButton.setOnClickListener(this);
actionButton.setTag(floatingButtonTag);
nDS = new NotesDataSource(this);
lv = (ListView) findViewById(R.id.lv);
nDS.open();
notesList = nDS.getAllNotes();
nDS.close();
notes = new String[notesList.size()];
for (i = 0; i < notesList.size(); i++) {
notes[i] = notesList.get(i).getTitle();
}
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,
android.R.id.text1, notes);
lv.setAdapter(adapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
}
public void loadSavedPreferences() {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
boolean checkBoxStatus = prefs.getBoolean("Status", false);
if (checkBoxStatus) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
}
public void savePreferences(String key, boolean status) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean(key, status);
editor.commit();
}
#Override
public void onClick(View v) {
if (v.getTag() != null && v.getTag().equals(floatingButtonTag)) {
Intent nNote = new Intent(this, CreateNote.class);
startActivity(nNote);
}
savePreferences("Status", checkBox.isChecked());
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent nView = new Intent(this, ViewEditNote.class);
nView.putExtra("id", notesList.get(position).getId());
nView.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(nView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_item_selected, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onContextItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
String shareBody = NotesModel.body;
Intent shareIntent = new Intent("android.intent.action.SEND");
shareIntent.setType("text/plain");
shareIntent.putExtra("android.intent.extra.TEXT", shareBody);
startActivity(shareIntent);
return true;
case R.id.delete:
AlertDialog.Builder deleteDialog = new AlertDialog.Builder(this);
deleteDialog.setTitle(getString(R.string.delete_title));
deleteDialog.setMessage(R.string.delete_body);
deleteDialog.setIcon(R.drawable.my_notes);
deleteDialog.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface deleteDialog, int witch) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
nDS.open();
nDS.deleteNote(notesList.get(info.position).getId());
notesList = nDS.getAllNotes();
nDS.close();
notes = new String[notesList.size()];
for (i = 0; i < notesList.size(); i++) {
notes[i] = notesList.get(i).getTitle();
}
adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,
android.R.id.text1, notes);
lv.setAdapter(adapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(MainActivity.this);
Toast nDelete = Toast.makeText(MainActivity.this, R.string.deleted, Toast.LENGTH_LONG);
nDelete.show();
return;
}
});
deleteDialog.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface deleteDialog, int which) {
// Do Not Do Anything.
}
});
deleteDialog.show();
return true;
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mainMenuAbout:
AlertDialog.Builder aboutDialog = new AlertDialog.Builder(this);
aboutDialog.setTitle(getString(R.string.about_title));
aboutDialog.setMessage(R.string.about_body);
aboutDialog.setIcon(R.drawable.my_notes);
aboutDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface aboutDialog, int witch) {
// Do Not Do Anything.
}
});
aboutDialog.show();
return true;
case R.id.mainMenuBackupHelp:
AlertDialog.Builder backupHelpDialog = new AlertDialog.Builder(this);
backupHelpDialog.setTitle(getString(R.string.backup_help_title));
backupHelpDialog.setMessage(R.string.backup_help_body);
backupHelpDialog.setIcon(R.drawable.my_notes);
backupHelpDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface backupHelpDialog, int witch) {
// Do Not Do Anything.
}
});
backupHelpDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
The NotesModel class:
package com.twitter.i_droidi.mynotesdonation;
public class NotesModel {
int id;
String title;
String body;
static NotesModel actualNote;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
The NotesDataSource class:
package com.twitter.i_droidi.mynotesdonation;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class NotesDataSource {
DB myDB;
SQLiteDatabase sql;
public static NotesModel note;
String[] getAllColumns = new String[]{DB.ID, DB.TITLE, DB.BODY};
public NotesDataSource(Context context) {
myDB = new DB(context);
}
public void open() {
try {
sql = myDB.getWritableDatabase();
} catch (Exception ex) {
Log.d("Error in your database!", ex.getMessage());
}
}
public void close() {
sql.close();
}
public void createNote(String title, String body) {
ContentValues note = new ContentValues();
note.put(myDB.TITLE, title);
note.put(myDB.BODY, body);
sql.insert(myDB.TABLE_NAME, null, note);
}
public NotesModel getNote(int id) {
note = new NotesModel();
Cursor cursor = sql.rawQuery("SELECT * FROM " + DB.TABLE_NAME + " WHERE " + DB.ID + " = ?", new String[]{id + ""});
if (cursor.getCount() > 0) {
cursor.moveToFirst();
note.setId(cursor.getInt(0));
note.setTitle(cursor.getString(1));
note.setBody(cursor.getString(2));
cursor.close();
}
return note;
}
public void updateNote(int id, String title, String body) {
ContentValues note = new ContentValues();
note.put(myDB.TITLE, title);
note.put(myDB.BODY, body);
sql.update(myDB.TABLE_NAME, note, myDB.ID + " = " + id, null);
}
public void deleteNote(Object id) {
sql.delete(myDB.TABLE_NAME, myDB.ID + " = " + id, null);
}
public List<NotesModel> getAllNotes() {
List<NotesModel> notesList = new ArrayList<NotesModel>();
Cursor cursor = sql.query(myDB.TABLE_NAME, getAllColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
NotesModel notes = new NotesModel();
notes.setId(cursor.getInt(0));
notes.setTitle(cursor.getString(1));
notes.setBody(cursor.getString(2));
notesList.add(notes);
cursor.moveToNext();
}
cursor.close();
return notesList;
}
}
The logcat:
09-06 01:53:10.263 24553-24553/com.twitter.i_droidi.mynotesdonation E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.twitter.i_droidi.mynotesdonation, PID: 24553
java.lang.NullPointerException: Attempt to read from field 'java.lang.String com.twitter.i_droidi.mynotesdonation.NotesModel.body' on a null object reference
at com.twitter.i_droidi.mynotesdonation.MainActivity.onContextItemSelected(MainActivity.java:144)
at android.app.Activity.onMenuItemSelected(Activity.java:2905)
at android.support.v4.app.FragmentActivity.onMenuItemSelected(FragmentActivity.java:325)
at android.support.v7.app.AppCompatActivity.onMenuItemSelected(AppCompatActivity.java:147)
at android.support.v7.internal.view.WindowCallbackWrapper.onMenuItemSelected(WindowCallbackWrapper.java:100)
at com.android.internal.policy.impl.PhoneWindow$DialogMenuCallback.onMenuItemSelected(PhoneWindow.java:4701)
at com.android.internal.view.menu.MenuBuilder.dispatchMenuItemSelected(MenuBuilder.java:761)
at com.android.internal.view.menu.MenuItemImpl.invoke(MenuItemImpl.java:152)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:904)
at com.android.internal.view.menu.MenuBuilder.performItemAction(MenuBuilder.java:894)
at com.android.internal.view.menu.MenuDialogHelper.onClick(MenuDialogHelper.java:167)
at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:1082)
at android.widget.AdapterView.performItemClick(AdapterView.java:305)
at android.widget.AbsListView.performItemClick(AbsListView.java:1146)
at android.widget.AbsListView$PerformClick.run(AbsListView.java:3053)
at android.widget.AbsListView$3.run(AbsListView.java:3860)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
It seems like you haven't initialised the actualNote field in the NotesModel class. Try saying
static NotesModel actualNote = new NotesModel();
Why you are making inner static object in this case, just use :
public class NotesModel {
int id;
String title;
public static String body;
...
}
and fetch like :
NotesModel.body
EDIT :
Use Getter method if you do not want static identifier:
NotesModel mModel = new NotesModel();
mModel.setBody(" String with your body ");
String shareBody = mModel.getBody(); // Getter method
In my note app for Android, if I press long on a note then chose "Delete" to delete the note, the note still exists in the list, then after I close the app then return to it, the note is gone!
Hint: I am uses the onContextItemSelected method to show the "Delete" option.
How I can delete the note from the list and from the database?!
The MainActivity class which contains the onContextItemSelected method:
package com.twitter.i_droidi.mynotes;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
public class MainActivity extends ActionBarActivity implements AdapterView.OnItemClickListener {
ListView lv;
NotesDataSource nDS;
List<NotesModel> notesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nDS = new NotesDataSource(this);
lv = (ListView) findViewById(R.id.lv);
nDS.open();
notesList = nDS.getAllNotes();
nDS.close();
String[] notes = new String[notesList.size()];
for (int i = 0; i < notesList.size(); i++) {
notes[i] = notesList.get(i).getTitle();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1,
android.R.id.text1, notes);
lv.setAdapter(adapter);
registerForContextMenu(lv);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent nView = new Intent(this, Second2.class);
nView.putExtra("id", notesList.get(position).getId());
nView.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(nView);
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_delete, menu);
super.onCreateContextMenu(menu, v, menuInfo);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
nDS.open();
nDS.deleteNote("id"); // Check...!!!
nDS.close();
Toast nDelete = Toast.makeText(this, R.string.deleted, Toast.LENGTH_LONG);
nDelete.show();
}
return super.onContextItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.mainMenuNewNote:
Intent nNote = new Intent(this, Second.class);
startActivity(nNote);
return true;
case R.id.mainMenuAbout:
AlertDialog.Builder aboutDialog = new AlertDialog.Builder(this);
aboutDialog.setTitle(getString(R.string.about_title));
aboutDialog.setMessage(R.string.about_body);
aboutDialog.setIcon(R.drawable.my_notes);
aboutDialog.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface aboutDialog, int witch) {
// Do Not Do Anything.
}
});
aboutDialog.show();
return true;
case R.id.mainMenuExit:
AlertDialog.Builder exDialog = new AlertDialog.Builder(this);
exDialog.setTitle(R.string.exit_title);
exDialog.setMessage(R.string.exit_body);
exDialog.setIcon(R.drawable.my_notes);
exDialog.setNegativeButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface exDialog, int which) {
finish();
}
});
exDialog.setPositiveButton(R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface exDialog, int which) {
// Do Not Do Anything.
}
});
exDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}
}
The DB class:
package com.twitter.i_droidi.mynotes;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DB extends SQLiteOpenHelper {
private static final String DB_NAME = "MyNotes";
private static final int DB_VERSION = 1;
public static final String TABLE_NAME = "MyNotes";
public static final String ID = "id";
public static final String TITLE = "title";
public static final String BODY = "body";
private static final String DB_CREATE = "create table " + TABLE_NAME + " (" + ID + " integer primary key autoincrement, " +
TITLE + " text not null, " + BODY + " text not null)";
public DB(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DB_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);
onCreate(db);
}
}
The NotesDataSource class:
package com.twitter.i_droidi.mynotes;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import java.util.ArrayList;
import java.util.List;
public class NotesDataSource {
DB myDB;
SQLiteDatabase sql;
String[] getAllColumns = new String[]{DB.ID, DB.TITLE, DB.BODY};
public NotesDataSource(Context context) {
myDB = new DB(context);
}
public void open() {
try {
sql = myDB.getWritableDatabase();
} catch (Exception ex) {
Log.d("Error in your database!", ex.getMessage());
}
}
public void close() {
sql.close();
}
public void createNote(String title, String body) {
ContentValues note = new ContentValues();
note.put(myDB.TITLE, title);
note.put(myDB.BODY, body);
sql.insert(myDB.TABLE_NAME, null, note);
}
public NotesModel getNote(int id) {
NotesModel note = new NotesModel();
Cursor cursor = sql.rawQuery("SELECT * FROM " + DB.TABLE_NAME + " WHERE " + DB.ID + " = ?", new String[]{id + ""});
if (cursor.getCount() > 0) {
cursor.moveToFirst();
note.setId(cursor.getInt(0));
note.setTitle(cursor.getString(1));
note.setBody(cursor.getString(2));
cursor.close();
}
return note;
}
public void updateNote(int id, String title, String body) {
ContentValues note = new ContentValues();
note.put(myDB.TITLE, title);
note.put(myDB.BODY, body);
sql.update(myDB.TABLE_NAME, note, myDB.ID + " = " + id, null);
}
public void deleteNote(Object id) {
sql.delete(myDB.TABLE_NAME, myDB.ID + " = " + id, null);
}
public List<NotesModel> getAllNotes() {
List<NotesModel> notesList = new ArrayList<NotesModel>();
StringBuffer selectQuery = new StringBuffer();
selectQuery.append("SELECT * FROM "+ myDB.TABLE_NAME +"");
Cursor cursor = sql.rawQuery(selectQuery.toString(), null);
if(cursor != null && cursor.moveToFirst()) {
do {
NotesModel notes = new NotesModel();
notes.setId(cursor.getInt(0));
notes.setTitle(cursor.getString(1));
notes.setBody(cursor.getString(2));
notesList.add(notes);
} while (cursor.moveToNext());
}
cursor.close();
return notesList;
}
}
After removing item from database
Remove the deleted item from
String[] notes
by using
notes.remove(position);
nd call
adapter.notifyDataSetChanged();