I am sending a data via JSON to my apps,it displays in my ListView, without internet is not working,so i want to make an database to store the JSON parsing data alone.I tried to create a database for JSON storing but its not properly done. How can I solve this problem?
Myadapterclass.java
public class GinfyDbAdapter {
private static final String DATABASE_NAME = "ginfy.db";
private static final String DATABASE_TABLE_PROJ = "prayers";
private static final int DATABASE_VERSION = 2;
public static final String CATEGORY_COLUMN_ID = "id";
public static final String CATEGORY_COLUMN_TITLE = "title";
public static final String CATEGORY_COLUMN_CONTENT = "content";
public static final String CATEGORY_COLUMN_COUNT = "count";
private static final String TAG = "ProjectDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
public GinfyDbAdapter(MainActivity mainActivity) {
// TODO Auto-generated constructor stub
}
public GinfyDbAdapter GinfyDbAdapter(Context context){
mDbHelper = new DatabaseHelper(context);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void saveCategoryRecord(String id, String title, String content, String count) {
ContentValues contentValues = new ContentValues();
contentValues.put(CATEGORY_COLUMN_ID, id);
contentValues.put(CATEGORY_COLUMN_TITLE, title);
contentValues.put(CATEGORY_COLUMN_CONTENT, content);
contentValues.put(CATEGORY_COLUMN_COUNT, count);
mDb.insert(DATABASE_NAME, null, contentValues);
}
public Cursor getTimeRecordList() {
return mDb.rawQuery("select * from " + DATABASE_NAME, null);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private static final String DATABASE_CREATE_PROJ =
"create table " + DATABASE_TABLE_PROJ + " ("
+ CATEGORY_COLUMN_ID + " integer primary key autoincrement, "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer primary key autoincrement );" ;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE_PROJ + "( "
+ CATEGORY_COLUMN_ID + " INTEGER PRIMARY KEY, "
+ CATEGORY_COLUMN_TITLE + " TEXT, " + CATEGORY_COLUMN_CONTENT + " TEXT, " + CATEGORY_COLUMN_COUNT + " INTEGER PRIMARY KEY )" );
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_NAME);
onCreate(db);
}
}
}
This is my mainactivity which contains listview of data
public class MainActivity extends Activity implements FetchDataListener,OnClickListener{
private static final int ACTIVITY_CREATE=0;
private static final String TAG_CATEGORY = "post";
private static final String CATEGORY_COLUMN_ID = "id";
private static final String CATEGORY_COLUMN_TITLE = "title";
private static final String CATEGORY_COLUMN_CONTENT = "content";
private static final String CATEGORY_COLUMN_COUNT = "count";
private static final int Application = 0;
private ProgressDialog dialog;
ListView lv;
ListView lv1;
private List<Application> items;
private Button btnGetSelected;
private Button praycount;
public int pct;
private String stringVal;
private TextView value;
private int prayers;
private int prayerid;
EditText myFilter;
ApplicationAdapter adapter;
private GinfyDbAdapter mDbHelper;
JSONArray contacts = null;
private SimpleCursorAdapter dataAdapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mDbHelper=new GinfyDbAdapter(MainActivity.this);
lv1 =(ListView)findViewById(R.id.list);
lv =(ListView)findViewById(R.id.list);
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
// Creating JSON Parser instance
JSONParser jParser = new JSONParser();
String url = "http://www.ginfy.com/api/v1/posts.json";
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
contacts = json.getJSONArray(TAG_CATEGORY);
// looping through All Contacts
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(CATEGORY_COLUMN_ID);
String title = c.getString(CATEGORY_COLUMN_TITLE);
String content = c.getString(CATEGORY_COLUMN_CONTENT);
String count = c.getString(CATEGORY_COLUMN_COUNT);
mDbHelper.saveCategoryRecord(id,title,content,count);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(CATEGORY_COLUMN_ID, id);
map.put(CATEGORY_COLUMN_TITLE, title);
map.put(CATEGORY_COLUMN_CONTENT, content);
map.put(CATEGORY_COLUMN_COUNT, count);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
myFilter = (EditText) findViewById(R.id.myFilter);
initView();
}
private void initView(){
// show progress dialog
dialog = ProgressDialog.show(this, "", "Loading...");
String url = "http://www.ginfy.com/api/v1/posts.json";
FetchDataTask task = new FetchDataTask(this);
task.execute(url);
}
I changed my code like this it shwoing error in JSONparser line
Related
I think i ran out from ideas about how to do this. I am building and TODO app with register and login feature. Once a user is logged, can create new todos task in SQLite(for now), later i want to delete and rename todos as well.
This is my DB class with SQliteHelper.
public class DatabaseHelper extends SQLiteOpenHelper {
// Database Version
private static final int DATABASE_VERSION = 1;
// Database Name
private static final String DATABASE_NAME = "UserManager.db";
// User table name
private static final String TABLE_USER = "user";
// User Table Columns names
private static final String COLUMN_USER_ID = "user_id";
private static final String COLUMN_USER_NAME = "user_name";
private static final String COLUMN_USER_EMAIL = "user_email";
private static final String COLUMN_USER_PASSWORD = "user_password";
//Table mToDo task name
private final static String mTODO = "Todos";
//Todos table columns names
private final static String TASK_ID = "task_Id"; //autoincrement
private final static String user_Id = "userId";
private final static String TITLE = "title";
private final static String CONTENT = "content";
// create table sql query
private String CREATE_USER_TABLE = "CREATE TABLE " + TABLE_USER + "("
+ COLUMN_USER_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," +
COLUMN_USER_NAME + " TEXT,"
+ COLUMN_USER_EMAIL + " TEXT," + COLUMN_USER_PASSWORD + " TEXT" +
")";
private String CREATE_mTODO_TABLE = "CREATE TABLE " + mTODO + "("
+ TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + user_Id + " TEXT NOT NULL,"
+ TITLE + " TEXT," + CONTENT + " TEXT" + ")";
// drop table sql query
private String DROP_USER_TABLE = "DROP TABLE IF EXISTS " + TABLE_USER;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// this.ctx = context;
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_USER_TABLE);
db.execSQL(CREATE_mTODO_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//Drop User Table if exist
db.execSQL(DROP_USER_TABLE);
// Create tables again
onCreate(db);
}
Adding new Task to second table
public void add(ToDo todoTask) {
SQLiteDatabase db = this.getWritableDatabase();
// SharedPreferences sp = PreferenceManager
// .getDefaultSharedPreferences(ctx);
// String d = sp.toString();
ContentValues values = new ContentValues();
values.put(TITLE, todoTask.getTitle());
values.put(CONTENT, todoTask.getContent());
// values.put(user_Id,todoTask.getUserID(d));
// Inserting Row
db.insert(mTODO, null, values);
db.close();
}
ToDo.java
public class ToDo {
private int id;
private String userID;
private String title;
private String content;
public ToDo(String content, int id, String title, String userID) {
this.content = content;
this.id = id;
this.title = title;
this.userID = userID;
}
public ToDo(String content, String title, String userID) {
this.content = content;
this.title = title;
this.userID = userID;
}
public ToDo() {
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public int getId(String name) {
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 getUserID(String userID) {
return userID;
}
public void setUserID(String userID) {
this.userID = userID;
}
}
Add activity class with inputs and add method
public class addTask extends AppCompatActivity {
private EditText titleUser;
private EditText contentDesc;
private DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_task);
Button btnAdd = (Button) findViewById(R.id.addToDo);
titleUser = (EditText) findViewById(R.id.titleID);
contentDesc = (EditText) findViewById(R.id.contentDescId);
db = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AddItem();
}
});
}
private void AddItem() {
ToDo todo = new ToDo();
todo.setTitle(titleUser.getText().toString().trim());
todo.setContent(contentDesc.getText().toString().trim());
db.add(todo);
finish();
}
The current user that is logged, i am putting that user id to Shared preferences
In my second Table i have something like this
task_Id user_id title content
1 null Eat go to Mc
user_id is null here, and i don't know why
i want something like this
task_Id user_id title content
1 2 Eat go to Mc
user_id- should be which user id make the todo
Supposing that you already know how to store and get the userid from the shared preferences.
In your addTask activity, add:
private String userId;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
userId = sharedPreference.getString("USER_ID",null);
...
}
in the addItem() add:
private void AddItem() {
...
todo.setUserId(userId);
...
}
in the DB add() use this:
public void add(ToDo todoTask) {
...
values.put(USERID, todoTask.getUserId());
...
}
OR:
Another approach is to get the value directly from the DB class if you are sure that you will never insert task for other users.
public void add(ToDo todoTask) {
SQLiteDatabase db = this.getWritableDatabase();
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(ctx);
String d = sp.toString();
ContentValues values = new ContentValues();
values.put(TITLE, todoTask.getTitle());
values.put(CONTENT, todoTask.getContent());
values.put(user_Id,todoTask.getUserID(d));
db.insert(mTODO, null, values);
db.close();
}
and in the constructor save the context for further use.
private Context ctx;
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.ctx = context;
}
You are creating ToDo Table using user_id. while static String refrenced is userid: hence in database when entered it goes null by default
//Table mToDo task name
private final static String mTODO = "Todos";
//Todos table columns names
private final static String TASK_ID = "task_Id";
private final static String user_Id = "userId"; //<----Wrong Here
private final static String TITLE = "title";
private final static String CONTENT = "content";
private String CREATE_mTODO_TABLE = "CREATE TABLE " + mTODO + "("
+ TASK_ID + " INTEGER PRIMARY KEY AUTOINCREMENT," + user_Id + " TEXT NOT NULL,"
+ TITLE + " TEXT," + CONTENT + " TEXT" + ")";
Also here is something more for you, Simply you must supply the User Id value to the Field. Below are Some Examples How to do So
private static final String TAG = "DB_HANDLER";
private static final int DATABASE_VERSION = 15;
private static final String DATABASE_NAME = "ElmexContactsManager.db";
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
private static final String TABLE_BIZ_SEGMENT = "BizSegment";
/*01*/private static final String KEY_LOCAL_BIZ_SEGMENT_ID = "LocalBizSegmentId";
/*02*/private static final String KEY_BIZ_SEGMENT_ID = "BizSegmentId";
/*03*/private static final String KEY_BIZ_SEGMENT = "BizSegment";
/*04*/private static final String KEY_ADDED_ON = "AddedOn";
/*05*/private static final String KEY_UPDATED_ON = "UpdatedOn";
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
String CREATE_TABLE_BIZ_SEGMENT = "CREATE TABLE " + TABLE_BIZ_SEGMENT + "("
/*01*/ + KEY_LOCAL_BIZ_SEGMENT_ID + " INTEGER PRIMARY KEY AUTOINCREMENT,"
/*02*/ + KEY_BIZ_SEGMENT_ID + " INTEGER,"
/*03*/ + KEY_BIZ_SEGMENT + " TEXT,"
/*04*/ + KEY_ADDED_ON + " TEXT,"
/*05*/ + KEY_UPDATED_ON + " TEXT"
+ ")";
public ContactDatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
//3rd argument to be passed is CursorFactory instance
}
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) { try {
sqLiteDatabase.execSQL(CREATE_TABLE_BIZ_SEGMENT);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_TYPE);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_SOURCE);
sqLiteDatabase.execSQL(CREATE_TABLE_CONT_INDUSTRY);
sqLiteDatabase.execSQL(CREATE_TABLE_MARKETING_REGION);
sqLiteDatabase.execSQL(CREATE_TABLE_MARKETING_REGION_BLOCK);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_MASTER);
sqLiteDatabase.execSQL(CREATE_TABLE_CONTACT_DET);
} catch (SQLException e) {
e.printStackTrace();
}
Log.d(TAG, "Table Craeted ");
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1) {
// Drop older table if existed
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_BIZ_SEGMENT);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_TYPE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_SOURCE);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONT_INDUSTRY);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_MARKETING_REGION);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_MARKETING_REGION_BLOCK);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_MASTER);
sqLiteDatabase.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACT_DET);
// Create tables again
onCreate(sqLiteDatabase);
Log.d(TAG, "Table Udgraded to Version :" + i1);
}
/*-------------------------------------------BIZ_SEGMENT----------------------------------------*/
public void addBizSegment(BizSegment bizSegment) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
ContentValues values = new ContentValues();
values.put(KEY_BIZ_SEGMENT_ID, bizSegment.getBizSegmentId());
values.put(KEY_BIZ_SEGMENT, bizSegment.getBizSegment());
values.put(KEY_ADDED_ON, df.format(bizSegment.getAddedOn()));
values.put(KEY_UPDATED_ON, df.format(bizSegment.getUpdatedOn()));
// Inserting Row
sqLiteDatabase.insert(TABLE_BIZ_SEGMENT, null, values);
//2nd argument is String containing nullColumnHack
sqLiteDatabase.close(); // Closing database connection
}
public void updateBizSegment(BizSegment bizSegment) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
ContentValues values = new ContentValues();
//values.put(KEY_BIZ_SEGMENT_ID, bizSegment.getBizSegmentId());
values.put(KEY_BIZ_SEGMENT, bizSegment.getBizSegment());
values.put(KEY_ADDED_ON, df.format(bizSegment.getAddedOn()));
values.put(KEY_UPDATED_ON, df.format(bizSegment.getUpdatedOn()));
// Inserting Row
sqLiteDatabase.update(TABLE_BIZ_SEGMENT, values, KEY_BIZ_SEGMENT_ID + " = ?", new String[]{String.valueOf(bizSegment.getBizSegmentId())});
//2nd argument is String containing nullColumnHack
sqLiteDatabase.close(); // Closing database connection
}
public List<BizSegment> getBizSegmentAll() {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
List<BizSegment> bizSegmentList = new ArrayList<BizSegment>();
DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_BIZ_SEGMENT;
Cursor cursor = sqLiteDatabase.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
try {
BizSegment bizSegment = new BizSegment(cursor.getInt(0),
cursor.getInt(1),
cursor.getString(2),
df.parse(cursor.getString(3)),
df.parse(cursor.getString(4)));
bizSegmentList.add(bizSegment);
} catch (ParseException e) {
e.printStackTrace();
}
} while (cursor.moveToNext());
}
cursor.close();
sqLiteDatabase.close();
//2nd argument is String containing nullColumnHack
return bizSegmentList;
}
public void deleteBizSegment(BizSegment bizSegment) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_BIZ_SEGMENT, KEY_BIZ_SEGMENT_ID + " = ?",
new String[]{String.valueOf(bizSegment.getBizSegmentId())});
db.close();
}
Other method is Using Shared Preference suitable for limited Data. It does not provide any relationships. I use this to store basic User related Data. Not for complicated/Relational Large Data. For That Sqlite is preferred.
public class AppPreference {
SharedPreferences pref;
SharedPreferences.Editor edit;
/**
* #param clientMaster object to set preference
* #param context Context of call
*/
public void putPreference(ClientMaster clientMaster, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putInt("ClientId", clientMaster.getClientId());
edit.putString("FirstName", clientMaster.getFirstName());
edit.putString("LastName", clientMaster.getLastName());
edit.putString("Mobile", clientMaster.getMobile());
edit.putInt("PincodeId", clientMaster.getPincodeId());
edit.putString("Email", clientMaster.getEmail());
edit.putString("Password", clientMaster.getPassword());
edit.putString("MembershipCode", clientMaster.getMembershipCode());
edit.putString("MembershipIssueDate", clientMaster.getMembershipIssueDate().toString());
edit.putString("MembershipExpiryDate", clientMaster.getMembershipExpiryDate().toString());
edit.putString("MemberShipUpdatedOn", clientMaster.getMemberShipUpdatedOn().toString());
edit.putString("MemberShipQRCode", clientMaster.getMemberShipQRCode());
edit.putInt("ReferredByTypeID", clientMaster.getReferredByTypeID());
edit.putInt("ReferredByID", clientMaster.getReferredByID());
//edit.putString("LastPasswordUpdatedOn", clientMaster.getLastPasswordUpdatedOn().toString());
edit.putString("TempMembershipCode", clientMaster.getTempMembershipCode());
edit.putString("AddedOn", clientMaster.getAddedOn().toString());
//edit.putString("UpdatedOn", clientMaster.getUpdatedOn().toString());
edit.putBoolean("Login", true);
edit.putBoolean("Skip", false);
edit.commit();
}
/**
*
* #param appLanguage
* #param context
*/
public void putLanguagePreference(String appLanguage, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putString("AppLanguage", appLanguage);
edit.commit();
}
/**
* To clear All Object preference & Login False
*
* #param context Context call
*/
public void clearPreference(Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.clear();
edit.putBoolean("Login", false);
edit.commit();
}
/**
* #param InstanceId Instance Id
* #param context
*/
public void putPreferenceInstance(String InstanceId, Context context) {
pref = context.getSharedPreferences("AppPreference", Context.MODE_PRIVATE);
edit = pref.edit();
edit.putString("InstanceId", InstanceId);
edit.commit();
}
}
I have a problem with the following issue:
I have build an Android app which saves data into a SQL database (SQLite). I managed so the current date, time and the category is saved down and shown in a different menu. Somehow I am not able to get the value saved down and shown in the other layout. The data should come from an EditText: android:id="#+id/edit_betrag
The SQL column is defined like: public static final String BUDGET_BETRAG = "betrag";
and then should be shown in textView_betrag in the class BudgetRechnerAdapter respectively the other layout.
Can you please help me with this issue? Thanks a lot!!!
public class BudgetRechnerOpenHandler extends SQLiteOpenHelper {
private static final String TAG = BudgetRechnerOpenHandler.class
.getSimpleName();
// Name und Version der Datenbank
private static final String DATABASE_NAME = "budgetrechner.db";
private static final int DATABASE_VERSION = 1;
// Name und Attribute der Tabelle "Budget"
public static final String _ID = "_id";
public static final String TABELLE_NAME_BUDGET = "budget";
public static final String BUDGET_ZEIT = "zeitStempel";
public static final String BUDGET_AUSGABENART = "ausgabenArt";
public static final String BUDGET_BETRAG = "betrag";
// Konstanten für die Stimmungen
public static final int BUDGET_ESSEN = 1;
public static final int BUDGET_GETRAENK = 2;
public static final int BUDGET_SONSTIGES = 3;
// Tabelle Budget anlegen
private static final String TABELLE_BUDGET_ERSTELLEN = "CREATE TABLE "
+ TABELLE_NAME_BUDGET + " (" + _ID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + BUDGET_ZEIT + " INTEGER, "
+ BUDGET_BETRAG + " INTEGER," + BUDGET_AUSGABENART + " INTEGER);";
// Tabelle Budget löschen
private static final String TABELLE_BUDGET_DROP = "DROP TABLE IF EXISTS "
+ TABELLE_NAME_BUDGET;
BudgetRechnerOpenHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABELLE_BUDGET_ERSTELLEN);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrade der Datenbank von Version " + oldVersion + " zu "
+ newVersion + "; alle Daten werden gelöscht");
db.execSQL(TABELLE_BUDGET_DROP);
onCreate(db);
}
public void insert(int art, String beschreibung, long zeit) {
long rowId = -1;
try {
// Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
// die zu speichernden Werte
ContentValues wert = new ContentValues();
wert.put(BUDGET_AUSGABENART, art);
wert.put(BUDGET_BETRAG, beschreibung);
wert.put(BUDGET_ZEIT, zeit);
// in die Tabelle Budget einfügen
rowId = db.insert(TABELLE_NAME_BUDGET, null, wert);
} catch (SQLiteException e) {
Log.e(TAG, "insert()", e);
} finally {
Log.d(TAG, "insert(): rowId=" + rowId);
}
}
public Cursor query() {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
return db.query(TABELLE_NAME_BUDGET, null, null, null, null, null,
BUDGET_ZEIT + " DESC"
);
}
public void update(long id, int ausgabe_art_zahl) {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(BUDGET_AUSGABENART, ausgabe_art_zahl);
int numUpdated = db.update(TABELLE_NAME_BUDGET, values, _ID + " = ?",
new String[] { Long.toString(id) });
Log.d(TAG, "update(): id=" + id + " -> " + numUpdated);
}
public void delete(long id) {
// ggf. Datenbank öffnen
SQLiteDatabase db = getWritableDatabase();
int numDeleted = db.delete(TABELLE_NAME_BUDGET, _ID + " = ?",
new String[] { Long.toString(id) });
Log.d(TAG, "delete(): id=" + id + " -> " + numDeleted);
}
}
public class BudgetRechnerAdapter extends CursorAdapter {
private final Date datum;
private static final DateFormat DF_DATE = SimpleDateFormat
.getDateInstance(DateFormat.MEDIUM);
private static final DateFormat DF_TIME = SimpleDateFormat
.getTimeInstance(DateFormat.MEDIUM);
private Integer betrag;
private static final Integer DF_BETRAG = R.id.edit_betrag;
private LayoutInflater inflator;
private int ciAusgabenArt, ciZeit, ciBetrag;
public BudgetRechnerAdapter(Context context, Cursor c) {
super(context, c);
datum = new Date();
betrag = null;
inflator = LayoutInflater.from(context);
ciAusgabenArt = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_AUSGABENART);
ciZeit = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_ZEIT);
ciBetrag = c.getColumnIndex(BudgetRechnerOpenHandler.BUDGET_BETRAG);
}
#Override
public void bindView(View view, Context context, Cursor cursor) {
ImageView image = (ImageView) view.findViewById(R.id.icon);
int art = cursor.getInt(ciAusgabenArt);
TextView textView_art = (TextView) view.findViewById(R.id.text3);
if (art == BudgetRechnerOpenHandler.BUDGET_ESSEN) {
image.setImageResource(R.drawable.bild_essen);
textView_art.setText("Essen");
} else if (art == BudgetRechnerOpenHandler.BUDGET_GETRAENK) {
image.setImageResource(R.drawable.bild_getraenk);
textView_art.setText("Getränk");
} else {
image.setImageResource(R.drawable.bild_sonstiges);
textView_art.setText("Sonstiges");
}
TextView textView_Datum = (TextView) view.findViewById(R.id.text1);
TextView textView_Zeit = (TextView) view.findViewById(R.id.text2);
TextView textView_betrag = (TextView) view.findViewById(R.id.text4);
long zeitStempel = cursor.getLong(ciZeit);
datum.setTime(zeitStempel);
textView_Datum.setText(DF_DATE.format(datum));
textView_Zeit.setText(DF_TIME.format(datum));
textView_betrag.setText(DF_BETRAG.toString());
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return inflator.inflate(R.layout.verlauf, null);
}
}
i have two class one is MainActivity.java and DBadapter.java
Main Activity looks like this Code:
public class MainActivity extends Activity {
DBadapter myDB;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_activity);
openDB();
populateListFromDB();
}
private void onDistroy(){
super.onDestroy();
closeDB();
}
private void openDB(){
myDB = new DBadapter(this);
myDB.open();
}
public void closeDB(){
myDB.close();
}
private void populateListFromDB(){
Cursor cursor = myDB.getAllRows();
startManagingCursor(cursor);
String[] columnFromTable = new String[]
{DBadapter.KEY_NAME, DBadapter.KEY_GAMES, DBadapter.KEY_WON,
DBadapter.KEY_LOST, DBadapter.KEY_DIFF, DBadapter.KEY_POINTS};
int[] toLayoutElement = new int[]
{R.id.txtview_name, R.id.txtview_gameno, R.id.txtview_won,
R.id.txtview_lost, R.id.txtview_difference, R.id.txtview_points};
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(
this, R.layout.item_layout, cursor, columnFromTable, toLayoutElement);
ListView mylistview = (ListView) findViewById(R.id.listview_tabela);
mylistview.setAdapter(myCursorAdapter);
}
}
and the DBadapter Code:
public class DBadapter {
private static final String TAG = "DBadapter";
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;
public static final String KEY_NAME = "name";
public static final String KEY_GAMES = "games_no";
public static final String KEY_WON = "won";
public static final String KEY_LOST= "lost";
public static final String KEY_DIFF="difference";
public static final String KEY_POINTS="points";
public static final int COL_NAME = 1;
public static final int COL_GAMES = 2;
public static final int COL_WON = 3;
public static final int COL_LOST= 4;
public static final int COL_DIFF= 5;
public static final int COL_POINTS= 6;
public static final String[] ALL_KEYS = new String[] {KEY_ROWID, KEY_NAME, KEY_GAMES, KEY_WON, KEY_LOST, KEY_DIFF, KEY_POINTS};
// DB info: it's name, and the table we are using (just one).
public static final String DATABASE_NAME = "mydaatabase";
public static final String DATABASE_TABLE = "baske_tbl";
// Track DB version if a new version of your app changes the format.
public static final int DATABASE_VERSION = 1;
private static final String DATABASE_CREATE_SQL =
"create table " + DATABASE_TABLE
+ " (" + KEY_ROWID + " integer primary key autoincrement, "
+ KEY_NAME + " text not null, "
+ KEY_GAMES + " integer not null, "
+ KEY_WON + " integer not null"
+ KEY_LOST + " integer not null, "
+ KEY_DIFF + " integer not null, "
+ KEY_POINTS + " integer not null "
+ ");";
// Context of application who uses us.
private final Context context;
private DatabaseHelper myDBHelper;
private SQLiteDatabase db;
public DBadapter(Context ctx) {
this.context = ctx;
myDBHelper = new DatabaseHelper(context);
}
// Open the database connection.
public DBadapter open() {
db = myDBHelper.getWritableDatabase();
return this;
}
// Close the database connection.
public void close() {
myDBHelper.close();
}
// Return all data in the database.
public Cursor getAllRows() {
String where = null;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS,
where, null, null, null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase database) {
database.execSQL(DATABASE_CREATE_SQL);
}
#Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading application's database from version " + oldVersion
+ " to " + newVersion + ", which will destroy all old data!");
// Destroy old database:
database.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
// Recreate new database:
onCreate(database);
}
}
}
also have two layouts one is row layout called item_layout.xml and list_activity.xml with listView in it.
every time i try to run it it shows "process has stopped unexpectedly". Any solution ?
I am sending my Server side JSON data into database,after that i am display in an listview. But while changing in an server side or my json data will increase, it will not reflect or change in my db,Actually after changing my JSON, i want my db also update like Old+new. It has to save the new one also in db while any data add in server side also.
This my JSON part:
{
"post": [
{
"id": 249,
"title": "Career",
"content": "Last ten days ,work is not going well",
"count": 0
},
{
"id": 248,
"title": "Career",
"content": "Last ten days ,work is not going well",
"count": 0
},
]
}
This JSON value has to store in db,if next time in website some thing will add,my json will also increase,My db also wants to add that data,Rightnow is not adding that data,only one time its fetching and displaying.
This is my Mainactivity.java
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item);
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor.getCount()>0)
{
fillData(projectsCursor);
Log.i("filling", "...");
}
else
{
new GetDataAsyncTask().execute();
}
btnGetSelected = (Button) findViewById(R.id.btnget);
btnGetSelected.setOnClickListener(this);
}
private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
Dialog.setMessage("Loading.....");
Dialog.show();
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Dialog.dismiss();
mDbHelper=new GinfyDbAdapter(MainActivity.this); // initialize mDbHelper before.
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
if(projectsCursor.getCount()>0)
{
fillData(projectsCursor);
}
}
#Override
protected Void doInBackground(Void... params) {
getData();
return null;
}
}
public void getData() {
try
{
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://192.168.1.18:3001/api/v1/posts.json");
// HttpGet request = new HttpGet("http://gdata.youtube.com/feeds/api/users/mbbangalore/uploads?v=2&alt=jsonc");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity); // content will be consume only once
Log.i("................",_response);
httpclient.getConnectionManager().shutdown();
JSONObject jsonObject = new JSONObject(_response);
JSONArray contacts = jsonObject.getJSONArray("post");//(url);
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("title");
String content = c.getString("content");
String count = c.getString("count");
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
mDbHelper.saveCategoryRecord(new Category(id,title,content,count));
}
} catch (Exception e) {
e.printStackTrace();
}
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void fillData(Cursor projectsCursor) {
//mDbHelper.open();
if(projectsCursor!=null)
{
String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE, GinfyDbAdapter.CATEGORY_COLUMN_CONTENT, GinfyDbAdapter.CATEGORY_COLUMN_COUNT};
int[] to = new int[]{R.id.text2, R.id.text1, R.id.count};
dataAdapter = new SimpleCursorAdapter(
this, R.layout.activity_row,
projectsCursor,
from,
to,
0);
setListAdapter(dataAdapter);
}else
{
Log.i("...........","null");
}
}
Here i mention my dpclass also.
private static final String DATABASE_NAME = "test";
private static final String DATABASE_TABLE_PROJ = "projects";
private static final int DATABASE_VERSION = 3;
public static final String CATEGORY_COLUMN_ID = "_id";
public static final String CATEGORY_COLUMN_TITLE = "title";
public static final String CATEGORY_COLUMN_CONTENT = "content";
public static final String CATEGORY_COLUMN_COUNT = "count";
private static final String TAG = "GinfyDbAdapter";
private DatabaseHelper mDbHelper;
private static SQLiteDatabase mDb;
private final Context mCtx;
public void saveCategoryRecord(String id, String title, String content, String count) {
ContentValues contentValues = new ContentValues();
contentValues.put(CATEGORY_COLUMN_ID, id);
contentValues.put(CATEGORY_COLUMN_TITLE, title);
contentValues.put(CATEGORY_COLUMN_CONTENT, content);
contentValues.put(CATEGORY_COLUMN_COUNT, count);
mDb.insert(DATABASE_NAME, null, contentValues);
}
public Cursor getTimeRecordList() {
return mDb.rawQuery("select * from " + DATABASE_NAME, null);
}
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
private static final String DATABASE_CREATE_PROJ =
"create table " + DATABASE_TABLE_PROJ + " ("
+ CATEGORY_COLUMN_ID + " integer primary key , "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer );" ;
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String DATABASE_CREATE_PROJ = "CREATE TABLE " + DATABASE_TABLE_PROJ + "( "
+ CATEGORY_COLUMN_ID + " integer primary key, "
+ CATEGORY_COLUMN_TITLE + " text not null, " + CATEGORY_COLUMN_CONTENT + " text not null, " + CATEGORY_COLUMN_COUNT + " integer );" ;
db.execSQL(DATABASE_CREATE_PROJ);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS"+ DATABASE_TABLE_PROJ);
onCreate(db);
}
}
public void saveCategoryRecord(Category category) {
ContentValues values = new ContentValues();
values.put(CATEGORY_COLUMN_TITLE , category.getTitle());
values.put(CATEGORY_COLUMN_CONTENT, category.getContent());
values.put(CATEGORY_COLUMN_COUNT, category.getCount());
// Inserting Row
mDb.insert(DATABASE_TABLE_PROJ, null, values);
mDb.close(); // Closing database connection
}
public Cursor fetchAllProjects() {
// TODO Auto-generated method stub
return mDb.query(DATABASE_TABLE_PROJ, new String[] {CATEGORY_COLUMN_ID, CATEGORY_COLUMN_TITLE, CATEGORY_COLUMN_CONTENT, CATEGORY_COLUMN_COUNT }, null, null, null, null, null);
}
public GinfyDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public GinfyDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public boolean updateProject(long _id, String title, String content, String count) {
ContentValues args = new ContentValues();
args.put(CATEGORY_COLUMN_TITLE, title );
args.put(CATEGORY_COLUMN_CONTENT, content );
args.put(CATEGORY_COLUMN_COUNT, count );
return mDb.update(DATABASE_TABLE_PROJ, args, CATEGORY_COLUMN_ID + "=" + _id, null) > 0;
}
}
My problem is:For first time it fetches my JSON data and save in db,next time while launching its not getting newly added part of json data,I want that old and new JSON data should be store in db.
please use insert or replase raw query instead this look this.
SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"
String query = INSERT OR REPLACE INTO DATABASE_TABLE_PROJ
(CATEGORY_COLUMN_ID,CATEGORY_COLUMN_TITLE,CATEGORY_COLUMN_CONTENT,CATEGORY_COLUMN_COUNT)
VALUES
('1', 'Muhammad','xyz','2');
db.execSQL(query);
public class Mainactivity extends Activity{
ArrayList<String> ID = new ArrayList<String>();
ArrayList<String> TITLE= new ArrayList<String>();
ArrayList<String> CONTENT= new ArrayList<String>();
ArrayList<String> COUNT= new ArrayList<String>();
protected onCreate(Bundle savedInastanceState){
}
public void getData() {
//your json code
JSONArray contacts = jsonObject.getJSONArray("post");//(url);
for(int i = 0; i < contacts.length(); i++){
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("id");
String title = c.getString("title");
String content = c.getString("content");
String count = c.getString("count");
ID.add(id);
TITLE.add(title);
CONTENT.add(content);
COUNT.add(count);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private class GetDataAsyncTask extends AsyncTask<Void, Void, Void> {
private ProgressDialog Dialog = new ProgressDialog(MainActivity.this);
protected void onPreExecute() {
//
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
Dialog.dismiss();
//
}
#Override
protected Void doInBackground(Void... params) {
getData();
return null;
}
#Override
protected void onPostExecute(Void result) {
for(int i=0; i<ID.size(); i++){
mDbHelper=new GinfyDbAdapter(MainActivity.this);
mDbHelper.open();
mDbHelper.saveCategoryRecord(new Category(ID.get(i),TITLE.get(i),CONTENT.get(i),COUNTER.get(i)));
}
}
I am using SQLite in Android eclipse, however it gives me a java.lang.nullpointerexception in the function createEntry. I tried using Questoid SQLite manager to view the database file and it does show up with the table created. Where's the bug?
public class Transact {
public static final String KEY_ROWID = "_id";
public static final String KEY_TAG = "saved_tag";
private static final String DATABASE_NAME = "MyDatabaseName";
private static final String DATABASE_TABLE = "tagsTable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL(
"CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_TAG + " TEXT NOT NULL);"
);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public Transact(Context c ){
ourContext = c;
}
public Transact open() throws SQLException{
ourHelper = new DbHelper(ourContext);
ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String tagword) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_TAG, tagword);
return ourDatabase.insert(DATABASE_TABLE, "", cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{KEY_ROWID, KEY_TAG};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iRow = c.getColumnIndex(KEY_ROWID);
int iTag = c.getColumnIndex(KEY_TAG);
for(c.moveToFirst();!c.isAfterLast();c.moveToNext()){
result = result + c.getString(iRow) + " " + c.getString(iTag) + "\n";
}
return null;
}
}
Code for the add button from Main.java class:
case R.id.addDB:
boolean doneAdd = true;
try{
String tag = textTag.getText().toString();
Transact entry = new Transact(Main.this);
entry.open();
entry.createEntry(tag);
entry.close();
}catch(Exception e){
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("Error");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
doneAdd = false;
}finally{
if(doneAdd){
Dialog d = new Dialog(this);
d.setTitle("Addition done");
TextView tv = new TextView(this);
tv.setText("Success");
d.setContentView(tv);
d.show();
}
}
break;
You are using ourDatabase variable without initializing it. So not only insert you will get nullpointerexception everywhere where you are using ourDatabase variable
you can use something like following in constructor.
SQLiteDatabase db = context.openOrCreateDatabase(DATABASE_NAME,
Context.MODE_PRIVATE, null);
used this code in sq light java file
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
public class SQLiteAdapter {
Cursor cursor;
public static final String MYDATABASE_NAME = "MY_DATABASE";
public static final String MYDATABASE_TABLE = "MY_TABLE";
public static final int MYDATABASE_VERSION = 2;
public static final String KEY_ID = "_id";
public static final String KEY_CONTENT1 = "Content1";
public static final String KEY_CONTENT2 = "Content2";
public static final String KEY_CONTENT3 = "Content3";
public static final String KEY_CONTENT4 = "Content4";
public static final String KEY_CONTENT5 = "Content5";
public static final String KEY_CONTENT6 = "Content6";
public static final String KEY_CONTENT7 = "Content7";
public static final String KEY_CONTENT8 = "Content8";
public static final String KEY_CONTENT9 = "Content9";
public static final String KEY_CONTENT10 = "Content10";
public static final String KEY_CONTENT11 = "Content11";
public static final String KEY_CONTENT12 = "Content12";
// create table MY_DATABASE (ID integer primary key, Content text not null);
private static final String SCRIPT_CREATE_DATABASE = "create table "
+ MYDATABASE_TABLE + " (" + KEY_ID
+ " integer primary key autoincrement, " + KEY_CONTENT1
+ " text not null, " + KEY_CONTENT2 + " text not null, "
+ KEY_CONTENT3 + " text not null, " + KEY_CONTENT4
+ " text not null, " + KEY_CONTENT5 + " text not null, "
+ KEY_CONTENT6 + " text not null, " + KEY_CONTENT7
+ " text not null, " + KEY_CONTENT8 + " text not null, "
+ KEY_CONTENT9 + " text not null, " + KEY_CONTENT10
+ " text not null, " + KEY_CONTENT11 + " blob not null, "
+ KEY_CONTENT12 + " long not null);";
private SQLiteHelper sqLiteHelper;
private SQLiteDatabase sqLiteDatabase;
private Context context;
public SQLiteAdapter(Context c) {
context = c;
}
public SQLiteAdapter openToRead() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getReadableDatabase();
return this;
}
public SQLiteAdapter openToWrite() throws android.database.SQLException {
sqLiteHelper = new SQLiteHelper(context, MYDATABASE_NAME, null,
MYDATABASE_VERSION);
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
return this;
}
public void close() {
sqLiteHelper.close();
}
public class SQLiteHelper extends SQLiteOpenHelper {
public SQLiteHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("PRAGMA foreign_keys=ON");
db.execSQL(SCRIPT_CREATE_DATABASE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
}