My program was working fine until I decide to modify my DBHelper class, after a few changes every time I modify my program shows me this Log:
E/KernelCpuSpeedReader: Failed to read cpu-freq
java.io.FileNotFoundException: /sys/devices/system/cpu/cpu0/cpufreq/stats/time_in_state: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:452)
at java.io.FileInputStream.<init>(FileInputStream.java:76)
at java.io.FileInputStream.<init>(FileInputStream.java:103)
at java.io.FileReader.<init>(FileReader.java:66)
at com.android.internal.os.KernelCpuSpeedReader.readDelta(KernelCpuSpeedReader.java:49)
at com.android.internal.os.BatteryStatsImpl.updateCpuTimeLocked(BatteryStatsImpl.java:8002)
at com.android.internal.os.BatteryStatsImpl$MyHandler.handleMessage(BatteryStatsImpl.java:155)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.os.HandlerThread.run(HandlerThread.java:61)
at com.android.server.ServiceThread.run(ServiceThread.java:46)
Caused by: android.system.ErrnoException: open failed: ENOENT (No such file or directory)
at libcore.io.Posix.open(Native Method)
at libcore.io.BlockGuardOs.open(BlockGuardOs.java:186)
at libcore.io.IoBridge.open(IoBridge.java:438)
at java.io.FileInputStream.<init>(FileInputStream.java:76)
at java.io.FileInputStream.<init>(FileInputStream.java:103)
at java.io.FileReader.<init>(FileReader.java:66)
at com.android.internal.os.KernelCpuSpeedReader.readDelta(KernelCpuSpeedReader.java:49)
at com.android.internal.os.BatteryStatsImpl.updateCpuTimeLocked(BatteryStatsImpl.java:8002)
at com.android.internal.os.BatteryStatsImpl$MyHandler.handleMessage(BatteryStatsImpl.java:155)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.os.HandlerThread.run(HandlerThread.java:61)
at com.android.server.ServiceThread.run(ServiceThread.java:46)
04-24 05:36:35.369 1299-1313/? E/KernelUidCpuTimeReader: Failed to read uid_cputime
java.io.FileNotFoundException: /proc/uid_cputime/show_uid_stat: open failed: ENOENT (No such file or directory)
at libcore.io.IoBridge.open(IoBridge.java:452)
at java.io.FileInputStream.<init>(FileInputStream.java:76)
at java.io.FileInputStream.<init>(FileInputStream.java:103)
at java.io.FileReader.<init>(FileReader.java:66)
I don't want to assume or make more changes, this is my final stage of my project please help here is my
DB Helper:
public class DBHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "MyDBName.db";
public static final String VALUES_TABLE_NAME = "values";
public static final String VALUES_COLUMN_ID = "id";
public static final String VALUES_COLUMN_CONDUCTIVITY = "conductivity";
public static final String VALUES_COLUMN_MOISTURE = "moisture";
public static final String VALUES_COLUMN_OXYGEN = "oxygen";
public static final String VALUES_COLUMN_PH = "ph";
private HashMap hp;
public DBHelper(Context context)
{
super(context, DATABASE_NAME , null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"create table values " +
"(id integer primary key, conductivity text,ph text,oxygen text, moisture text)"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS values");
onCreate(db);
}
public boolean insertContact (String conductivity, String ph, String oxygen, String moisture)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("conductivity", conductivity);
contentValues.put("ph", ph);
contentValues.put("oxygen", oxygen);
contentValues.put("moisture", moisture);
db.insert("values", null, contentValues);
return true;
}
public Cursor getData(int id){
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from values where id="+id+"", null );
return res;
}
public int numberOfRows(){
SQLiteDatabase db = this.getReadableDatabase();
int numRows = (int) DatabaseUtils.queryNumEntries(db, VALUES_TABLE_NAME);
return numRows;
}
public boolean updateContact (Integer id, String conductivity, String ph, String oxygen, String moisture)
{
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put("conductivity", conductivity);
contentValues.put("phone", ph);
contentValues.put("oxygen", oxygen);
contentValues.put("moisture", moisture);
db.update("values", contentValues, "id = ? ", new String[] { Integer.toString(id) } );
return true;
}
public Integer deleteContact (Integer id)
{
SQLiteDatabase db = this.getWritableDatabase();
return db.delete("values",
"id = ? ",
new String[] { Integer.toString(id) });
}
public ArrayList<String> getAllCotacts()
{
ArrayList<String> array_list = new ArrayList<String>();
//hp = new HashMap();
SQLiteDatabase db = this.getReadableDatabase();
Cursor res = db.rawQuery( "select * from values", null );
res.moveToFirst();
while(res.isAfterLast() == false){
array_list.add(res.getString(res.getColumnIndex(VALUES_COLUMN_CONDUCTIVITY)));
res.moveToNext();
}
return array_list;
}
}
Main Activity:
package com.example.carlos.application1;
import android.view.ContextMenu;
import android.view.MenuInflater;
import android.widget.Toast;
import android.widget.Button;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.MenuItem;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.DialogInterface;
public class MainActivity extends ActionBarActivity {
public final static String EXTRA_MESSAGE = "MESSAGE";
private ListView obj;
DBHelper mydb;
int status = 0;
Button hp_1, HP2, fo, previous, next, MZ, Control, show, home;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button home = (Button) findViewById(R.id.home);
registerForContextMenu(home);
mydb = new DBHelper(this);
ArrayList array_list = mydb.getAllCotacts();
ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, array_list);
Button hp_1 = (Button) findViewById(R.id.hp_1);
obj = (ListView) findViewById(R.id.listView1);
obj.setAdapter(arrayAdapter);
obj.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
int id_To_Search = arg2 + 1;
Bundle dataBundle = new Bundle();
dataBundle.putInt("id", id_To_Search);
Intent intent = new Intent(getApplicationContext(), DisplayValues.class);
intent.putExtras(dataBundle);
startActivity(intent);
}
});
hp_1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
status = 1;
Bundle bundle = new Bundle();
bundle.putInt("status", status);
Intent intent = new Intent(MainActivity.this, DisplayValues.class);
intent.putExtras(bundle);
startActivity(intent);/*Intent intent = new Intent(first.this, second.class);
Bundle bundle = new Bundle();
bundle.putInt("index", index);
intent.putExtras(bundle);
startActivity(intent); */
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item){
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.item1:Bundle dataBundle = new Bundle();
dataBundle.putInt("id", 0);
Intent intent = new Intent(getApplicationContext(),DisplayValues.class);
intent.putExtras(dataBundle);
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public boolean onKeyDown(int keycode, KeyEvent event) {
if (keycode == KeyEvent.KEYCODE_BACK) {
moveTaskToBack(true);
}
return super.onKeyDown(keycode, event);
}
//dfsdfasdfasdfasd
}
And Display Value class, where I get the entries to my DB:
package com.example.carlos.application1;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class DisplayValues extends Activity {
int from_Where_I_Am_Coming = 0;
private DBHelper mydb ;
TextView conductivity ;
TextView ph;
TextView moisture;
TextView oxygen;
int id_To_Update = 0;
public void backButtonHandler() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
DisplayValues.this);
// Setting Dialog Title
alertDialog.setTitle("Leave the page?");
// Setting Dialog Message
alertDialog.setMessage("Are you sure you want to leave without saving the Entries?");
// Setting Icon to Dialog
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to invoke NO event
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
#Override
public void onBackPressed() {
backButtonHandler();
return;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
conductivity = (TextView) findViewById(R.id.editTextConductivity);
oxygen= (TextView) findViewById(R.id.editTextOxygen);
moisture = (TextView) findViewById(R.id.editTextMoisture);
ph = (TextView) findViewById(R.id.editTextpH);
mydb = new DBHelper(this);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
//means this is the view part not the add contact part.
Cursor rs = mydb.getData(Value);
id_To_Update = Value;
rs.moveToFirst();
String condc = rs.getString(rs.getColumnIndex(DBHelper.VALUES_COLUMN_CONDUCTIVITY));
String mois = rs.getString(rs.getColumnIndex(DBHelper.VALUES_COLUMN_MOISTURE));
String oxy = rs.getString(rs.getColumnIndex(DBHelper.VALUES_COLUMN_OXYGEN));
String phe = rs.getString(rs.getColumnIndex(DBHelper.VALUES_COLUMN_PH));
/* public static final String DATABASE_NAME = "MyDBName.db";
public static final String VALUES_TABLE_NAME = "values";
public static final String VALUES_COLUMN_CONDUCTIVITY = "conductivity";
public static final String VALUES_COLUMN_MOISTURE = "moisture";
public static final String VALUES_COLUMN_OXYGEN = "oxygen";
public static final String VALUES_COLUMN_PH = "ph";*/
if (!rs.isClosed())
{
rs.close();
}
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.INVISIBLE);
conductivity.setText((CharSequence)condc);
conductivity.setFocusable(false);
conductivity.setClickable(false);
moisture.setText((CharSequence)mois);
moisture.setFocusable(false);
moisture.setClickable(false);
ph.setText((CharSequence)phe);
ph.setFocusable(false);
ph.setClickable(false);
oxygen.setText((CharSequence)oxy);
oxygen.setFocusable(false);
oxygen.setClickable(false);
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
getMenuInflater().inflate(R.menu.display_contact, menu);
}
else{
getMenuInflater().inflate(R.menu.menu_main, menu);
}
}
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch(item.getItemId())
{
case R.id.Edit_Contact:
Button b = (Button)findViewById(R.id.button1);
b.setVisibility(View.VISIBLE);
conductivity.setEnabled(true);
conductivity.setFocusableInTouchMode(true);
conductivity.setClickable(true);
ph.setEnabled(true);
ph.setFocusableInTouchMode(true);
ph.setClickable(true);
moisture.setEnabled(true);
moisture.setFocusableInTouchMode(true);
moisture.setClickable(true);
oxygen.setEnabled(true);
oxygen.setFocusableInTouchMode(true);
oxygen.setClickable(true);
return true;
case R.id.Delete_Contact:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.deleteContact)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
mydb.deleteContact(id_To_Update);
Toast.makeText(getApplicationContext(), "Deleted Successfully", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
})
.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog d = builder.create();
d.setTitle("Are you sure");
d.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void run(View view)
{
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
int Value = extras.getInt("id");
if(Value>0){
if(mydb.updateContact(id_To_Update,conductivity.getText().toString(), ph.getText().toString(), oxygen.getText().toString(), moisture.getText().toString())){
Toast.makeText(getApplicationContext(), "Updated", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
else{
Toast.makeText(getApplicationContext(), "not Updated", Toast.LENGTH_SHORT).show();
}
}
else{
if(mydb.insertContact(conductivity.getText().toString(), ph.getText().toString(), oxygen.getText().toString(), moisture.getText().toString())){
Toast.makeText(getApplicationContext(), "done", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "not done", Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent);
}
}
}
}
Related
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();
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
I am trying to show all my data from my database into the listview
Code to create database:
DataHander.java
package com.example.testingforstack;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
public class DataHandler {
public static final String NAME = "name";
public static final String EMAIL = "email";
public static final String TABLE_NAME = "mytable";
public static final String DATA_BASE_NAME = "mydatabase";
public static final int DATABASE_VERSION = 1;
public static final String TABLE_CREATE = "create table mytable (name text not null, email text not null);";
DataBaseHelper dbhelper;
Context ctx;
SQLiteDatabase db;
public DataHandler(Context ctx){
this.ctx = ctx;
dbhelper = new DataBaseHelper(ctx);
}
public static class DataBaseHelper extends SQLiteOpenHelper{
public DataBaseHelper(Context ctx) {
super(ctx, DATA_BASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db){
try{
db.execSQL(TABLE_CREATE);
}catch (SQLException e){
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
//db.execSQL("DROP TABLE IF EXISTS mytable");
onCreate(db);
}
}
public DataHandler open(){
db = dbhelper.getReadableDatabase();
return this;
}
public void close(){
dbhelper.close();
}
public long insertData(String name, String email){
ContentValues content = new ContentValues();
content.put(NAME, name);
content.put(EMAIL, email);
return db.insertOrThrow(TABLE_NAME, null, content);
}
public Cursor returnData(){
return db.query(TABLE_NAME, new String[] {NAME, EMAIL}, null, null, null, null, null);
}
}
mainActivity.java
package com.example.testingforstack;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity {
Button save, load;
EditText name, email;
DataHandler handler;
String getName, getEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save = (Button) findViewById(R.id.save);
load = (Button) findViewById(R.id.load);
name = (EditText) findViewById(R.id.name);
email = (EditText) findViewById(R.id.email);
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String getName = name.getText().toString();
String getEmail = email.getText().toString();
handler = new DataHandler(getBaseContext());
handler.open();
long id = handler.insertData(getName, getEmail);
insertSuccess();
//Toast.makeText(getBaseContext(), "Data inserted", Toast.LENGTH_LONG).show();
handler.close();
}
});
load.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getName = "";
getEmail = "";
handler = new DataHandler(getBaseContext());
handler.open();
Cursor C = handler.returnData();
if(C.moveToFirst()){
do{
getName = C.getString(0);
getEmail = C.getString(1);
}while(C.moveToNext());
}
handler.close();
loadSuccess();
//Toast.makeText(getBaseContext(), "Name: "+getName+", Email: "+getEmail, Toast.LENGTH_LONG).show();
}
});
}
public void insertSuccess()
{
AlertDialog.Builder insertData = new AlertDialog.Builder(this);
insertData.setTitle("Info");
insertData.setMessage("Data Inserted");
insertData.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int value) {
// TODO Auto-generated method stub
arg0.dismiss();
}
});
insertData.show();
}
public void loadSuccess()
{
AlertDialog.Builder loadData = new AlertDialog.Builder(this);
loadData.setTitle("Info");
loadData.setMessage("Name: "+getName+" & your email: "+getEmail);
loadData.setNegativeButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int value) {
// TODO Auto-generated method stub
arg0.dismiss();
}
});
loadData.show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
I have two button save and load. I have successfully implemented the save button to save the user name and email. However, I don't really know to load the data into the listview. How to do that?
In listview you can use different types of adapters. For database, most appropriate is to use cursorAdapter where you tell which cursor to use. You can also manually walk through elements in DB and save them in some other object in array and then you can have arrayAddapter in which you pass your array of object. In each case you must set binder or override method onCreateView where you tell which parameter go in which child.
You can look this http://www.mysamplecode.com/2012/07/android-listview-cursoradapter-sqlite.html example for more information.
I would like to implement a database which consists of 2 tables, number and receivernumber. In fact, I have 2 xml files, one using number table, another using receivernumber. However, the code below only allows the first table to be used for both of the xmls.
Previously, I have tried implementing 2 different sets of class files, as stated below. But it crashes the entire app instead. So I tried changing to using the same class file with the receivernumber table being number2 instead. Now, both of the activity/xml file uses the first database but not the second. Please advice. Thanks in advance.
Note: there are no error logs available as it is working. Just that the table used for both activities are the same, but it's supposed to be different.
Set_numbers_to_forward.java
import java.util.ArrayList;
import java.util.List;
import com.example.awkwardpanda_redirectcall.DBAdapter;
import com.example.awkwardpanda_redirectcall.CallAdapter;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
public class Set_numbers_to_forward extends Activity {
Context mContext;
ArrayAdapter<String> adapter;
List<String> adapterData;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_numbers_to_forward);
mContext = this;
ListView list = (ListView) findViewById(R.id.number_list);
adapterData = new ArrayList<String>();
DBAdapter db = new DBAdapter(this);
// ---get all contacts---
db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst()) {
do {
adapterData.add(c.getString(1));
} while (c.moveToNext());
}
db.close();
adapter = new CallAdapter(this,
R.layout.set_numbers_to_forward_editable, adapterData);
list.setAdapter(adapter);
} // end onCreate
public void onCreate2(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.set_number_to_receive);
mContext = this;
ListView list = (ListView) findViewById(R.id.receiver_number);
adapterData = new ArrayList<String>();
DBAdapter db = new DBAdapter(this);
// ---get all contacts---
db.open();
Cursor c = db.getAllContacts();
if (c.moveToFirst()) {
do {
adapterData.add(c.getString(1));
} while (c.moveToNext());
}
db.close();
adapter = new CallAdapter(this,
R.layout.set_number_to_receive_editable, adapterData);
list.setAdapter(adapter);
} // end onCreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.addbtn, menu);
return true;
}
public boolean onCreateOptionsMenu2(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.addbtn2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("New Phone Number");
builder.setMessage("Enter Phone Number :");
final EditText input = new EditText(Set_numbers_to_forward.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
DBAdapter db = new DBAdapter(mContext);
db.open();
db.insertContact(input.getText().toString());
db.close();
adapterData.add(input.getText().toString());
adapter.notifyDataSetChanged();
}
});
builder.create().show();
return true;
}
public boolean onOptionsItemSelected2(MenuItem item) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("New Phone Number");
builder.setMessage("Enter Phone Number :");
final EditText input = new EditText(Set_numbers_to_forward.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
DBAdapter db = new DBAdapter(mContext);
db.open();
db.insertContact2(input.getText().toString());
db.close();
adapterData.add(input.getText().toString());
adapter.notifyDataSetChanged();
}
});
builder.create().show();
return true;
}
}
DBAdapter.java
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBAdapter {
public static final String KEY_ROWID = "hpnumberID";
public static final String KEY_NAME = "hpNumber";
private static final String TAG = "DBAdapter";
public static final String KEY_ROWID2 = "hpnumberID";
public static final String KEY_NAME2 = "hpNumber";
private static final String DATABASE_NAME = "HPnumberDB";
private static final String DATABASE_TABLE = "number";
private static final String DATABASE_TABLE2 = "receivernumber";
private static final int DATABASE_VERSION = 2;
private static final String DATABASE_CREATE =
"create table number (hpnumberID integer primary key autoincrement, "
+ "hpNumber text not null);";
private static final String DATABASE_CREATE2 =
"create table receivernumber (hpnumberID integer primary key autoincrement, "
+ "hpNumber text not null);";
private final Context context;
private DatabaseHelper DBHelper;
private SQLiteDatabase db;
public DBAdapter(Context ctx)
{
this.context = ctx;
DBHelper = new DatabaseHelper(context);
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
try {
db.execSQL(DATABASE_CREATE);
db.execSQL(DATABASE_CREATE2);
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE2);
onCreate(db);
}
} // end DatabaseHelper class
//---opens the database---
public DBAdapter open() throws SQLException
{
db = DBHelper.getWritableDatabase();
return this;
}
//---closes the database---
public void close()
{
DBHelper.close();
}
//---insert a contact into the database---
public long insertContact(String hpNumber)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME, hpNumber);
return db.insert(DATABASE_TABLE, null, initialValues);
}
public long insertContact2(String hpNumber)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_NAME2, hpNumber);
return db.insert(DATABASE_TABLE2, null, initialValues);
}
//---deletes a particular contact---
public boolean deleteContact(long hpnumberID)
{
return db.delete(DATABASE_TABLE, KEY_ROWID + "=" + hpnumberID, null) > 0;
}
public boolean deleteContact2(long hpnumberID)
{
return db.delete(DATABASE_TABLE2, KEY_ROWID2 + "=" + hpnumberID, null) > 0;
}
//---retrieves all the contacts---
public Cursor getAllContacts()
{
return db.query(DATABASE_TABLE, new String[] {KEY_ROWID, KEY_NAME}, null, null,
null, null, null);
}
public Cursor getAllContacts2()
{
return db.query(DATABASE_TABLE2, new String[] {KEY_ROWID2, KEY_NAME2}, null, null,
null, null, null);
}
//---retrieves a particular contact---
public Cursor getContact(long hpnumberID) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE, new String[] {KEY_ROWID,
KEY_NAME}, KEY_ROWID + "=" + hpnumberID, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public Cursor getContact2(long hpnumberID) throws SQLException
{
Cursor mCursor =
db.query(true, DATABASE_TABLE2, new String[] {KEY_ROWID2,
KEY_NAME2}, KEY_ROWID2 + "=" + hpnumberID, null,
null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
//---updates a contact---
public boolean updateContact(long hpnumberID, String hpNumber)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME, hpNumber);
return db.update(DATABASE_TABLE, args, KEY_ROWID + "=" + hpnumberID, null) > 0;
}
public boolean updateContact2(long hpnumberID, String hpNumber)
{
ContentValues args = new ContentValues();
args.put(KEY_NAME2, hpNumber);
return db.update(DATABASE_TABLE2, args, KEY_ROWID2 + "=" + hpnumberID, null) > 0;
}
} // end DBAdapter class
CallAdapter.java
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class CallAdapter extends ArrayAdapter<String> {
Context mContext;
List<String> list;
public CallAdapter(Context context, int resource, List<String> list) {
super(context, resource, list);
// TODO Auto-generated constructor stub
mContext = context;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater
.inflate(R.layout.set_numbers_to_forward_editable, parent,
false);
TextView hpNumber = (TextView) rowView.findViewById(R.id.hp_Number);
ImageView discardButton = (ImageView) rowView
.findViewById(R.id.number_discard_button);
ImageView editButton = (ImageView) rowView
.findViewById(R.id.number_edit_button);
hpNumber.setText(list.get(position));
discardButton.setTag(position);
editButton.setTag(position);
editButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String position = v.getTag().toString();
createDialog(position, list);
}
});
discardButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
createDeleteDialog(v.getTag().toString(), list);
}
});
return rowView;
}
public View getView2(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater
.inflate(R.layout.set_number_to_receive_editable, parent,
false);
TextView hpNumber = (TextView) rowView.findViewById(R.id.hp_Number);
ImageView discardButton = (ImageView) rowView
.findViewById(R.id.number_discard_button);
ImageView editButton = (ImageView) rowView
.findViewById(R.id.number_edit_button);
hpNumber.setText(list.get(position));
discardButton.setTag(position);
editButton.setTag(position);
editButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String position = v.getTag().toString();
createDialog(position, list);
}
});
discardButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
createDeleteDialog(v.getTag().toString(), list);
}
});
return rowView;
}
public void createDialog(String position, List<String> list) {
final long hpnumberID = Long.parseLong(position) + 1;
final int viewPosition = Integer.parseInt(position);
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setTitle("Edit");
final EditText input = new EditText(mContext);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
input.setText(list.get(viewPosition));
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
DBAdapter db = new DBAdapter(mContext);
db.open();
db.updateContact(hpnumberID, input.getText().toString());
db.close();
((Set_numbers_to_forward)
mContext).adapterData.remove(viewPosition);
((Set_numbers_to_forward)
mContext).adapterData.add(viewPosition, input
.getText().toString());
((Set_numbers_to_forward)
mContext).adapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
builder.create().show();
}
public void createDeleteDialog(String position, List<String> list) {
final int viewPosition = Integer.parseInt(position);
final long hpnumberID = Long.parseLong(position) + 1;
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Deleting \"" + list.get(viewPosition) + "\"");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
DBAdapter db = new DBAdapter(mContext);
db.open();
db.deleteContact(hpnumberID);
db.close();
((Set_numbers_to_forward)
mContext).adapterData.remove(viewPosition);
((Set_numbers_to_forward)
mContext).adapter.notifyDataSetChanged();
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
builder.create().show();
}
}
You don't really have a question in your... question. What I can tell you is that if you setup and use your own ContentProvider it takes care of a lot of what you are doing and makes it simpler. You can read the tutorial on the android documentation here http://developer.android.com/guide/topics/providers/content-provider-creating.html
If you start with that feel free to leave a comment on this answer if you run into any problems with the tutorial and I might be able to help. As it is you are 'reinventing the wheel' and making things difficult for yourself
edit
I've just realised from Tobor's comment there's a content provider buried in there as well - I still recommend following the tutorial above (or finding your own) to clear up the code
Why do you need doubles??
You can't use ArrayAdapter and Activity like this. Also, you don't need two xml files for this. Create an xml layout that contains two views inside and set this view as content view of your activity.
In overrided getView method in your adapter, update these views.
onCreate2 and getView2 methods are not called from anywhere and shouldn't be. In an activity, there can be only one content view.
Please see ArrayAdapter and creating Android Activity and SQLite DBAdapter examples first before starting new development.