lundi 30 mars 2015

SQLiteDataAdapter converts null to 0 - how to prevent that?

Below is a snippet of the code. As you can see, that method returns a table from SQLite database, and adds that table to a DataSet if it doesn't exist yet.



SQLiteConnection connection;
DataSet Set = new DataSet();

DataTable GetTable(string tableName, string command)
{
if (!Set.Tables.Contains(tableName))
{
var adapter = new SQLiteDataAdapter(command, connection);
SQLiteCommandBuilder builder = new SQLiteCommandBuilder(adapter);

adapter.FillSchema(Set, SchemaType.Source, tableName);
adapter.Fill(Set, tableName);
adapter.Dispose();
}

return Set.Tables[tableName];
}


To call it, for example



DataTable myTable = GetTable("MyTable", "select * from MyTable);


There are some cells that are of type int/decimal, but their values are null. However when I'm trying to populate myTable, they are conveniently converted to 0's which I DO NOT WANT. How do I go about fixing that? I would like to keep null values as null's.


The SQLite file that I use is SQLite3. Just in case it helps.


Thanks in advance!


Web Server Tutorial (SQLite)

I am currently developing an android application that will connect to the internet to receive data strings. Is there any good tutorial someone can give me or link me to.


Assume that I know nothing about web servers and how to even host one.


How to add Limit to Date_Time in SQLite for Android

The following line is used for query in Android, where orderBy is the parameter



String orderBy = Helper.COLUMN_DATE_TIME +" DESC";


This arranges the table rows in descending order of time. The value of date_time is in the format %Y-%m-%d %H:%M:%S


I would like to introduce LIMIT in the above statement (as in some instances I am only in need of %Y-%m-%d). How can this be done? I mean I am limited by my knowledge and try. Any help would be appreciated


Android how load n TextViews with data from Sqlite query

I have an sqlite db that contain information of some TextViews, like text, background color and id of the changed TextView, because i have a TableView with 60 TextViews. When the user touch one of them, he can change the content of the TextView and the background color. My problem is that when i take back all the saved TextView i put them into a list.


Materia.java is my object



package com.ddz.diarioscolastico;

public class Materia {

private int _id;
private String _nome;
private int _colore;
//private int _giorno;
//private int _ora;

//Empty constructor
public Materia(){

}
//Constructor
public Materia(int id, String nome, int colore){
this._id = id;
this._nome = nome;
this._colore = colore;

}
// constructor
public Materia(String nome, int colore){
this._nome = nome;
this._colore = colore;
}
// getting ID
public int getID(){
return this._id;
}

// setting id
public void setID(int id){
this._id = id;
}

//getting color
public int getColor(){

return this._colore;

}
//setting color
public void setColor(int colore){

this._colore = colore;

}
//getting nome materia
public String getMateria() {

return this._nome;

}
//setting nome materia
public void setMateria(String nome) {

this._nome = nome;

}
}


With the class MySQLiteHelper i manage the database



public class MySQLiteHelper extends SQLiteOpenHelper {

//Database version
private static final int DATABASE_VERSION = 1;
//Database name
private static final String DATABASE_NAME = "materie.db";
//Materie table name
public static final String TABLE_MATERIE = "materie";
//Materie columns table names
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "nome";
public static final String COLUMN_COLOR = "colore";

public MySQLiteHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_MATERIE_TABLE = "CREATE TABLE " + TABLE_MATERIE + "("
+ COLUMN_ID + " INTEGER PRIMARY KEY," + COLUMN_NAME + " TEXT,"
+ COLUMN_COLOR + " INTEGER," + ")";
db.execSQL(CREATE_MATERIE_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_MATERIE);

// Create tables again
onCreate(db);
}

// Adding new contact
public void addMateria(Materia materia) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(COLUMN_NAME, materia.getMateria()); // Materia Name
values.put(COLUMN_COLOR, materia.getColor()); // Materia color

// Inserting Row
db.insert(TABLE_MATERIE, null, values);
db.close(); // Closing database connection
}

