how to turn two sqlite tables into a JSON object - android

Is it possible to turn a two table(relational tabel) from sqlite in to a JSON object? I've googling but still cannot find a way to convert those table. So far, i've only manage to turn one table into JSON object. If it's possible, can you tell me how to do it? if it's not, can you give me an alternatives? thanks.
here's the code that turn one table to JSON object:
private JSONArray getResults()
{
Context context = this;
String myPath = String.valueOf(context.getDatabasePath("ekantin1.db"));// Set path to database
String myTable = DatabaseHelper.ORDER_TABLE_NAME;//Set name of table
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
String searchQuery = "SELECT * FROM " + myTable;
Cursor cursor = myDataBase.rawQuery(searchQuery, null );
JSONArray resultSet = new JSONArray();
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
int totalColumn = cursor.getColumnCount();
JSONObject rowObject = new JSONObject();
for( int i=0 ; i< totalColumn ; i++ )
{
if( cursor.getColumnName(i) != null )
{
try
{
if( cursor.getString(i) != null )
{
Log.d("TAG_NAME", cursor.getString(i) );
rowObject.put(cursor.getColumnName(i) , cursor.getString(i) );
}
else
{
rowObject.put( cursor.getColumnName(i) , "" );
}
}
catch( Exception e )
{
Log.d("TAG_NAME", e.getMessage() );
}
}
}
resultSet.put(rowObject);
cursor.moveToNext();
}
cursor.close();
Log.d("TAG_NAME", resultSet.toString() );
Intent pass_data = new Intent(this,BluetoothOut.class);
pass_data.putExtra("pindah",resultSet.toString());
startActivity(pass_data);
return resultSet;
}
}
And this is my table in my DatabaseHelper :
//tabel order
public static final String ORDER_TABLE_NAME="tb_order";
public static final String COL_1="ORDERID";
public static final String COL_2="USERID";
public static final String COL_3="PASSWORD";
public static final String COL_4="MEJA";
public static final String COL_5="TOPUP";
public static final String COL_6="SALDO";
//tabel lineitems
public static final String LINEITEMS_TABLE_NAME="tb_lineitems";
public static final String COL1 = "FOODID";
public static final String COL2 = "PRICE";
public static final String COL3 = "NUM";
public static final String COL4 = "RES";
public static final String COL6 = "ORDERID_FK";
table line items and orderid related to each other where orderid in tb_order as PK and orderid_fk in tb_lineitems as FK.

A good way to export data from your database is to use Gson, which is Google's Json serialization/deserialization library.
Fetch your Objects from your database like normally, and then use Gson to convert it into Json and export it.
Here is an example of how you could do it.
private void exportDatabase() {
// Create an instance of Gson.
Gson gson = new Gson();
// You can easily convert Objects into Json.
MyItem item = new MyItem();
String json = gson.toJson(item);
// Fetch your items from your database.
ArrayList<MyItems> items = database.getAll();
// Arrays are a bit harder to convert, but not very.
json = gson.toJson(items, new TypeToken<ArrayList<MyItems>>(){}.getType());
// Now export it to some easily copy-pasted location.
System.out.println(json);
}

Related

Java Android about Hashmap

