How can I localize the database for the project in other languages (for example en, ru, fr and others)
I have an already ready database in English, but I want to make the application multilingual and able to work with other databases depending on the device locale.
I've already seen a lot of forums on this issue, but in each of them it says that you need to get the current locale. But I can not understand where these codes should be attributed. My code is completely listed below.
public class DatabaseHelper extends OrmLiteSqliteOpenHelper
{
private static final String DATABASE_NAME = MuseumConfig.DATABASE_NAME;
private static final String DATABASE_PATH = "/data/data/" + CookbookApplication.getContext().getPackageName() + "/databases/";
private static final int DATABASE_VERSION = CookbookConfig.DATABASE_VERSION;
private static final String PREFS_KEY_DATABASE_VERSION = "database_version";
private Dao<CategoryModel, Long> mCategoryDao = null;
private Dao<AboutModel, Long> mRecipeDao = null;
private Dao<InformationModel, Long> mIngredientDao = null;
// singleton
private static DatabaseHelper instance;
public static synchronized DatabaseHelper getInstance()
{
if(instance==null) instance = new DatabaseHelper();
return instance;
}
private DatabaseHelper()
{
super(CookbookApplication.getContext(), DATABASE_PATH + DATABASE_NAME, null, DATABASE_VERSION);
if(!databaseExists() || DATABASE_VERSION>getVersion())
{
synchronized(this)
{
boolean success = copyPrepopulatedDatabase();
if(success)
{
setVersion(DATABASE_VERSION);
}
}
}
}
#Override
public void onCreate(SQLiteDatabase db, ConnectionSource connectionSource)
{
try
{
Logcat.d("DatabaseHelper.onCreate()");
//TableUtils.createTable(connectionSource, CategoryModel.class);
//TableUtils.createTable(connectionSource, RecipeModel.class);
//TableUtils.createTable(connectionSource, IngredientModel.class);
}
catch(android.database.SQLException e)
{
Logcat.e("DatabaseHelper.onCreate(): can't create database", e);
e.printStackTrace();
}
}
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion)
{
try
{
Logcat.d("DatabaseHelper.onUpgrade()");
}
catch(android.database.SQLException e)
{
Logcat.e("DatabaseHelper.onUpgrade(): can't upgrade database", e);
e.printStackTrace();
}
}
#Override
public void close()
{
super.close();
mCategoryDao = null;
mRecipeDao = null;
mIngredientDao = null;
}
public synchronized void clearDatabase()
{
try
{
Logcat.d("DatabaseHelper.clearDatabase()");
TableUtils.dropTable(getConnectionSource(), CategoryModel.class, true);
TableUtils.dropTable(getConnectionSource(), RecipeModel.class, true);
TableUtils.dropTable(getConnectionSource(), IngredientModel.class, true);
TableUtils.createTable(getConnectionSource(), CategoryModel.class);
TableUtils.createTable(getConnectionSource(), RecipeModel.class);
TableUtils.createTable(getConnectionSource(), IngredientModel.class);
}
catch(android.database.SQLException e)
{
Logcat.e("DatabaseHelper.clearDatabase(): can't clear database", e);
e.printStackTrace();
}
catch(java.sql.SQLException e)
{
Logcat.e("DatabaseHelper.clearDatabase(): can't clear database", e);
e.printStackTrace();
}
}
public synchronized Dao<CategoryModel, Long> getCategoryDao() throws java.sql.SQLException
{
if(mCategoryDao==null)
{
mCategoryDao = getDao(CategoryModel.class);
}
return mCategoryDao;
}
public synchronized Dao<RecipeModel, Long> getRecipeDao() throws java.sql.SQLException
{
if(mRecipeDao==null)
{
mRecipeDao = getDao(RecipeModel.class);
}
return mRecipeDao;
}
public synchronized Dao<IngredientModel, Long> getIngredientDao() throws java.sql.SQLException
{
if(mIngredientDao==null)
{
mIngredientDao = getDao(IngredientModel.class);
}
return mIngredientDao;
}
private boolean databaseExists()
{
File file = new File(DATABASE_PATH + DATABASE_NAME);
boolean exists = file.exists();
Logcat.d("DatabaseHelper.databaseExists(): " + exists);
return exists;
}
private boolean copyPrepopulatedDatabase()
{
String locale = java.util.Locale.getDefault().getDisplayName();
// copy database from assets
try
{
// create directories
File dir = new File(DATABASE_PATH);
dir.mkdirs();
// output file name
String outputFileName = DATABASE_PATH + DATABASE_NAME;
Logcat.d("DatabaseHelper.copyDatabase(): " + outputFileName);
// create streams
InputStream inputStream = CookbookApplication.getContext().getAssets().open(DATABASE_NAME);
OutputStream outputStream = new FileOutputStream(outputFileName);
// write input to output
byte[] buffer = new byte[1024];
int length;
while((length = inputStream.read(buffer))>0)
{
outputStream.write(buffer, 0, length);
}
// close streams
outputStream.flush();
outputStream.close();
inputStream.close();
return true;
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
}
private int getVersion()
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(CookbookApplication.getContext());
return sharedPreferences.getInt(PREFS_KEY_DATABASE_VERSION, 0);
}
private void setVersion(int version)
{
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(CookbookApplication.getContext());
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt(PREFS_KEY_DATABASE_VERSION, version);
editor.commit();
}
}
Related
I have a custom ListView that uses an object class for its data. The users can add new items to the listview, the arraylist is then saved in SharedPreferences. However, I also want to save each individual item so that I can use it in another Expandable ListView, how could I create a file for each individual item the user creates, or perhaps there is a better why to do it? Thanks in advance. Here is the object class:
public class Item implements Serializable{
String homework, date, classes;
public Item(String homework, String date, String classes){
this.homework = homework;
this.date = date;
this.classes = classes;
}
public String getHomework(){
return homework;
}
public String getDate(){
return date;
}
public String getClasses(){
return classes;
}
}
Why not use a database?There is a bit of setting up, but after the initial set up writing/reading data is very easy.
https://developer.android.com/training/basics/data-storage/databases.html
An example of serialize-deserialize class
public final class Serialize
{
private static final String className = Serialize.class.getName();
public static void save(Object saveThis, String serializeFileName, Context context)
{
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try
{
if(saveThis != null)
{
fos = context.openFileOutput(serializeFileName, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(saveThis);
}
}
catch(Throwable t)
{
//log it
}
finally
{
if(oos != null)
{
try{oos.close();}catch(Throwable t){}
}
if(fos != null)
{
try{fos.close();}catch(Throwable t){}
}
}
}
public static Object read(String serializeFileName, Context context)
{
FileInputStream fis = null;
ObjectInputStream ois = null;
Object readThis = null;
try
{
File file = context.getFileStreamPath(serializeFileName);
if(file != null && file.exists())
{
fis = context.openFileInput(serializeFileName);
ois = new ObjectInputStream(fis);
readThis = ois.readObject();
}
}
catch(Throwable t)
{
//log it
}
finally
{
if(ois != null)
{
try{ois.close();}catch(Throwable t){}
}
if(fis != null)
{
try{fis.close();}catch(Throwable t){}
}
}
return readThis;
}
public static boolean delete(String serializeFileName, Context context)
{
boolean deleted = false;
try
{
File file = context.getFileStreamPath(serializeFileName);
if(file != null && (file.exists()))
{
deleted = file.delete();
}
}
catch(Throwable t)
{
//log it
}
return deleted;
}
public static boolean exist(String serializeFileName, Context context)
{
boolean exist = false;
try
{
File file = context.getFileStreamPath(serializeFileName);
if(file != null && (file.exists()))
{
exist = true;
}
}
catch(Throwable t)
{
//log it
}
return exist;
}
}
Use the save method to save the serializable object in a file and the read method to read it.
We used a special database,so i want to write a database connection Pool,there is something wrong with the code, when i debug into the static block,at first JVM worked in the Properties properties = new Properties(); but next step is int i = 0; i dont know why it ingored the other code in the static block
public class GoldDataSource {
private static String goldip;
private static int goldport;
private static String username;
private static String password;
private static int maxPollSize;
private static LinkedList<Server> list = new LinkedList<Server>();
private static Logger logger = LoggerFactory.getLogger(GoldDataSource.class);
static {
try {
Properties properties = new Properties();
InputStream is = GoldDataSource.class.getClassLoader().getResourceAsStream("/conf/db/gold.properties");
properties.load(is);
goldip = properties.getProperty("gold.ip");
goldport = Integer.parseInt(properties.getProperty("gold.port"));
username = properties.getProperty("gold.username");
password = properties.getProperty("gold.password");
maxPollSize = Integer.parseInt(properties.getProperty("gold.pool.maxPollSize"));
for (int i = 0; i < maxPollSize; i++) {
Server server = new ServerImpl(goldip, goldport, username, password);
server.connect();
server.login();
list.add(server);
}
} catch (Exception e) {
....
}
}
public synchronized static Server getServer() {
try {
int i = 0;
while (true) {
Server aServer = list.removeFirst();
if (aServer != null) {
return aServer;
} else {
if (i >= 3) {
return aServer;
}
Thread.sleep(500);
i++;
}
}
} catch (Exception e) {
...
return null;
}
}
public static void closeServer(Server aServer) {
list.addLast(aServer);
}}
I used Server server = GoldDataSource.getServer(); to get connection,but when it executed Properties properties = new Properties();then jump into the code int i = 0; which in the getServer() method
I edited the code with singleton pattern,it worked ,but i still do not understand why the old code didn't worked , and i catched "java.lang.reflect.InvocationTargetException" in the first catch block old code.
public class GoldDataSource {
private static String goldip;
private static int goldport;
private static String username;
private static String password;
private static int maxPollSize;
private static LinkedList<Server> list = new LinkedList<Server>();
private static InputStream is;
private static GoldDataSource aDataSource = new GoldDataSource();
private static Logger logger = LoggerFactory.getLogger(GoldDataSource.class);
private goldDataSource() {
try {
Properties properties = new Properties();
is = GoldDataSource.class.getClassLoader().getResourceAsStream("/conf/db/gold.properties");
properties.load(is);
goldip = properties.getProperty("gold.ip");
goldport = Integer.parseInt(properties.getProperty("gold.port"));
username = properties.getProperty("gold.username");
password = properties.getProperty("gold.password");
maxPollSize = Integer.parseInt(properties.getProperty("gold.pool.maxPollSize"));
for (int i = 0; i < maxPollSize; i++) {
Server server = new ServerImpl(goldip, goldport, username, password);
server.connect();
server.login();
list.add(server);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static goldDataSource getDateSource() {
return aDataSource;
}
public synchronized Server getServer() {
try {
int i = 0;
while (true) {
Server aServer = list.removeFirst();
if (aServer != null) {
return aServer;
} else {
if (i >= 3) {
return aServer;
}
Thread.sleep(500);
i++;
}
}
} catch (Exception e) {
logger.error("get connection error:" + e.toString());
return null;
}
}
public void closeServer(Server aServer) {
list.addLast(aServer);
}
}
I have a topology in which I am trying to count word occurrences which are being generated by SimulatorSpout (not real Stream) and after that write to MySQL database table, the table scheme is very simple:
Field | Type | ...
ID | int(11) | Auto_icr
word | varchar(50) |
count | int(11) |
But I am facing weird problem(as I beforementioned)
I successfully submitted The Topology to my Storm Cluster which consists of 4 supervisors, and I can see the flow of the Topology in Storm Web UI
(no exceptions) but when I checked the MySQL table, to my surprise, the table is empty...
ANY COMMENTS, SUGGESTIONS ARE WELCOME...
Here are spouts and bolts:
public class MySQLConnection {
private static Connection conn = null;
private static String dbUrl = "jdbc:mysql://192.168.0.2:3306/test?";
private static String dbClass = "com.mysql.jdbc.Driver";
public static Connection getConnection() throws SQLException, ClassNotFoundException {
Class.forName(dbClass);
conn = DriverManager.getConnection(dbUrl, "root", "qwe123");
return conn;
}
}
============================= SentenceSpout ===============================
public class SentenceSpout extends BaseRichSpout{
private static final long serialVersionUID = 1L;
private boolean _completed = false;
private SpoutOutputCollector _collector;
private String [] sentences = {
"Obama delivered a powerfull speech against USA",
"I like cold beverages",
"RT http://www.turkeyairline.com Turkish Airlines has delayed some flights",
"don't have a cow man...",
"i don't think i like fleas"
};
private int index = 0;
public void open (Map config, TopologyContext context, SpoutOutputCollector collector) {
_collector = collector;
}
public void nextTuple () {
_collector.emit(new Values(sentences[index]));
index++;
if (index >= sentences.length) {
index = 0;
Utils.waitForSeconds(1);
}
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("sentence"));
}
public void ack(Object msgId) {
System.out.println("OK: " + msgId);
}
public void close() {}
public void fail(Object msgId) {
System.out.println("FAIL: " + msgId);
}
}
============================ SplitSentenceBolt ==============================
public class SplitSentenceBolt extends BaseRichBolt {
private static final long serialVersionUID = 1L;
private OutputCollector _collector;
public void prepare (Map config, TopologyContext context, OutputCollector collector) {
_collector = collector;
}
public void execute (Tuple tuple) {
String sentence = tuple.getStringByField("sentence");
String httpRegex = "((https?|ftp|telnet|gopher|file)):((//)|(\\\\))+[\\w\\d:##%/;$()~_?\\+-=\\\\\\.&]*";
sentence = sentence.replaceAll(httpRegex, "").replaceAll("RT", "").replaceAll("[.|,]", "");
String[] words = sentence.split(" ");
for (String word : words) {
if (!word.isEmpty())
_collector.emit(new Values(word.trim()));
}
_collector.ack(tuple);
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("word"));
}
}
=========================== WordCountBolt =================================
public class WordCountBolt extends BaseRichBolt {
private static final long serialVersionUID = 1L;
private HashMap<String , Integer> counts = null;
private OutputCollector _collector;
private ResultSet resSet = null;
private Statement stmt = null;
private Connection _conn = null;
private String path = "/home/hduser/logOfStormTops/logger.txt";
String rLine = null;
public void prepare (Map config, TopologyContext context, OutputCollector collector) {
counts = new HashMap<String, Integer>();
_collector = collector;
}
public void execute (Tuple tuple) {
int insertResult = 0;
int updateResult = 0;
String word = tuple.getStringByField("word");
//----------------------------------------------------
if (!counts.containsKey(word)) {
counts.put(word, 1);
try {
insertResult = wordInsertIfNoExist(word);
if (insertResult == 1) {
_collector.ack(tuple);
} else {
_collector.fail(tuple);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
} else {
//-----------------------------------------------
counts.put(word, counts.get(word) + 1);
try {
// writing to db
updateResult = updateCountOfExistingWord(word);
if (updateResult == 1) {
_collector.ack(tuple);
} else {
_collector.fail(tuple);
}
// Writing to file
BufferedWriter buffer = new BufferedWriter(new FileWriter(path));
buffer.write("[ " + word + " : " + counts.get("word") + " ]");
buffer.newLine();
buffer.flush();
buffer.close();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("{word-" + word + " : count-" + counts.get(word) + "}");
}
}
public void declareOutputFields(OutputFieldsDeclarer declarer) {
}
// *****************************************************
public int wordInsertIfNoExist(String word) throws ClassNotFoundException, SQLException {
String query = "SELECT word FROM wordcount WHERE word=\"" + word + "\"";
String insert = "INSERT INTO wordcount (word, count) VALUES (\"" + word + "\", 1)";
_conn = MySQLConnection.getConnection();
stmt = _conn.createStatement();
resSet = stmt.executeQuery(query);
int res = 0;
if (!resSet.next()) {
res = stmt.executeUpdate(insert);
} else {
System.out.println("Yangi qiymatni kirityotrganda nimadir sodir bo'ldi");
}
resSet.close();
stmt.close();
_conn.close();
return res;
}
public int updateCountOfExistingWord(String word) throws ClassNotFoundException, SQLException {
String update = "UPDATE wordcount SET count=count+1 WHERE word=\"" + word + "\"";
_conn = MySQLConnection.getConnection();
stmt = _conn.createStatement();
int result = stmt.executeUpdate(update);
//System.out.println(word + "'s count has been updated (incremented)");
resSet.close();
stmt.close();
_conn.close();
return result;
}
}
========================= WordCountTopology ==============================
public class WordCountTopology {
private static final String SENTENCE_SPOUT_ID = "sentence-spout";
private static final String SPLIT_BOLT_ID = "split-bolt";
private static final String COUNT_BOLT_ID = "count-bolt";
private static final String TOPOLOGY_NAME = "NewWordCountTopology";
#SuppressWarnings("static-access")
public static void main(String[] args) throws AlreadyAliveException, InvalidTopologyException {
SentenceSpout spout = new SentenceSpout();
SplitSentenceBolt splitBolt = new SplitSentenceBolt();
WordCountBolt countBolt = new WordCountBolt();
TopologyBuilder builder = new TopologyBuilder();
builder.setSpout(SENTENCE_SPOUT_ID, spout, 2);
builder.setBolt(SPLIT_BOLT_ID, splitBolt, 4).shuffleGrouping(SENTENCE_SPOUT_ID);
builder.setBolt(COUNT_BOLT_ID, countBolt, 4).fieldsGrouping(SPLIT_BOLT_ID, new Fields("word"));
Config config = new Config();
config.setMaxSpoutPending(100);
config.setDebug(true);
StormSubmitter submitter = new StormSubmitter();
submitter.submitTopology(TOPOLOGY_NAME, config, builder.createTopology());
}
}
It is because the _collector.ack(tuple) is not being called when there is exception thrown. When there are too many pending tuple, spout will stop sending new tuples. Try throwing out RuntimeException instead of printStackTrace.
This question already has answers here:
Ship an application with a database
(15 answers)
Closed 7 years ago.
I have a static sqlite db. How could I include it into the app? Where should i put it in my project folder? How should I access it from DatabaseHandler?
Everything I found on the web was using sqlite only for creating a new db and storing user or temp data in it, but not using existing db with predefined data.
Official Google docs does not tell how to do that.
Handling this case is basically just doing a file copy.
The tricky part is
To create the database when needed only (otherwise just open it)
To implement the upgrade logic
I wrote a sample Helper class that demonstrate how to load a database from your assets.
public abstract class SQLiteAssetHelper extends SQLiteOpenHelper {
// ----------------------------------
// CONSTANTS
// ----------------------------------
private static final String DATABASE_DIR_NAME = "databases";
// ----------------------------------
// ATTRIBUTES
// ----------------------------------
private final Context mContext;
private final CursorFactory mFactory;
private SQLiteDatabase mDatabase;
private String mDatabaseName;
private String mDatabaseAssetPath;
private String mDatabaseDiskPath;
private boolean mIsProcessingDatabaseCreation; // Database creation may take some time
// ----------------------------------
// CONSTRUCTORS
// ----------------------------------
public SQLiteAssetHelper(Context context, String name, CursorFactory factory, String destinationPath, int version) {
super(context, name, factory, version);
mContext = context;
mFactory = factory;
mDatabaseName = name;
mDatabaseAssetPath = DATABASE_DIR_NAME + "/" + name;
if (destinationPath == null) {
mDatabaseDiskPath = context.getApplicationInfo().dataDir + "/" + DATABASE_DIR_NAME;
} else {
mDatabaseDiskPath = destinationPath;
}
}
// ----------------------------------
// OVERRIDEN METHODS
// ----------------------------------
#Override
public synchronized SQLiteDatabase getWritableDatabase() {
if (mDatabase != null && mDatabase.isOpen() && !mDatabase.isReadOnly()) {
// the database is already open and writable
return mDatabase;
}
if (mIsProcessingDatabaseCreation) {
throw new IllegalStateException("getWritableDatabase is still processing");
}
SQLiteDatabase db = null;
boolean isDatabaseLoaded = false;
try {
mIsProcessingDatabaseCreation = true;
db = createOrOpenDatabase();
// you should probably check for database new version and process upgrade if necessary
onOpen(db);
isDatabaseLoaded = true;
return db;
} catch (IOException e) {
e.printStackTrace();
return null;
} finally {
mIsProcessingDatabaseCreation = false;
if (isDatabaseLoaded) {
if (mDatabase != null) {
try {
mDatabase.close();
} catch (Exception e) {
e.printStackTrace();
}
}
mDatabase = db;
} else {
if (db != null) db.close();
}
}
}
#Override
public final void onCreate(SQLiteDatabase db) {
// getWritableDatabase() actually handles database creation so nothing to code here
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO implement your upgrade logic here
}
// ----------------------------------
// PRIVATE METHODS
// ----------------------------------
private void copyDatabaseFromAssets() throws IOException {
String dest = mDatabaseDiskPath + "/" + mDatabaseName;
String path = mDatabaseAssetPath;
InputStream is = mContext.getAssets().open(path);
File databaseDestinationDir = new File(mDatabaseDiskPath + "/");
if (!databaseDestinationDir.exists()) {
databaseDestinationDir.mkdir();
}
IOUtils.copy(is, new FileOutputStream(dest));
}
private SQLiteDatabase createOrOpenDatabase() throws IOException {
SQLiteDatabase db = null;
File file = new File (mDatabaseDiskPath + "/" + mDatabaseName);
if (file.exists()) {
db = openDatabase();
}
if (db != null) {
return db;
} else {
copyDatabaseFromAssets();
db = openDatabase();
return db;
}
}
private SQLiteDatabase openDatabase() {
try {
SQLiteDatabase db = SQLiteDatabase.openDatabase(
mDatabaseDiskPath + "/" + mDatabaseName, mFactory, SQLiteDatabase.OPEN_READWRITE);
return db;
} catch (SQLiteException e) {
e.printStackTrace();
return null;
}
}
// ----------------------------------
// NESTED CLASSES
// ----------------------------------
private static class IOUtils {
private static final int BUFFER_SIZE = 1024;
public static void copy(InputStream in, OutputStream outs) throws IOException {
int length;
byte[] buffer = new byte[BUFFER_SIZE];
while ((length = in.read(buffer)) > 0) {
outs.write(buffer, 0, length);
}
outs.flush();
outs.close();
in.close();
}
}; // IOUtils
}
Then you only have to create a class that extends from the one above like this :
public class MyDbHelper extends SQLiteAssetHelper {
// ----------------------------------
// CONSTANTS
// ----------------------------------
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_FILE_NAME = "test.db";
// ----------------------------------
// CONSTRUCTORS
// ----------------------------------
public MyDbHelper(Context context) {
super(context, DATABASE_FILE_NAME, null, context.getFilesDir().getAbsolutePath(), DATABASE_VERSION);
}
}
Each time you will call getWritableDatabase() from your MyDbHelper instance, it will do all the copy/open stuff for you and return the writable database.
As I said before, I did not implement the upgrade() method in this sample, you'll have to.
I also didn't implement getReadableDatabase() since I usually only use getWritableDatabase(). You may need to do it.
If you want to test it, just do the following:
Copy the code above
Create a folder in your assets called "databases" and insert your sqlite database file in it
In MyDatabaseHelper, change the value of the DATABASE_FILE_NAME constants with the name of the database in the asset folder
Don't forget to instantiate the MyDatabaseHelper and call for getWritableDatabse()
Hope this helped.
I created this class and I created my data in json. It seems that doesn't work and returns empty when I try to insert the data in a database sqLite. This is the class with the creation of the Json:
public class Corsa
{
public Corsa corsaData = null;
public int id = 0;
public String oraPartenza;
public String oraArrivo;
public String partenza;
public String arrivo;
public String codiceLinea;
public String codiceCorsa;
public String tipoCorsa;
public String linkDettaglio;
#Override
public String toString() {
return partenza + " / "+ oraPartenza + "\n" + arrivo + " / " +oraArrivo;
}
public Corsa() {
}
/** Json **/
public static Corsa LoadJson(String jsonStr)
{
Corsa corsaJson = new Corsa();
try
{
JSONObject jObj = new JSONObject(jsonStr);
corsaJson.oraPartenza = HtmlUtils.getJSonString(jObj, "oraPartenza");
corsaJson.oraArrivo = HtmlUtils.getJSonString(jObj, "oraArrivo");
corsaJson.partenza = HtmlUtils.getJSonString(jObj, "partenza");
corsaJson.arrivo = HtmlUtils.getJSonString(jObj, "arrivo");
corsaJson.linkDettaglio = HtmlUtils.getJSonString(jObj, "linkDettaglio");
corsaJson.codiceCorsa = HtmlUtils.getJSonString(jObj, "codiceCorsa");
corsaJson.codiceLinea = HtmlUtils.getJSonString(jObj, "codiceLinea");
}
catch (Exception e) { e.printStackTrace(); }
return corsaJson;
}
public static JSONObject CreateJSon(Corsa corsaJson)
{
JSONObject jObj = new JSONObject();
try
{
jObj.put("oraPartenza", corsaJson.oraPartenza);
jObj.put("oraArrivo", corsaJson.oraArrivo);
jObj.put("partenza", corsaJson.partenza);
jObj.put("arrivo", corsaJson.arrivo);
jObj.put("linkDettaglio", corsaJson.linkDettaglio);
jObj.put("codiceCorsa", corsaJson.codiceCorsa);
jObj.put("codiceLinea", corsaJson.codiceLinea);
} catch (Exception e) { e.printStackTrace(); }
return jObj;
}
}
This is the saved json:
public static void SaveCorsa(Context context, Corsa c)
{
DeleteCorsa(context, c);
SqlHelper dbHelper = null;
try {
dbHelper = new SqlHelper(context);
SQLiteDatabase database = dbHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put("CORSA_DATA", Corsa.CreateJSon(c.corsaData).toString());
database.insert(TABLE_PREFERITI, null, initialValues);
Log.d("Insert preferiti", initialValues.toString());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dbHelper!=null) dbHelper.close();
}
}
and the logCat returns CORSA_DATA{}..So it is empty.. But it's strange beacause is created in the activity..Any idea what's wrong? Thanks