// Getting single contact
public Materia getMateria(int id) {
SQLiteDatabase db = this.getReadableDatabase();

//ELIMINATO COLUMN_DAY e COLUMN_HOUR
Cursor cursor = db.query(TABLE_MATERIE, new String[] { COLUMN_ID,
COLUMN_NAME, COLUMN_COLOR }, COLUMN_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();

Materia materia = new Materia(Integer.parseInt(cursor.getString(0)),
cursor.getString(1),
Integer.parseInt(cursor.getString(2)));
// return contact
return materia;
}

// Getting All Contacts
public List<Materia> getAllMaterie() {
List<Materia> materiaList = new ArrayList<Materia>();
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_MATERIE;

SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);

// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Materia materia = new Materia();
materia.setID(Integer.parseInt(cursor.getString(0)));
materia.setMateria(cursor.getString(1));
materia.setColor(Integer.parseInt(cursor.getString(2)));
// Adding contact to list
materiaList.add(materia);
} while (cursor.moveToNext());
}

// return contact list
return materiaList;
}

// Getting contacts Count
public int getMateriaCount() {
String countQuery = "SELECT * FROM " + TABLE_MATERIE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();

// return count
return cursor.getCount();
}

// Updating single contact
public int updateMateria(Materia materia) {
SQLiteDatabase db = this.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(COLUMN_NAME, materia.getMateria());
values.put(COLUMN_COLOR, materia.getColor());

// updating row
return db.update(TABLE_MATERIE, values, COLUMN_ID + " = ?",
new String[] { String.valueOf(materia.getID()) });
}

// Deleting single contact
public void deleteMateria(Materia materia) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_MATERIE, COLUMN_ID + " = ?",
new String[] { String.valueOf(materia.getID()) });
db.close();
}

}//Close class database


As you can see with the method public List<Materia> getAllMaterie() i take all materie from sqlite and put them into a list.


onCreate of the activity that manage data:



@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_set_orario);

MySQLiteHelper db = new MySQLiteHelper(this);

//Get all materie inside database
List<Materia> materia = db.getAllMaterie();

//Cambio ciclicamente le textview presenti nel database
TextView changedtextview = (TextView)findViewById(materia.);
changedtextview.setText(materia.nome);


}//Fine oncreate


In my Activity i need to take back all the materie inputed into database for change the TextViews that are touched from user. How can i take the single id's in the List materia? Something like:



TextView changedtextview = (TextView)findViewById(materia._id);


But this not work. There is something wrong?


Android APP multilanguage SQLite

I would fully translate my Android app. (this includes the SQLite is displayed on the phone language)


This is like now connect;



private static final int DATABASE_VERSION = 5;
private static final String DATABASE_NAME = "quotes.db";
private static final String DB_PATH_SUFFIX = "/databases/";
private static final String TABLE_QUOTES = "quote";
private static final String KEY_ID = "_id";
static Context myContext;

public DataBaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
myContext = context;
}


I had thought to remove the name string database and pass it the name database using the strings.xml file.


super(context, context.getResources (). getString (R.string.DATABASE_NAME), null, DATABASE_VERSION);


Also look for the query to pass on through strings.xml, but can not find clear documentation.


I would appreciate if I do not guide a little. Many Thanks.


Example the query:



// Select All Query
String selectQuery = "SELECT name, COUNT(author_name ) AS count FROM author LEFT JOIN quote ON name = author_name WHERE name LIKE '%"
+ value + "%' GROUP BY name ORDER BY name ASC";

Generating Achart From SQLite Database

I am trying to display information from my SQLite database in a chart. I am using the AchartEngine for this, but I cannot seem to get the chart to populate from the database. I have hard coded in in the example below to show that the chart draws, but no matter what I try, I cannot seem to get the values to plot on the chart. I am new to android and any help would be great.


Thanks.


Here is my DBAdapter Class:



