i'm trying to de-serialization a class from a sqlite db, this is how i serialize it:
protected String serializeRule(){
String ruleSerialized = "";
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
ObjectOutputStream so = new ObjectOutputStream(bo);
so.writeObject(this);
so.flush();
ruleSerialized = bo.toString();
} catch (Exception e) {
ruleSerialized ="";
}
return ruleSerialized;
}
store into a sqlite database:
public void writeRule(){
String ruleSerialized = serializeRule();
if (ruleSerialized != null && !ruleSerialized.isEmpty() ){
DatabaseHelper mDbHelper = new DatabaseHelper(context);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(RuleContract.RuleEntry.COLUMN_NAME, ruleSerialized);
id = db.insert(RuleContract.RuleEntry.TABLE_NAME, null, values);
}
}
de-serialized it:
public static ArrayList<RuleBase> getRules(Context context){
ArrayList<RuleBase> ret = new ArrayList<RuleBase>();
DatabaseHelper mDbHelper = new DatabaseHelper(context);
SQLiteDatabase db = mDbHelper.getWritableDatabase();
String[] projection = {
RuleContract.RuleEntry._ID,
RuleContract.RuleEntry.COLUMN_NAME
};
Cursor c = db.query(
RuleContract.RuleEntry.TABLE_NAME, // The table to query
projection, // The columns to return
null, // The columns for the WHERE clause
null, // The values for the WHERE clause
null, // don't group the rows
null, // don't filter by row groups
null // The sort order
);
if(c.moveToFirst()){
do{
String column1 = c.getString(0);
String column2 = c.getString(1);
RuleBase r = getRule(column2);
ret.add(r);
}while(c.moveToNext());
}
c.close();
db.close();
return ret;
}
public static RuleBase getRule(String rules){
RuleBase obj = null;
try {
byte b[] = rules.getBytes();
ByteArrayInputStream bi = new ByteArrayInputStream(b);
ObjectInputStream si = new ObjectInputStream(bi);
obj = (RuleBase) si.readObject();
} catch (Exception e) {}
return obj;
}
when i open a new ObjectInputStream(bi) i always have StreamCorruptedException some problem with sqlite or other?
Related
I have created one App. In this app I want to get Data from Database using Getter and Setter method. I don't Know how can I do that. Please help me. Necessary Code is here:
DisplayMedia.java
public class DisplayMedia extends Activity {
ImageView displayImage;
VideoView displayVideo;
TextView txtMediaDate,txtMediaTime,txtMediaAddress;
DatabaseHelper dbHelper;
Intent intent;
String mediaPath,mediaDate,mediaTime,mediaAddress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display_media);
displayImage = (ImageView) findViewById(R.id.displayImage);
displayVideo = (VideoView) findViewById(R.id.displayVideo);
txtMediaDate = (TextView) findViewById(R.id.txtMediaDate);
txtMediaTime = (TextView) findViewById(R.id.txtMediaTime);
txtMediaAddress = (TextView) findViewById(R.id.txtMediaAddress);
dbHelper = new DatabaseHelper(getApplicationContext());
mediaPath = dbHelper.displayImages();
File mediaFile = new File(mediaPath);
if (mediaFile.exists()) {
if (isImage(mediaPath)) {
displayVideo.setVisibility(View.GONE);
displayImage.setVisibility(View.VISIBLE);
Bitmap myBitmap = BitmapFactory.decodeFile(mediaFile.getAbsolutePath());
int height = (myBitmap.getHeight() * 512 / myBitmap.getWidth());
Bitmap scale = Bitmap.createScaledBitmap(myBitmap, 512, height, true);
displayImage.setImageBitmap(scale);
} else {
displayImage.setVisibility(View.GONE);
displayVideo.setVisibility(View.VISIBLE);
displayVideo.setVideoURI(Uri.parse(mediaFile.toString()));
displayVideo.start();
}
}
}
public static boolean isImage(String str) {
boolean temp = false;
String[] arr = { ".jpeg", ".jpg", ".png", ".bmp", ".gif" };
for (int i = 0; i < arr.length; i++) {
temp = str.endsWith(arr[i]);
if (temp) {
break;
}
}
return temp;
}
}
DataBaseHelper.java
public void insertMedia(String mPath,String mDate,String mTime,String mAddress) {
db = this.getWritableDatabase();
ContentValues values = new ContentValues();
cur = db.query(INCIDENT, null, null, null, null, null, null);
cur.moveToFirst();
values.put("mediaPath", mPath);
values.put("mediaDate", mDate);
values.put("mediaTime", mTime);
values.put("mediaAddress", mAddress);
db.insert(INCIDENT, null, values);
db.close();
}
public String displayMedia() {
db = this.getReadableDatabase();
cur = db.query(INCIDENT, null, null, null, null, null, null);
String path = null,date = null, time = null, address = null;
cur.moveToFirst();
while (cur.isAfterLast() == false) {
path = (cur.getString(0));
date = (cur.getString(1));
time = (cur.getString(2));
address = (cur.getString(3));
cur.moveToNext();
}
return path;
}
In this app I inserted data in data base successfully. In my data base following data has stored:
MediaPath, MediaDate, MediaTime, MediaAddress
Now I want to get all data using above displayMedia(). how can I do that?
You can get a Cursor Object contains all the table data inside:
public Cursor getCursor() {
db = this.getReadableDatabase();
return db.query(INCIDENT, null, null, null, null, null, null);
}
And then, wherever You need it, You can get the information like:
Cursor c = yourDatabaseClass.getCursor();
int rows = c.getCount();
for(int i=0;i<rows;i++){
String path = c.getString(0);
String date = c.getString(1);
String time = c.getString(2);
String adress = c.getString(3);
c.moveToNext();
}
Then it´s up to You how You want to display path/date/time/adress information.
I'm trying to copy some data in a table and insert into another table. I entered the data into an ArrayList, however, is only copied a given and not all those present. What am I missing?
private void Tras() {
String numero_ricevuto = (i.getStringExtra("numero"));
SQLiteDatabase db = mHelper.getWritableDatabase();
final ArrayList<Dettaglio_i> dettaglii = new ArrayList<Dettaglio_i>();
String sql = "SELECT data, unita_di_misura FROM prev WHERE numero = '"+numero_ricevuto+"'";
Cursor c = db.rawQuery(sql, null);
while (c.moveToNext()){
Dettaglio_i e = new Dettaglio_i();
e.data_ = c.getString(0);
e.unita_di_misura = c.getString(1);
dettaglii.add(e);
}
c.close();
ContentValues cv = new ContentValues();
Dettaglio_i e = new Dettaglio_i();
cv.put(VerTable.SI_NO, "0");
cv.put(VerTable .DATA, e.data_);
cv.put(VerTable .U_M, e.unita_di_misura);
boolean inserite = false;
if (!inserite){
long result = db.insert(VerTable .TABLE_NAME, null, cv);
if (result > 0){
inserite = true;
}
}
if (inserite){
}
db.close();
}
Try replacing your code with this:
private void Tras() {
String numero_ricevuto = (i.getStringExtra("numero"));
SQLiteDatabase db = mHelper.getWritableDatabase();
String insert = String.format("INSERT INTO %s (%s, %s, %s) ",
VerTable.TABLE_NAME, VerTable.SI_NO, VerTable.DATA, VerTable .U_M);
String select = "SELECT '0', data, unita_di_misura FROM prev WHERE " +
"numero='"+numero_ricevuto+"'";
db.rawQuery(insert+select, null);
db.close();
}
In my app i am storing data to SQLite, and now i am trying to fetch that data from SQLite to activity.
as per requirement i just have to store single data at a time and my table will contain only single data row not more than one row.
so I want if table has data row then fetch data and show in form in onCreate(..) of LoginActivity.java
Getting:
The method SelectData(String) in the type myDBClass is not applicable for the arguments ()
myDBClass.java:
// Select Data
public String[] SelectData(String strOperatorID) {
// TODO Auto-generated method stub
try {
String arrData[] = null;
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_NAME, new String[] { "*" },
"OperatorID=?",
new String[] { String.valueOf(strOperatorID) }, null, null, null, null);
if(cursor != null)
{
if (cursor.moveToFirst()) {
arrData = new String[cursor.getColumnCount()];
arrData[0] = cursor.getString(0); // DeviceID
arrData[1] = cursor.getString(1); // EmailID
arrData[2] = cursor.getString(2); // Event
arrData[3] = cursor.getString(3); // Operator
arrData[4] = cursor.getString(4); // EventOperator
}
}
cursor.close();
db.close();
return arrData;
} catch (Exception e) {
return null;
}
}
LoginActivity.java:-
public class LoginActivity extends Activity {
.................
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_login);
btnLogout = (Button) findViewById(R.id.btnLogout);
btnCamera = (Button) findViewById(R.id.btnCamera);
btnGallery = (Button) findViewById(R.id.btnGallery);
txtDeviceID = (TextView) findViewById(R.id.txtDeviceID);
txtEmailID = (TextView) findViewById(R.id.txtEmailID);
txtEvent = (TextView) findViewById(R.id.txtEvent);
txtOperative = (TextView) findViewById(R.id.txtOperative);
txtEventOperator = (TextView) findViewById(R.id.txtEventOperator);
Intent intent = getIntent();
deviceID = intent.getStringExtra("deviceID");
emailID = intent.getStringExtra("emailID");
event = intent.getStringExtra("name");
operative = intent.getStringExtra("firstName");
txtDeviceID.setText(deviceID);
txtEmailID.setText(emailID);
txtEvent.setText(event);
txtOperative.setText(operative);
txtEventOperator.setText(event + " " + operative);
strEvent = txtEvent.getText().toString();
strOperative = txtOperative.getText().toString();
// Dialog
final AlertDialog.Builder adb = new AlertDialog.Builder(this);
AlertDialog ad = adb.create();
// new Class DB
final myDBClass myDb = new myDBClass(this);
// Save Data
long saveStatus = myDb.InsertData(
txtDeviceID.getText().toString(),
txtEmailID.getText().toString(),
txtEvent.getText().toString(),
txtOperative.getText().toString(),
txtEventOperator.getText().toString()
);
if(saveStatus <= 0)
{
ad.setMessage("Error!! ");
ad.show();
return;
}
// Show Data
String arrData[] = myDb.SelectData();
if(arrData != null)
{
txtDeviceID.setText(arrData[1]);
txtEmailID.setText(arrData[2]);
txtEvent.setText(arrData[3]);
txtOperative.setText(arrData[4]);
txtEventOperator.setText(arrData[5]);
}
if(txtEvent.getText().toString().equals("") && txtOperative.getText().toString().equals(""))
{
Intent intentCall = new Intent(LoginActivity.this, LicenseListActivity.class);
startActivity(intentCall);
}
}
From the op requirement..
change your method like this..
public String[] SelectData() {
// TODO Auto-generated method stub
try {
String arrData[] = new String[5];
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_NAME, null, null, null, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
arrData[0] = cursor.getString(0); // DeviceID
arrData[1] = cursor.getString(1); // EmailID
arrData[2] = cursor.getString(2); // Event
arrData[3] = cursor.getString(3); // Operator
arrData[4] = cursor.getString(4); // EventOperator
}
}
cursor.close();
db.close();
return arrData;
} catch (Exception e) {
return null;
}
}
Your SelectData method takes a String argument (strOperatorID) but you are calling it with no argument, so obviously it cannot be found.
By the way you should respect Java naming conventions for your methods (i.e. not starting with upper case character)
public String[] SelectData() {
// TODO Auto-generated method stub
try {
String arrData[] = new String[5];
SQLiteDatabase db;
db = this.getReadableDatabase(); // Read Data
Cursor cursor = db.query(TABLE_NAME, null, null, null, null,
null, null);
if (cursor != null) {
if (cursor.moveToFirst()) {
do{
arrData[0] = cursor.getString(0); // DeviceID
arrData[1] = cursor.getString(1); // EmailID
arrData[2] = cursor.getString(2); // Event
arrData[3] = cursor.getString(3); // Operator
arrData[4] = cursor.getString(4); // EventOperator
} while (cur.moveToNext());
}
}
return arrData;
} catch (Exception e) {
return null;
}finally{
cursor.close();
db.close();
}
public Cursor getsomething()
{
this.open();
Cursor c = database.rawQuery("SELECT content_id FROM " +
DatabaseHandler.Table_Name2 +
" where playlist_id==100813", null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String path = c.getString(c.getColumnIndex("content_id"));
MainActivity.t1.append("\n");
MainActivity.t1.append(path);
}while (c.moveToNext());
}
}
this.close();
return null;
}
I am using the above code to get the values but it is showing all the values from he content_id column. What am I doing wrong?
this.open();
ContentValues values2 = new ContentValues();
String csvFilename = "/mnt/sdcard/playlist.csv";
CSVReader csvReader = new CSVReader(new FileReader(csvFilename));
String Rowst[] = null;
while((Rowst = csvReader.readNext()) != null) {
st1 = Rowst[0];
st2= Rowst[1];
st3= Rowst[2];
st4= Rowst[3];
st5= Rowst[4];
st6 = Rowst[5];
st7 = Rowst[6];
st8 = Rowst[7];
st9 = Rowst[8];
st10 = Rowst[9];
st11 = Rowst[10];
st12 = Rowst[11];
st13 = Rowst[12];
st14 = Rowst[13];
st15 = Rowst[14];
st16 = Rowst[15];
st17 = Rowst[16];
st18 = Rowst[17];
st19 = Rowst[18];
values2.put(DatabaseHandler.play1,st1);
values2.put(DatabaseHandler.play2,st2);
values2.put(DatabaseHandler.play3,st3);
values2.put(DatabaseHandler.play4,st4);
values2.put(DatabaseHandler.play5,st5);
values2.put(DatabaseHandler.play6,st6);
values2.put(DatabaseHandler.play7,st7);
values2.put(DatabaseHandler.play8,st8);
values2.put(DatabaseHandler.play9,st9);
values2.put(DatabaseHandler.play10,st10);
values2.put(DatabaseHandler.play11,st11);
values2.put(DatabaseHandler.play12,st12);
values2.put(DatabaseHandler.play13,st13);
values2.put(DatabaseHandler.play14,st14);
values2.put(DatabaseHandler.play15,st15);
values2.put(DatabaseHandler.play16,st16);
values2.put(DatabaseHandler.play17,st17);
values2.put(DatabaseHandler.play18,st18);
values2.put(DatabaseHandler.play19,st19);
database.insert(DatabaseHandler.Table_Name2, null, values2);
}
csvReader.close();
this.close();
this is my code to insert data in the this table,i am trying to read a csvfile on the sdcard and entering its data into table am i doing something wrong i have posted this also if it helps
public Cursor getsomething()
{
this.open();
Cursor c = db.query(DatabaseHandler.Table_Name2, null, "playlist_id=100813", null, null, null, null);
if (c.getCount() > 0)
{
if (c.moveToFirst())
{
do {
String path = c.getString(c.getColumnIndex("content_id"));
MainActivity.t1.append("\n");
MainActivity.t1.append(path);
}while (c.moveToNext());
}
}
this.close();
return null;
}
package com.omkarsoft.ImagePortofolio;
import java.util.ArrayList;
import com.omkarsoft.ImagePortofolio.dataBaseHelper;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
public class sqlQueries {
dataBaseHelper database;
SQLiteDatabase db ;
UrlList urllist ;
public sqlQueries( dataBaseHelper dbh , SQLiteDatabase db )
{
database = dbh;
this.db = db;
}
public sqlQueries() {
System.out.println("no are sqlqueries constructor");
}
public void insertIntoCompanyTable( String companyname ) {
db = database.getWritableDatabase(); // this works fine here
ContentValues values = new ContentValues();
values.put(dataBaseHelper.COMPANY_NAME, companyname);
System.out.println(values);
db.insert(dataBaseHelper.COMPANY_LIST, null, values);
}
public int getCompanyID( String companyName)
{
int id = 0 ;
Cursor c = null;
try {
db = database.getReadableDatabase(); // this works fine here
String query = "SELECT company_id FROM company_list WHERE company_name = '"+ companyName +"'";
c = db.rawQuery(query,null);
} catch (Exception e) {
System.out.println("In getCompanyID : " +e);
}
if (c != null ) {
if (c.moveToFirst()) {
id = c.getInt(c.getColumnIndex("company_id"));
}
}
return id;
}
public int getCompanies( String comp) {
int id = 0;
Cursor c = null;
ArrayList<String> names = new ArrayList<String>();
try {
db = database.getReadableDatabase(); // this works fine here
String query = "SELECT * FROM company_list ";
c = db.rawQuery(query, null);
} catch (Exception e) {
System.out.println(e);
}
if (c != null) {
if (c.getCount() == 0)
id = 1;
else {
if (c.moveToFirst()) {
do {
String name = c.getString(c.getColumnIndex("company_name"));
names.add(name);
} while (c.moveToNext());
}
if( names.contains(comp))
id = 0;
else
id = 1 ;
}
}
return id;
}
public void insertIntoImageTable( int companyid , String productname , String productdesc , byte[] bmp )
{
try
{
db = database.getWritableDatabase(); // blows here i get a NPE
ContentValues values = new ContentValues();
values.put(dataBaseHelper.COMPANY_ID, companyid);
values.put(dataBaseHelper.PRODUCT_NAME, productname);
values.put(dataBaseHelper.PRODUCT_DESCRIPTION, productdesc);
values.put(dataBaseHelper.PRODUCT_IMAGE, bmp);
System.out.println(values);
db.insertOrThrow(dataBaseHelper.IMAGE_DATA, null, values);
System.out.println(values);
}
catch( Exception e)
{
e.printStackTrace();
}
}
}
You need to open the DB for writing first like e.g.
SQLiteDatabase db = tdHelper.getWritableDatabase();
and tdHelper being an instance of
private static class TweetDBOpenHelper extends SQLiteOpenHelper
Just try to logcat every parameter you put in db.insert with String.valueOf(); You'll then see which parameter is null.