I am trying to retrieve from UpdateProduct (Hashmap) to be able to modify my items by clicking the button. I implemented void modifyItem, but I see it is missing something.
File DataBase.java
private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NOM = "Produits.db";
private static final String TABLE_PRODUCT = "Produits";
private static final String COLONNE_ID = "_id";
private static final String COLONNE_NAMEPRODUCT = "_nameProduct";
public void UpdateProduct(HashMap<String,String> object, String newValue) {
if(object == null) return;
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(COLONNE_NAMEPRODUCT, newValue);
int rows = db.update(TABLE_PRODUCT, values, "_id = ?", new String[]{object.get("id")});
db.close();
}
// MainActivity
Here my method to retrieve Hashmap data from UpdateProduct**
public void modifyItem(View view) {
if (objectSelected == null) return;
**????** selectedProduct = objectSelected.get("product");
if (selectedProduct != null && !selectedProduct.isEmpty()) {
DataBase.UpdateProduct(selectedProduct);
}
}`
Tryning to solve my project problems

How do I execute SELECT dateTime FROM TABLE_NAME using greendao

How do I execute SELECT dateTime FROM TABLE_NAME using greendao.
I am trying to fetch the coulmn datetime from table "TABLE_NAME.
To fetch a single column you need to use a raw query
private static final String SQL_DISTINCT_DATE = "SELECT DISTINCT "+YourDao.Properties.EName.datetime+" FROM "+YourDao.TABLENAME;
public static List<String> listEName(DaoSession session) {
ArrayList<String> result = new ArrayList<String>();
Cursor c = session.getDatabase().rawQuery(SQL_DISTINCT_DATE, null);
try{
if (c.moveToFirst()) {
do {
result.add(c.getString(0));
} while (c.moveToNext());
}
} finally {
c.close();
}
return result;
}

Json array with null values

I have trouble with a JSON array, and I really hope there is someone who can help me.
Lets say I have a class with JSON data and I'm sending "intent putextra" to another activity.
How can I change the value of null before I send it to another activity? I did a few prints to discover the null values and they are different, example :
Monday : null
Tuesday : 08:30 - 18:00
Wednesday : 09:00 - 17:00
**and so on.**
The problem is that --> I have all json data and I parsing them into objects, but I would like to before "intent.putextra" and send them to another activity finds null and replace them with "Closed"
so it will look like
Monday : Closed
Tuesday : 08:30 - 18:00
Wednesday : 09:00 - 17:00
EDIT
public class LocationBased extends ListActivity{
// JSON Node names
private static final String TAG_Location = "location_id";
private static final String TAG_Company = "company_id";
private static final String TAG_NAME = "name";
private static final String TAG_ADDRESS = "address";
private static final String TAG_PLACE = "place";
private static final String TAG_POSTAL = "postal";
private static final String TAG_CITY = "city";
private static final String TAG_MONDAY = "monday";
private static final String TAG_TUESDAY = "tuesday";
private static final String TAG_WEDNESDAY = "wednesday";
private static final String TAG_THURSDAY = "thursday";
private static final String TAG_FRIDAY = "friday";
private static final String TAG_SATURDAY = "saturday";
private static final String TAG_SUNDAY = "sunday";
private static final String TAG_TYPE = "type";
private static final String TAG_LAT = "lat";
private static final String TAG_LNG = "lng";
private static final String TAG_NOCAR = "nocar";
private static final String TAG = "Debug of Project"; //
private String a;
private String b;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SQLiteDatabase db = openOrCreateDatabase("mydb.db", Context.MODE_PRIVATE, null);
db.execSQL("CREATE TABLE IF NOT EXISTS gps_kordinater (ID INTEGER PRIMARY KEY AUTOINCREMENT, Latitude REAL, Longitude REAL);");
String query = "SELECT Latitude,Longitude FROM gps_kordinater WHERE Id = (SELECT MAX(Id) FROM gps_kordinater)";
Cursor cursor = db.rawQuery(query, null);
if(cursor != null)
{
cursor.moveToFirst();
a = cursor.getString(0);
b = cursor.getString(1);
}
String url = "http://webservice.XXX.XX/webservice/getLocationList.php?lat="+ a +"&lng="+ b +"";
Log.d(TAG, "Leyth URL = Lat : " + a +" Long : " + b);
// now enabled if disabled = ingen support for jb aka 4.0
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONArray json = jParser.getJSONFromUrl(url);
try {
for(int i = 0; i < json.length(); i++){
JSONObject c = json.getJSONObject(i);
String location_id = c.getString(TAG_Location);
String company_id = c.getString(TAG_Company);
String name = c.getString(TAG_NAME);
String address = c.getString(TAG_ADDRESS);
String place = c.getString(TAG_PLACE);
String postal = c.getString(TAG_POSTAL);
String city = c.getString(TAG_CITY);
String monday = c.getString(TAG_MONDAY);
String tuesday = c.getString(TAG_TUESDAY);
String wednesday = c.getString(TAG_WEDNESDAY);
String thursday = c.getString(TAG_THURSDAY);
String friday = c.getString(TAG_FRIDAY);
String saturday = c.getString(TAG_SATURDAY);
String sunday = c.getString(TAG_SUNDAY);
String type = c.getString(TAG_TYPE);
String lat = c.getString(TAG_LAT);
String lng = c.getString(TAG_LNG);
String nocar = c.getString(TAG_NOCAR);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_Location, location_id);
map.put(TAG_Company, company_id);
map.put(TAG_NAME, name);
map.put(TAG_ADDRESS, address);
map.put(TAG_PLACE, place);
map.put(TAG_POSTAL, postal);
map.put(TAG_CITY, city);
map.put(TAG_MONDAY, monday);
map.put(TAG_TUESDAY, tuesday);
map.put(TAG_WEDNESDAY, wednesday);
map.put(TAG_THURSDAY, thursday);
map.put(TAG_FRIDAY, friday);
map.put(TAG_SATURDAY, saturday);
map.put(TAG_SUNDAY, sunday);
map.put(TAG_TYPE, type);
map.put(TAG_LAT, lat);
map.put(TAG_LNG, lng);
map.put(TAG_NOCAR, nocar);
// Log.d(TAG, "Leyth Days = Mandag : " + monday +" Onsdag : " + wednesday);
// adding HashList to ArrayList
contactList.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(this, contactList,
R.layout.list_item,
new String[] { TAG_LAT, TAG_LNG, TAG_POSTAL }, new int[] {
R.id.name, R.id.email, R.id.mobile });
setListAdapter(adapter);
// selecting single ListView item
ListView lv = getListView();
// Launching new screen on Selecting Single ListItem
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
String cost = ((TextView) view.findViewById(R.id.email)).getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile)).getText().toString();
String mandag = ((TextView) view.findViewById(R.id.mandag)).getText().toString();
String tirsdag = ((TextView) view.findViewById(R.id.tirsdag)).getText().toString();
String onsdag = ((TextView) view.findViewById(R.id.onsdag)).getText().toString();
String torsdag = ((TextView) view.findViewById(R.id.torsdag)).getText().toString();
String fredag = ((TextView) view.findViewById(R.id.fredag)).getText().toString();
String lordag = ((TextView) view.findViewById(R.id.lordag)).getText().toString();
String sondag = ((TextView) view.findViewById(R.id.sondag)).getText().toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(), dk.mitaffald.maps.MainActivity.class);
in.putExtra(TAG_LAT, name);
in.putExtra(TAG_LNG, cost);
in.putExtra(TAG_Company, description);
in.putExtra(TAG_MONDAY, mandag);
in.putExtra(TAG_TUESDAY, tirsdag);
in.putExtra(TAG_WEDNESDAY, onsdag);
in.putExtra(TAG_THURSDAY, torsdag);
in.putExtra(TAG_FRIDAY, fredag);
in.putExtra(TAG_SATURDAY, lordag);
in.putExtra(TAG_SUNDAY, sondag);
startActivity(in);
}
});
}
}
I am also suffering for this problem in past but i do not know this is good solution but it works for me. Hope it is usefull to you also.
String jsonObject_string ;
try {
if (jsonObject != null) {
// ur stuff when not null
}
} catch (Exception e) {
// TODO: handle exception
// when null it automatic fill value
jsonObject_string = "Closed";
}
As I understand you want to replace any null string with a specific string , say "Closed".
This doesn't have anything todo with JSON, if this were my code I would do a simple check before adding those values to my intent. the code will look something like this:
Intent in = new Intent(getApplicationContext(), dk.mitaffald.maps.MainActivity.class);
in.putExtra(TAG_LAT, name == null ? "Closed" : name);
in.putExtra(TAG_LAT, cost== null ? "Closed" : cost);
in.putExtra(TAG_Company, description == null ? "Closed" : description );
in.putExtra(TAG_MONDAY, mandag == null ? "Closed" : mandag);
....
And so on.
name == null ? "Closed" : name ;
Simple asks if name is null then the value is closed, else return name.
it is the same as :
if (name == null){
in.putExtra(TAG_LAT, "Closed");
} else {
in.putExtra(TAG_LAT, name);
}
I hope that is what you're looking for
Why not try to replace all null strings in the JSON as a string before you parse the JSON file/object?
Possible other solution could be looping through every object checking if they're null. then replacing that for Closed
EDIT:
Load the JSON object as a string and then replace all null to Closed like this:
String JSON = JsonObject.toString();
JSON.replace("null", "Closed");
EDIT 2:
add this below JSONArray json = jParser.getJSONFromUrl(url);:
String s = json.toString(); // converts json object to string
json.replace("null", "Closed"); // replaces null for Closed
JSONArray json = new JSONArray(s); // converts back to json object
if(c.getString(TAG_MONDAY!=null && c.getString(TAG_MONDAY).length>0 && !(c.getString(TAG_MONDAY).equals("")))
{
String monday=c.getString(TAG_MONDAY);
}
else
{
String monday="Closed";
}

Get String Array from Cursor

I have a SQLite Database with 45 different entries, each with:
public static final String TABLE = "Table";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_HOUR = "hour";
public static final String COLUMN_WEEK = "week";
public static final String COLUMN_DAY = "day";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_DESCRIPTION = "description";
public static final String COLUMN_COLOUR = "colour";
public static final String COLUMN_ROOM = "room";
now I want to read out all. I Do this with following:
public Cursor fetchAllSubject(){
Cursor mCursor = database.query(true, TABLE, new String[] {
COLUMN_ID, COLUMN_HOUR, COLUMN_WEEK, COLUMN_DAY, COLUMN_NAME, COLUMN_DESCRIPTION, COLUMN_COLOUR, COLUMN_ROOM},null
, null, null, null, null, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
In a other class I have this code to read all out:
dao = new DAO(this);
Cursor subjectList = dao.fetchAllSubject();
Now I want to have for each entry an array with ID, Hour, week, ... but I have no idea how to do that.
My first try was following:
ArrayList<String> mo1h = new ArrayList<String>();
subjectList.moveToFirst();
while(!subjectList.isAfterLast()) {
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ID)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_HOUR)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_WEEK)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_DAY)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_NAME)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_DESCRIPTION)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_COLOUR)));
mo1h.add(subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ROOM)));
subjectList.moveToNext();
}
But everything is in mo1h, and I dont know how to devide it.
The best would be to have a String[] for each. Has anybody an Idea?
Thanks!
You can create on Bean class and then create one ArrayList (Collection class)
public class Bean
{
public Bean();
String id, hour, week, day, name, description, color, room;
}
now create list of Bean
ArrayList<Bean> mo1h = new ArrayList<Bean>();
subjectList.moveToFirst();
while(!subjectList.isAfterLast()) {
Bean b = new Bean();
b.id = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ID));
b.hour =subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_HOUR));
...
...
// all your column
mo1h.add(b);
}
Why not continue with your strategy, but instead use an ArrayList of String[]:
ArrayList<String[]> mo1h = new ArrayList<String[]>();
subjectList.moveToFirst();
while(!subjectList.isAfterLast()) {
String[] toUse = new String[8];
toUse[0] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ID));
toUse[1] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_HOUR));
toUse[2] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_WEEK));
toUse[3] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_DAY));
toUse[4] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_NAME));
toUse[5] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_DESCRIPTION));
toUse[6] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_COLOUR));
toUse[7] = subjectList.getString(subjectList.getColumnIndex(dao.COLUMN_ROOM));
mo1h.add(toUse);
subjectList.moveToNext();
}

My device doesnt recognize my DB where my emulator does

When I try to query using my db in the femulator it works perfectly, but given the same appliction and same varibales into the device (milestone) it seems like the DB is not recognized.
I think the key to solving it is to understand where on the device we store the db.
On the emulator it's on /data/data/com.countryCityGame/databases/test1.db
But when I am using the device itself it must be in another place, does someone know where?
This is the java code where I build the DB:
public static void main(String[] args) throws Exception {
String CITIES[] = city.split(",");
String ANIMEL[] = animel.split(",");
String CELEB[] = UK_CELEB.split(",");
String Nature[] = vegtablesAndFruiets.split(",");
String V[][] = {COUNTRIES,CITIES,ANIMEL,Nature,occupations,CELEB};
String []TypeNames = {"Country","City","Animels","Nature","Occupation","Celeb"};
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:test1.db");
Statement stat = conn.createStatement();
//stat.executeUpdate("drop table if exists "+"android_metadata"+";");
stat.executeUpdate("create table android_metadata (\"locale\" TEXT DEFAULT 'en_US');");
//PreparedStatement prep1 = conn.prepareStatement(
// "insert into "+"android_metadata"+" values (?);");
//prep1.setString(1, "en_US") ;
//prep1.addBatch();
stat.executeUpdate("drop table if exists "+TABLE_NAME+";");
//stat.executeUpdate("create table "+TABLE_NAME+" (name, occupation);");
stat.executeUpdate("create table "+TABLE_NAME+" ("+VALUE+" TEXT NOT NULL,"+TYPE+" TEXT NOT NULL,"+LETTER+" TEXT NOT NULL,"+counter+" INTEGER);");
PreparedStatement prep = conn.prepareStatement(
"insert into "+TABLE_NAME+" values (?,?,?,?);");
//private void insertToTalble();
int j=0,i=0;
try{
for(j = 0 ;j < V.length; j++)
for (i = 0 ;i < V[j].length ; i++)
{
if (V[j][i] != null)
{
V[j][i] = asUpperCaseFirstChar(V[j][i]);
Character c = V[j][i].charAt(0);
prep.setString(3, c.toString());
}
prep.setString(1, V[j][i]);
prep.setString(2, TypeNames[j]);
prep.setInt(4,0);
prep.addBatch();
}
}catch(Exception e) {
System.out.println("***********"+i+"***************");
}
conn.setAutoCommit(false);
prep.executeBatch();
// prep1.executeBatch();
conn.setAutoCommit(true);
ResultSet rs = stat.executeQuery("select * from "+TABLE_NAME+";");
while (rs.next()) {
System.out.println("country name = " + rs.getString(VALUE));
System.out.println("type = " + rs.getString(TYPE));
System.out.println("letter = " + rs.getString(LETTER));
System.out.println("********************************");
}
rs.close();
conn.close();
}
and this is the code from where i first get the bug:
private static final String DB_PATH = "/data/data/com.countryCityGame/databases/test1.db";
private static final String DATABASE_NAME = "test1.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_NAME = "GameTable";
private static final String VALUE = "value";
private static final String TYPE = "type";
private static final String LETTER = "letter";
public countryCityGameLogic(EditText[] myEditTextArr , Context context) {
points = 0;//init values
Cursor cursor = null ;
this.context = context;
openHelper = new OpenHelper(context);
gameList = new CharSequence [myEditTextArr.length];
for (int i = 0 ; i < myEditTextArr.length; i++){
gameList[i] = myEditTextArr[i].getText();
}
//this.db = openHelper.getWritableDatabase();
try{
db = SQLiteDatabase.openDatabase(DB_PATH , null, SQLiteDatabase.NO_LOCALIZED_COLLATORS/*SQLiteDatabase.CREATE_IF_NECESSARY*/);
//this question
cursor = db.query(TABLE_NAME, new String[] {LETTER}
,LETTER+ " like " + "'%" + "A" +"%'", null, null, null, null);
if ( !cursor.moveToFirst()){
//*****if data base doesnot exist HERE I GOT PROBLEMES****
this.db = openHelper.getWritableDatabase();//make new data base
}
}catch(SQLiteException e){
this.db = openHelper.getWritableDatabase();//make new data base
// for (int i = 0 ; i < ALLVALUES.length ; i++)
// insertValus(ALLVALUES[i],i);
}
NOTICE: In the device I am using /data/data/com.countryCityGame/databases/test1.db, it might not be the path where the appliction is located onto the device I am using.

Categories

Resources