public class DBAdapter {

// For logging:
private static final String TAG = "DBAdapter";

// DB Fields
public static final String KEY_ROWID = "_id";
public static final int COL_ROWID = 0;

public static final String KEY_EXERCISE = "exercise";
public static final String KEY_LAST = "lastCount";
public static final String KEY_HIGH = "highCount";


public static final int COL_EXERCISE = 1;
public static final int COL_LAST = 2;
public static final int COL_HIGH = 3;

public static final String[] ALL_KEYS = new String[] { KEY_ROWID, KEY_EXERCISE,
KEY_LAST, KEY_HIGH };


public static final String DATABASE_NAME = "Exercise.db";
public static final String DATABASE_TABLE = "CounterTable";

public static final int DATABASE_VERSION = 3;

private static final String CREATE_TABLE = "CREATE TABLE " + DATABASE_TABLE + " (" + KEY_ROWID
+ " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_EXERCISE
+ " TEXT NOT NULL, " + KEY_LAST + " TEXT NOT NULL, "
+ KEY_HIGH + " TEXT NOT NULL);";

// Context of application
private DatabaseHelper myDBHelper;
private final Context context;
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();
}

// Add a new set of values to the database.
public long insertRow(String exercise, int lastCount, int highCount) {

// Create row's data:
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_EXERCISE, exercise);
initialValues.put(KEY_LAST, lastCount);
initialValues.put(KEY_HIGH, highCount);

// Insert it into the database.
return db.insert(DATABASE_TABLE, null, initialValues);
}

// Change an existing row to be equal to new data.
public void updateRow(long rowId, String exercise,
int lastCount, int highCount) {
String where = KEY_ROWID + "=" + rowId;
ContentValues newValues = new ContentValues();
newValues.put(KEY_EXERCISE, exercise);
newValues.put(KEY_LAST, lastCount);
newValues.put(KEY_HIGH, highCount);

// Insert it into the database.
db.update(DATABASE_TABLE, newValues, where, null);
}

// Change an existing row to be equal to new data.
public void updateRow(String exercise, int lastCount) {
String where = KEY_EXERCISE + "= \"" + exercise +"\"";
ContentValues newValues = new ContentValues();
newValues.put(KEY_LAST, lastCount);

// Insert it into the database.
db.update(DATABASE_TABLE, newValues, where, null);
}

// Change an existing row to be equal to new data.
public void updateRow(String exercise, int lastCount, int highCount) {
String where = KEY_EXERCISE + "= \"" + exercise +"\"";
ContentValues newValues = new ContentValues();
newValues.put(KEY_LAST, lastCount);
newValues.put(KEY_HIGH, highCount);

// Insert it into the database.
db.update(DATABASE_TABLE, newValues, where, null);
}

// Delete a row from the database, by rowId (primary key)
public boolean deleteRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
return db.delete(DATABASE_TABLE, where, null) != 0;
}

public void deleteAll() {
Cursor c = getAllRows();
long rowId = c.getColumnIndexOrThrow(KEY_ROWID);
if (c.moveToFirst()) {
do {
deleteRow(c.getLong((int) rowId));
} while (c.moveToNext());
}
c.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;
}

// Get a specific row (by rowId)
public Cursor getRow(long rowId) {
String where = KEY_ROWID + "=" + rowId;
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}

public Cursor getRow(String exercise) {
String where = KEY_EXERCISE + "= \"" + exercise +"\"";
Cursor c = db.query(true, DATABASE_TABLE, ALL_KEYS, where, null, null,
null, null, null);
if (c != null) {
c.moveToFirst();
}
return c;
}


/**
* Private class which handles database creation and upgrading. Used to
* handle low-level database access.
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

@Override
public void onCreate(SQLiteDatabase _db) {
_db.execSQL(CREATE_TABLE);
}

@Override
public void onUpgrade(SQLiteDatabase _db, 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:
_db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);

// Recreate new database:
onCreate(_db);
}
}


}


Here is my ChartActivity:



public class BarChartActivity extends Circuit {

private Button BackButton;
private View mChart;
private String[] exercise = new Circuit().exercises;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_draw_bar_chart);

BackButton = (Button) this.findViewById(R.id.backButton);

// Set up quit button function
BackButton.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {

Intent intent = new Intent(getApplicationContext(), ChartMenu.class);
startActivity(intent);

}
});


////////////////////////////////////////////****Problem Here****/////////////////////////////////////////////////////////////////////////////



int[] x = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };

// What do i put in here to get the values to read from the database?
int[] Last = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
int[] Highest = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };


/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////



// Creating an XYSeries for Last
XYSeries LastSeries = new XYSeries("Last");
// Creating an XYSeries for Highest
XYSeries HighestSeries = new XYSeries("Highest");
// Adding data to Last and Highest Series
for (int i = 0; i < x.length; i++) {
LastSeries.add(i, Last[i]);
HighestSeries.add(i, Highest[i]);
}

// Creating a dataset to hold each series
XYMultipleSeriesDataset dataset = new XYMultipleSeriesDataset();
// Adding Last Series to the dataset
dataset.addSeries(LastSeries);
// Adding Highest Series to dataset
dataset.addSeries(HighestSeries);

// Creating a XYMultipleSeriesRenderer to customize the whole chart
XYMultipleSeriesRenderer multiRenderer = new XYMultipleSeriesRenderer();
multiRenderer.setChartTitle("Last vs Highest Chart");
multiRenderer.setXTitle("Exercises");
multiRenderer.setYTitle("Reps");
multiRenderer.setAxesColor(Color.BLACK);
multiRenderer.setLabelsColor(Color.BLACK);
multiRenderer.setMarginsColor(Color.WHITE);
multiRenderer.setBarSpacing(0.5);
multiRenderer.setYLabelsPadding(10);
multiRenderer.setMargins(new int[] { 5, 15, 5, 5 });
multiRenderer.setXLabelsAngle(300);
multiRenderer.setXLabelsPadding(20);
for (int i = 0; i < exercise.length - 1; i++) {
multiRenderer.addXTextLabel(i, exercise[i]);
}

// Creating XYSeriesRenderer to customize highestSeries
XYSeriesRenderer highestRenderer = new XYSeriesRenderer();
highestRenderer.setDisplayChartValues(true);
highestRenderer.setChartValuesSpacing((float) 2.5);

// Creating XYSeriesRenderer to customize lastSeries
XYSeriesRenderer lastRenderer = new XYSeriesRenderer();
lastRenderer.setColor(Color.RED);
lastRenderer.setDisplayChartValues(true);
lastRenderer.setChartValuesSpacing((float) 2.5);

// Adding LastRenderer and HighestRenderer to multipleRenderer
// Note: The order of adding dataseries to dataset and renderers to
// multipleRenderer
// should be same
multiRenderer.addSeriesRenderer(lastRenderer);
multiRenderer.addSeriesRenderer(highestRenderer);

// this part is used to display graph on the xml
LinearLayout chartContainer = (LinearLayout) findViewById(R.id.chart);
// remove any views before u paint the chart
chartContainer.removeAllViews();
// drawing bar chart
mChart = ChartFactory.getBarChartView(BarChartActivity.this, dataset,
multiRenderer, null);
// adding the view to the linearlayout
chartContainer.addView(mChart);

db.close();
}
}


}


I'm already using a simple cursor adapter to read from the db in another class to display the db in a listView:



public class LogView extends Activity {

private Button BackButton;

DBAdapter myDb;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_db_list);

openDB();
populateListViewFromDB();
//registerListClickCallback();
}

@Override
protected void onDestroy() {
super.onDestroy();
closeDB();
}

private void openDB() {
myDb = new DBAdapter(this);
myDb.open();
}

private void closeDB() {
myDb.close();
}

public void populateListViewFromDB() {
Cursor cursor = myDb.getAllRows();

// Allow activity to manage lifetime of the cursor.
// DEPRECATED! Runs on the UI thread, OK for small/short queries.
startManagingCursor(cursor);

// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[] { DBAdapter.KEY_ROWID, DBAdapter.KEY_EXERCISE,
DBAdapter.KEY_LAST, DBAdapter.KEY_HIGH,
DBAdapter.KEY_LAST };
int[] toViewIDs = new int[] { R.id.textView0, R.id.textView2, R.id.textView1,
R.id.textView3 };

// Create adapter to may columns of the DB onto elements in the UI.
SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, // Context
R.layout.item_layout, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);

// Set the adapter for the list view
ListView myList = (ListView) findViewById(R.id.list);
myList.setAdapter(myCursorAdapter);

BackButton = (Button) this.findViewById(R.id.backButton);

// Set up quit button function
BackButton.setOnClickListener(new OnClickListener() {

public void onClick(View arg0) {

Intent intent = new Intent(getApplicationContext(), StartScreen.class); startActivity(intent);

}
});
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.log_view, menu);
return true;
}


}


Any help would be great, I'm really stuck. Thanks


How can I put Rating Bar

I'm trying to put rating bar stars instead of spinner on this code but getting error again and again can anybody after trying my luck i came here. Can anybody help me please. Thanks



<RatingBar
android:id="@+id/review_rating"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:numStars="3"
android:stepSize="1.0"
android:entries="@array/rating"
android:rating="2.0" />
</RatingBar>


package com.example.facilitiesreviewapp;


public class AddReviewActivity extends ActionBarActivity {



String id;

@Override
protected void onCreate(Bundle savedInstanceState) {
setTitle("Add Reviews");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_review);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.add_review, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();

Intent intent;

if(id == R.id.search_station)
{
intent = new Intent(this, SearchActivity.class);
startActivity(intent);
}
else if(id == R.id.add_station)
{
intent = new Intent(this, AddStationActivity.class);
startActivity(intent);
}

return super.onOptionsItemSelected(item);
}

public void onResume()
{
super.onResume();

Intent intent = getIntent();
id = intent.getStringExtra(SearchActivity.EDITID);
}

public void saveReview(View view)
{
//Get fields
EditText dateView = (EditText) findViewById(R.id.review_date);
EditText commentView = (EditText) findViewById(R.id.review_comments);
ratingBar ratingView = (ratingBar) findViewById(R.id.review_rating);
Spinner featureView = (Spinner) findViewById(R.id.review_feature);

//Get Content
String review_date = dateView.getText().toString();
String review_comment = commentView.getText().toString();
String review_rating = ratingView.getSelectedItem().toString();
String review_feature = featureView.getSelectedItem().toString();

//Validation
boolean errors = false;
String error_msg = "";

if(review_date.equals(""))
{
errors = true;
error_msg += "Date field is required";
}

if(errors)
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(error_msg).setTitle("Error in submission");
AlertDialog dialog = builder.create();
dialog.show();
}
else
{
DbHandler dbh = new DbHandler(this);
SQLiteDatabase db = dbh.getWritableDatabase();

ContentValues values = new ContentValues();
values.put(DbHandler.ReviewHandler.COLUMN_NAME_STATION_ID, id);
values.put(DbHandler.ReviewHandler.COLUMN_NAME_DATE, review_date);
values.put(DbHandler.ReviewHandler.COLUMN_NAME_FEATURE, review_feature);
values.put(DbHandler.ReviewHandler.COLUMN_NAME_RATING, review_rating);
values.put(DbHandler.ReviewHandler.COLUMN_NAME_COMMENTS, review_comment);

long newRowID = db.insert(DbHandler.ReviewHandler.Table_Name, "", values);

db.close();
dbh.close();

Intent intent = new Intent(this, ReviewsActivity.class);
intent.putExtra(SearchActivity.EDITID, id);
startActivity(intent);
}
}


}