How to insert new data into SQLite - java

I'm a newbie here.
I need to insert new data (Lat,Lng) into a SQLite database, so I can show all the markers from my table.
Here is my code, MySQLiteHelper.java.
Is it correct?
Please help me
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class MySQLiteHelper extends SQLiteOpenHelper{
public static final String TABLE_LOCATIONS = "locations";
public static final String NAMA = "id_title";
public static final String ID_COL = "loc_id";
public static final String TITLE = "loc_title";
public static final String SNIPPET = "loc_snippet";
public static final String POSITION = "loc_position";
private static final int DB_VERSION = 1;
private static final String DB_NAME = "parkir.db";
private static final String DATABASE_CREATE = "create table "
+ TABLE_LOCATIONS + "(" + ID_COL
+ " integer primary key autoincrement, "
+ " text, "+ TITLE
+ " text, " + SNIPPET
+ " text, " + POSITION
+ " text);";
public MySQLiteHelper(Context context){
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
SQLiteDatabase dba = this.getWritableDatabase();
ContentValues v=new ContentValues();
v.put(MySQLiteHelper.POSITION, "-6.368590, 106.832702");
v.put(MySQLiteHelper.TITLE, "Parkiran Kampus D");
v.put(MySQLiteHelper.SNIPPET, "Kampus Gunadarma yang terletak di Margonda");
dba.insert(MySQLiteHelper.TABLE_LOCATIONS, null,v);
v.put(MySQLiteHelper.POSITION, "-6.353212, 106.841462");
v.put(MySQLiteHelper.TITLE, "Parkiran Kampus E");
v.put(MySQLiteHelper.SNIPPET, "Kampus Gunadarma yang terletak di Kelapa Dua");
dba.insert(MySQLiteHelper.TABLE_LOCATIONS, null,v);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(MySQLiteHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS" + TABLE_LOCATIONS);
onCreate(db);
}
}
This is MyMarker.java code
import com.google.android.gms.maps.model.LatLng;
public class MyMarker {
private long id;
private String title;
private String snippet;
private String position;
private LatLng poLatLng;
public MyMarker() {
}
public MyMarker(long id, String title, String snippet, LatLng poLatLng) {
this.id = id;
this.title = title;
this.snippet = snippet;
this.poLatLng = poLatLng;
this.position = String.valueOf(poLatLng.latitude) + " " + String.valueOf(poLatLng.longitude);
}
public MyMarker(String title, String snippet, LatLng poLatLng){
this.title = title;
this.snippet = snippet;
this.poLatLng = poLatLng;
this.position = String.valueOf(poLatLng.latitude) + " " + String.valueOf(poLatLng.longitude);
}
/**
* #return the id
*/
public long getId() {
return id;
}
/**
* #param id the id to set
*/
public void setId(long id) {
this.id = id;
}
/**
* #return the title
*/
public String getTitle() {
return title;
}
/**
* #param title the title to set
*/
public void setTitle(String title) {
this.title = title;
}
/**
* #return the snippet
*/
public String getSnippet() {
return snippet;
}
/**
* #param snippet the snippet to set
*/
public void setSnippet(String snippet) {
this.snippet = snippet;
}
/**
* #return the position
*/
public String getPosition() {
return position;
}
/**
* #param position the position to set
*/
public void setPosition(LatLng poLatLng) {
this.poLatLng = poLatLng;
this.position = String.valueOf(poLatLng.latitude) + " " + String.valueOf(poLatLng.longitude);
}
/**
* #param position needs to be Latitude</space/>Longitude
*/
public void setPosition(String position) {
this.position = position;
String[] pos = position.split(" ");
this.poLatLng = new LatLng(Double.valueOf(pos[0]), Double.valueOf(pos[1]));
}
public LatLng getLatLng (){
return poLatLng;
}
}
This is my Dataparkir.java code
import android.content.ContentValues;
import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import java.util.ArrayList;
import java.util.List;
import android.database.Cursor;
import android.util.Log;
public class Dataparkir {
private SQLiteDatabase db;
private MySQLiteHelper dbhelper;
// String id, String title, String snippet, String position
private String[] allColumns = {
MySQLiteHelper.TITLE,
MySQLiteHelper.SNIPPET,
MySQLiteHelper.POSITION };
public Dataparkir(Context context){
dbhelper = new MySQLiteHelper(context);
}
public void open() throws SQLException{
db = dbhelper.getWritableDatabase();
}
public void close(){
dbhelper.close();
}
public void addMarker(MyMarker m){
ContentValues v = new ContentValues();
v.put(MySQLiteHelper.TITLE, m.getTitle());
v.put(MySQLiteHelper.SNIPPET, m.getSnippet());
v.put(MySQLiteHelper.POSITION, m.getPosition());
long insertId = db.insert(MySQLiteHelper.TABLE_LOCATIONS, null,
v);
Cursor cursor = db.query(MySQLiteHelper.TABLE_LOCATIONS,
allColumns, MySQLiteHelper.ID_COL + " = " + insertId, null,
null, null, null);
cursor.moveToFirst();
MyMarker mm = cursorToMarker(cursor);
cursor.close();
}
public List<MyMarker> getMyMarkers(){
List<MyMarker> markers = new ArrayList<MyMarker>();
Cursor cursor = db.query(MySQLiteHelper.TABLE_LOCATIONS,
allColumns, null, null, null, null, null);
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
MyMarker mm = cursorToMarker(cursor);
markers.add(mm);
cursor.moveToNext();
}
cursor.close();
return markers;
}
private MyMarker cursorToMarker(Cursor cursor) {
MyMarker mm = new MyMarker();
mm.setTitle(cursor.getString(0));
mm.setSnippet(cursor.getString(1));
mm.setPosition(cursor.getString(2));
return mm;
}
}
And this is my MainActivity.java
import java.util.List;
import android.content.Context;
import android.content.IntentSender;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptor;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.LatLng;
public class MainActivity extends FragmentActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener,
com.google.android.gms.location.LocationListener {
public static final String TAG = MainActivity.class.getSimpleName();
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;
private GoogleMap googleMap;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private LocationManager locationManager;
private Criteria criteria;
private Location location;
private SQLiteDatabase db;
private Context context = this;
private Dataparkir data = new Dataparkir(context);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setUpMapIfNeeded();
setUpMap();
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
criteria = new Criteria();
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!= null){
onLocationChanged(location);
}
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
// Create the LocationRequest object
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(10 * 1000) // 10 seconds, in milliseconds
.setFastestInterval(1 * 1000); // 1 second, in milliseconds
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
// Enable / Disable Toolbar
googleMap.getUiSettings().setMapToolbarEnabled(false);
}
#Override
protected void onResume() {
super.onResume();
setUpMapIfNeeded();
googleApiClient.connect();
}
#Override
protected void onPause() {
super.onPause();
if (googleApiClient.isConnected()) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, (com.google.android.gms.location.LocationListener) this);
googleApiClient.disconnect();
}
}
private void setUpMapIfNeeded() {
// Do a null check to confirm that we have not already instantiated the map.
if (googleMap == null) {
// Try to obtain the map from the SupportMapFragment.
googleMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
// Check if we were successful in obtaining the map.
if (googleMap != null) {
setUpMap();
}
}
}
private void setUpMap() {
try {
data.open();
} catch (SQLException e) {
}
List<MyMarker> markers = data.getMyMarkers();
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.marker);
for (int i = 0; i < markers.size(); i++) {
googleMap.addMarker(new MarkerOptions()
.title(markers.get(i).getTitle())
.snippet(markers.get(i).getSnippet())
.position(markers.get(i).getLatLng())
.icon(icon));
}
data.close();
}
private void handleNewLocation(Location location) {
Log.d(TAG, location.toString());
double currentLatitude = location.getLatitude();
double currentLongitude = location.getLongitude();
LatLng latLng = new LatLng(currentLatitude, currentLongitude);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng, 15));
googleMap.animateCamera(CameraUpdateFactory.zoomIn());
googleMap.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng) // Sets the center of the map to Mountain View
.zoom(15) // Sets the zoom
.build(); // Creates a CameraPosition from the builder
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
}
#Override
public void onConnected(Bundle bundle) {
location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (location == null) {
LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient, locationRequest, (com.google.android.gms.location.LocationListener) this);
}
else {
handleNewLocation(location);
}
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
if (connectionResult.hasResolution()) {
try {
// Start an Activity that tries to resolve the error
connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
// Thrown if Google Play services canceled the original
// PendingIntent
}
catch (IntentSender.SendIntentException e) {
// Log the error
e.printStackTrace();
}
}
else {
Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
}
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#Override
public void onDestroy() {
super.onDestroy();
db.close();
}
}

You miss a column name in the creation of your table:
private static final String DATABASE_CREATE = "create table "
+ TABLE_LOCATIONS + "(" + ID_COL
+ " integer primary key autoincrement, " // + COLUMN_NAME
+ " text, "+ TITLE
+ " text, " + SNIPPET
+ " text, " + POSITION
+ " text);";
I marked where you miss a column name.
Please note that your way of writing that code is confusing.
It would be more readable like this:
private static final String DATABASE_CREATE =
"CREATE TABLE " + TABLE_LOCATIONS + " (" +
ID_COL + " integer primary key autoincrement, " +
COLUMN_NAME + " text, " + // The missing column name
TITLE + " text, " +
SNIPPET + " text, " +
POSITION + " text)";

Related

setAdapter() crashes android app in android studio

I'm following this tutorial (https://www.youtube.com/watch?v=hDSVInZ2JCs&t=3615s&ab_channel=SoftwareandProgrammingwithProfessorSluiter)
Everything works great, until I try this line of code :
lv_productList.setAdapter(productArrayAdapter);
then the app crashes. I've looked online and tried a bunch of stuff but I'm super stuck
Here's the problem area
btn_viewAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this);
List<ProductModel> all = dataBaseHelper.getAll();
ArrayAdapter productArrayAdapter = new ArrayAdapter<ProductModel>(MainActivity.this, android.R.layout.simple_list_item_1, all);
lv_productList.setAdapter(productArrayAdapter);
Toast.makeText(MainActivity.this, all.toString(), Toast.LENGTH_SHORT).show();
}
});
here's my full code
MainActivity.java
package com.example.sqldemo;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.List;
public class MainActivity extends AppCompatActivity {
//reference to all buttons and controls on the layout
Button btn_add, btn_viewAll;
EditText et_name, et_number;
ListView lv_productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_add = findViewById(R.id.btn_add);
btn_viewAll = findViewById(R.id.btn_viewAll);
et_name = findViewById(R.id.et_name);
et_number = findViewById(R.id.et_number);
btn_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ProductModel productModel;
try {
productModel = new ProductModel(-1, et_name.getText().toString(), Integer.parseInt(et_number.getText().toString()));
Toast.makeText(MainActivity.this, productModel.toString(), Toast.LENGTH_SHORT).show();
}
catch(Exception err) {
Toast.makeText(MainActivity.this, "Error creating product", Toast.LENGTH_SHORT).show();
productModel = new ProductModel(-1, "error", 0);
}
DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this);
boolean success = dataBaseHelper.addOne(productModel);
Toast.makeText(MainActivity.this, "Success! Product has been added to the database :)", Toast.LENGTH_SHORT).show();
}
});
btn_viewAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DataBaseHelper dataBaseHelper = new DataBaseHelper(MainActivity.this);
List<ProductModel> all = dataBaseHelper.getAll();
ArrayAdapter productArrayAdapter = new ArrayAdapter<ProductModel>(MainActivity.this, android.R.layout.simple_list_item_1, all);
lv_productList.setAdapter(productArrayAdapter);
Toast.makeText(MainActivity.this, all.toString(), Toast.LENGTH_SHORT).show();
}
});
}
}
DataBaseHelper.java
package com.example.sqldemo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import androidx.annotation.Nullable;
import java.util.ArrayList;
import java.util.List;
public class DataBaseHelper extends SQLiteOpenHelper {
public static final String PRODUCT_TABLE = "PRODUCT_TABLE";
public static final String COLUMN_PRODUCT_NAME = "PRODUCT_NAME";
public static final String COLUMN_PRODUCT_NUMBER = "PRODUCT_AGE";
public static final String COLUMN_ID = "ID";
public DataBaseHelper(#Nullable Context context) {
super(context, "Products.db", null, 1);
}
//this is called the first item a database is accessed. used to create a new database
#Override
public void onCreate(SQLiteDatabase db) {
String createTableStatement = "CREATE TABLE " + PRODUCT_TABLE + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_PRODUCT_NAME + " TEXT, " + COLUMN_PRODUCT_NUMBER + " INT)";
db.execSQL(createTableStatement);
}
//this is called if the database version number changes. It prevents previous users apps from breaking when the database is updated
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public boolean addOne(ProductModel productModel) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues cv = new ContentValues();
cv.put(COLUMN_PRODUCT_NAME, productModel.getName());
cv.put(COLUMN_PRODUCT_NUMBER, productModel.getNumber());
//long insert returns positive in data insertion was successful, and negative if it was not
long insert = db.insert(PRODUCT_TABLE, null, cv);
if (insert == -1) {
return false;
}
else {
return true;
}
}
public List<ProductModel> getAll() {
List<ProductModel> returnList = new ArrayList<>();
// get data from the database
String queryString = "SELECT * FROM " + PRODUCT_TABLE;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(queryString, null);
//move the cursor to the first set of data and check if anything was returned
if (cursor.moveToFirst()) {
// loop through the cursor (result set) and create new product objects. Put them into the return list (defined above)
do {
int productID = cursor.getInt(0);
String productName = cursor.getString(1);
int productNumber = cursor.getInt(2);
ProductModel newProduct = new ProductModel(productID, productName, productNumber);
returnList.add(newProduct);
} while (cursor.moveToNext());
}
else {
//if no results from database, don't add anything to the list.
}
cursor.close();
db.close();
return returnList;
}
}
ProductModel.java
package com.example.sqldemo;
//declare a new public class/object with 3 variables
public class ProductModel {
private int id;
private String name;
private int number;
//constructor
public ProductModel(int id, String name, int number) {
this.id = id;
this.name = name;
this.number = number;
}
public ProductModel() {
}
// toString is necessary for printing the contents of a class object
#Override
public String toString() {
return "ProductModel{" +
"id=" + id +
", name='" + name + '\'' +
", number=" + number +
'}';
}
//getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
> Blockquote
You can simply change RecyclerView to ListView.
Or
if you want to use RecyclerView, you have to create a custom Recyclerview Adapter.
Here a Beginner friendly Guide: https://medium.com/#suhanshupatel/recyclerview-in-android-for-beginner-cfbc132a0dec

Program crashes the moment I start typing in the search bar

When I run the program, everything looks fine but the moment I type a letter in the search bar, the program crashes immediately.It mostly shows Exceptions at searchBar() function in LibraryDbAdapter class and at onQueryTextChange(String newText) in SearchViewActivity class.I am using ListView too.
LibraryDbAdapter.java
package com.example.waheed.library;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
/**
* Created by Waheed on 6/30/17.
*/
public class LibraryDbAdapter {
public static final String KEY_ROWID = "rowid";
//public static final String KEY_LIBRARY = "library";
public static final String KEY_BOOKNAME = "bookname";
public static final String KEY_BOOKAUTHOR = "bookauthor";
public static final String KEY_STORENAME = "storename";
public static final String KEY_STOREADDRESS = "storeaddress";
public static final String KEY_STORELAT = "storelat";
public static final String KEY_STORELONG = "storelong";
public static final String KEY_SEARCH = "searchData";
private static final String TAG = "LibraryDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
private static final String DATABASE_NAME = "LibraryData";
private static final String FTS_VIRTUAL_TABLE = "LibraryInfo";
private static final int DATABASE_VERSION = 1;
//Create a FTS3 Virtual Table for fast searches
private static final String DATABASE_CREATE =
"CREATE VIRTUAL TABLE " + FTS_VIRTUAL_TABLE + " USING fts3(" +
// KEY_LIBRARY + "," +
KEY_BOOKNAME + "," +
KEY_BOOKAUTHOR + "," +
KEY_STORENAME + "," +
KEY_STOREADDRESS + "," +
KEY_STORELAT + "," +
KEY_STORELONG + "," +
KEY_SEARCH + "," +
" UNIQUE (" + KEY_BOOKNAME + "));";
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
Log.w(TAG, DATABASE_CREATE);
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + FTS_VIRTUAL_TABLE);
onCreate(db);
}
}
public LibraryDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public LibraryDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
if (mDbHelper != null) {
mDbHelper.close();
}
}
public long createLibrary( String bookname, String bookauthor, String storename, String storeaddress, String storelat, String storelong) {
ContentValues initialValues = new ContentValues();
String searchValue = bookname;
//initialValues.put(KEY_LIBRARY, library);
initialValues.put(KEY_BOOKNAME, bookname);
initialValues.put(KEY_BOOKAUTHOR, bookauthor);
initialValues.put(KEY_STORENAME, storename);
initialValues.put(KEY_STOREADDRESS, storeaddress);
initialValues.put(KEY_STORELAT, storelat);
initialValues.put(KEY_STORELONG, storelong);
initialValues.put(KEY_SEARCH, searchValue);
return mDb.insert(FTS_VIRTUAL_TABLE, null, initialValues);
}
public Cursor searchBook(String inputText) throws SQLException {
Log.w(TAG, inputText);
String query = "SELECT " +
KEY_BOOKNAME +
" from " + FTS_VIRTUAL_TABLE +
" where " + KEY_SEARCH + " MATCH '" + inputText + "';";
Log.w(TAG, query);
Cursor mCursor = mDb.rawQuery(query, null);
if (mCursor != null) {
mCursor.moveToFirst();
}
return mCursor;
}
public boolean deleteAllLibrary() {
int doneDelete = 0;
doneDelete = mDb.delete(FTS_VIRTUAL_TABLE, null, null);
Log.w(TAG, Integer.toString(doneDelete));
return doneDelete > 0;
}
}
SearchViewActivity.java
package com.example.waheed.library;
import java.util.Calendar;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class SearchViewActivity extends Activity implements
SearchView.OnQueryTextListener,
SearchView.OnCloseListener {
private ListView mListView;
private SearchView searchView;
private LibraryDbAdapter mDbHelper;
private TextView inspectionDate;
private TextView bookName;
private TextView bookAuthor;
private TextView storeName;
private TextView storeAddress;
private TextView storeLat;
private TextView storeLong;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
searchView = (SearchView) findViewById(R.id.search);
searchView.setIconifiedByDefault(false);
searchView.setOnQueryTextListener(this);
searchView.setOnCloseListener(this);
mListView = (ListView) findViewById(R.id.list);
inspectionDate = (TextView) findViewById(R.id.inspectionDate);
displayDate();
mDbHelper = new LibraryDbAdapter(this);
mDbHelper.open();
//Clean all Customers
mDbHelper.deleteAllLibrary();
//Add some Customer data as a sample
mDbHelper.createLibrary("How to Win Friends and Influence People", "Dale Carnegie", "Book Centre", " Haider Rd, Rawalpindi 46000", "33.596651", "73.049094");
mDbHelper.createLibrary("The 7 Habits of Highly Effective People", "Stephen Covey", "Idris Book Bank", "Bank Rd, Rawalpindi 46000", "33.595789", "73.052405");
mDbHelper.createLibrary("Think and Grow Rich", "Napoleon Hill", "Students Book Company", "Bank Rd, Rawalpindi 44000", "33.596524", "73.051051");
mDbHelper.createLibrary("Psycho-Cybernetics", "Maxwell Maltz", "Old Book Bank", "Green Super Market, Kashmir Rd, Saddar, Rawalpindi, Punjab", "33.595810", "73.051530");
mDbHelper.createLibrary("How to stop worrying and start living", "Dale Carnegie", "Saeed Book Bank", "F-, Street 7, Islamabad 44000", "33.722446", "73.058763");
mDbHelper.createLibrary("A New Earth", " Eckhart Tolle", "Variety Books", "41-BC, Bank Rd, Saddar, Rawalpindi 46000", "33.597497", "73.049917");
mDbHelper.createLibrary("Blink: The Power of Thinking Without Thinking", "Malcolm Gladwell", "Rehan Book Shop", "Islamabad", "33.689734", "73.031652");
mDbHelper.createLibrary("First Things First", "Stephen Covey", "Idris Book Bank", "Bank Rd, Rawalpindi 46000", "33.595789", "73.052405");
mDbHelper.createLibrary("Emotional Intelligence", "Daniel Goleman", "Book Centre", " Haider Rd, Rawalpindi 46000", "33.596651", "73.049094");
mDbHelper.createLibrary("Anatomy of the Spirit", "Caroline Myss", "Students Book Company", "Bank Rd, Rawalpindi 44000", "33.596524", "73.051051");
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mDbHelper != null) {
mDbHelper.close();
}
}
public boolean onQueryTextChange(String newText) {
showResults(newText + "*");
return false;
}
public boolean onQueryTextSubmit(String query) {
showResults(query + "*");
return false;
}
public boolean onClose() {
showResults("");
return false;
}
private void showResults(String query) {
Cursor cursor = mDbHelper.searchBook((query != null ? query.toString() : "####"));
if (cursor == null) {
//
} else {
// Specify the columns we want to display in the result
String[] from = new String[]{
LibraryDbAdapter.KEY_BOOKNAME,
LibraryDbAdapter.KEY_BOOKAUTHOR,
LibraryDbAdapter.KEY_STORENAME,
LibraryDbAdapter.KEY_STOREADDRESS,
LibraryDbAdapter.KEY_STORELAT,
LibraryDbAdapter.KEY_STORELONG
};
// Specify the Corresponding layout elements where we want the columns to go
int[] to = new int[] { R.id.sbook,
R.id.sauthor,
R.id.sstore,
R.id.sstoreaddress,
R.id.slat,
R.id.slong};
// Create a simple cursor adapter for the definitions and apply them to the ListView
SimpleCursorAdapter books = new SimpleCursorAdapter(this,R.layout.bookresult, cursor, from, to);
mListView.setAdapter(books);
// Define the on-click listener for the list items
mListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Get the cursor, positioned to the corresponding row in the result set
Cursor cursor = (Cursor) mListView.getItemAtPosition(position);
// Get the state's capital from this row in the database.
String Book = cursor.getString(cursor.getColumnIndexOrThrow("Book"));
String Author = cursor.getString(cursor.getColumnIndexOrThrow("Author"));
String Store = cursor.getString(cursor.getColumnIndexOrThrow("Store"));
String storeaddress = cursor.getString(cursor.getColumnIndexOrThrow("storeaddress"));
String lat = cursor.getString(cursor.getColumnIndexOrThrow("lat"));
String lon = cursor.getString(cursor.getColumnIndexOrThrow("lon"));
//Check if the Layout already exists
LinearLayout bookLayout = (LinearLayout)findViewById(R.id.booklayout);
if(bookLayout == null){
//Inflate the Customer Information View
LinearLayout leftLayout = (LinearLayout)findViewById(R.id.rightLayout);
View bookInfo = getLayoutInflater().inflate(R.layout.bookinfo, leftLayout, false);
leftLayout.addView(bookInfo);
}
//Get References to the TextViews
bookName = (TextView) findViewById(R.id.book);
bookAuthor = (TextView) findViewById(R.id.author);
storeName = (TextView) findViewById(R.id.store);
storeAddress = (TextView) findViewById(R.id.storeaddress);
storeLat = (TextView) findViewById(R.id.latitude);
storeLong = (TextView) findViewById(R.id.longitude);
// Update the parent class's TextView
bookName.setText(Book);
bookAuthor.setText(Author);
storeName.setText(Store);
storeAddress.setText(storeaddress);
storeLat.setText(lat);
storeLong.setText(lon);
searchView.setQuery("",true);
}
});
}
}
private void displayDate() {
final Calendar c = Calendar.getInstance();
inspectionDate.setText(
new StringBuilder()
// Month is 0 based so add 1
.append(c.get(Calendar.MONTH) + 1).append("/")
.append(c.get(Calendar.DAY_OF_MONTH)).append("/")
.append(c.get(Calendar.YEAR)).append(" "));
}
}

Android : Unable to Access Function From Other Class (Service)

I am a php developer learning my way around android development.
I have a dbhelper helper class which has the below coding.
package com.example.bootstart;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DBHelper extends SQLiteOpenHelper {
private static final String LOGTAG = "THEDBHELPER";
private static final String DATABASE_NAME = "geolocation.db";
private static final int DATABASE_VERSION = 1;
private static final String TABLE_LOCATIONS = "locations";
private static final String COLUMN_ID = "id";
private static final String COLUMN_welawa = "welawa";
private static final String COLUMN_lati = "latitude";
private static final String COLUMN_longi = "longitude";
private static final String TABLE_CREATE = "CREATE TABLE " + TABLE_LOCATIONS + " ("
+ COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_welawa + " TEXT, " + COLUMN_lati
+ " TEXT, " + COLUMN_longi + " TEXT)";
public DBHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(TABLE_CREATE);
Log.i(LOGTAG, "TABLE HAS BEEN CREATED");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS " + TABLE_LOCATIONS);
onCreate(db);
}
public void insert_records(String lati, String longi) {
SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
Long tsLong = System.currentTimeMillis()/1000;
String ts = tsLong.toString();
sqLiteDatabase.execSQL("INSERT INTO " +
TABLE_LOCATIONS +
"(welawa,latitude,longitude) Values (" + ts + ","+ lati +"," + longi + ");");
Log.i(LOGTAG, "Data Entered");
}
}
However, when I try to access the insert_records function from another class by using
dbhelper = new DBHelper(this); //I can't even get the insert_records function in the suggestions in the drop here OR DBHelper dbh= new DBHelper(this); dbh.insert_records("12.2323", "25.22222"); lovely eclipse throws the error message The constructor DBHelper(new Runnable(){}) is undefined.
I simply have no idea on how to access my function.
I have
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
defined at the top of the class I am trying to access from.
Below is the class im trying to access the dbhelper function from.
package com.example.bootstart;
import android.app.Service;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class GPSService extends Service {
SQLiteOpenHelper dbhelper;
SQLiteDatabase database;
GPSTracker gps;
private int mInterval = 10000;
private Handler mHandler;
#Override
public void onCreate()
{
Log.v("StartServiceAtBoot", "StartAtBootService Created");
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent,int flags,int startId){
//Service Will Start until stopped
mHandler = new Handler();
Toast.makeText(this,"Service Started",Toast.LENGTH_LONG).show();
mStatusChecker.run();
return START_STICKY;
}
public void onDestroy(){
super.onDestroy();
Toast.makeText(this,"Service Stopped",Toast.LENGTH_LONG).show();
}
Runnable mStatusChecker = new Runnable() {
#Override
public void run() {
gps = new GPSTracker(GPSService.this);
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
//new AsyncSendData().execute("http://www.accuretta.lk/nv/maps/track_post"); Sending Info Code Is Working Fine
DBHelper dbh= new DBHelper(this);
dbh.insert_records("12.2323", "25.22222");
dbh.insert_records("55.2222", "11.256");
}
mHandler.postDelayed(mStatusChecker, mInterval);
}
};
void startRepeatingTask() {
mStatusChecker.run();
}
void stopRepeatingTask() {
mHandler.removeCallbacks(mStatusChecker);
}
}
I haven't seen any runnables created in any of the tutorials.
Your help is greatly appreciated.
You are passing the wrong parameter type to the DBHelper constructor. You have to do like this
DBHelper dbh= new DBHelper(getApplicationContext());
inside your void run() method of the mStatusChecker Runnable instance. if you look into the error message, you can understand that compiler is not able to find an appropriate constructor for DBHelper class with parameter type Runnable. that's why this error is thrown by eclipse.
Hope you understand now.

Content of the result of aggregation query not returned

I am a begineer and I want to allow just one user to sign up as per the demand of my project.
The SIGNUP.java is meant to accomplish it using DbHelper.java but things work fine for
c.getCount()
but not for
Integer.parseInt(c.getString(0))
SIGNUP.java reads:
package com.bishal.android.taskmanager;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class SIGNUP extends Activity {
Button register;
private EditText etName;
private EditText etEmail;
//private EditText etUsername;
private EditText etPassword;
private DbHelper dbhelper;
AlertDialogManager alert = new AlertDialogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.signup);
dbhelper=new DbHelper(this);
etName=(EditText)findViewById(R.id.edit_name);
etEmail=(EditText)findViewById(R.id.edit_email);
etPassword=(EditText)findViewById(R.id.edit_signup_password);
register=(Button)findViewById(R.id.signup);
final boolean bregister=(dbhelper.NoOfUser()==0)?true:false;
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
//String UserNameValue=etUsername.getText().toString();
String NameValue=etName.getText().toString();
String EmailValue=etEmail.getText().toString();
String PasswordValue=etPassword.getText().toString();
//Toast.makeText(SIGNUP.this,dbhelper.ThereIsUser(), Toast.LENGTH_LONG).show();
if (bregister){
ACCOUNT_INFO account=new ACCOUNT_INFO(NameValue,EmailValue,PasswordValue);
if(NameValue.trim().length()>0 && EmailValue.trim().length() > 0 && PasswordValue.trim().length() >0){
if(dbhelper.eMailValidation(EmailValue)){
if(dbhelper.validateregister(EmailValue)){
dbhelper.addAccount(account);
Toast.makeText(SIGNUP.this, "Your account has been sucessfully created.", Toast.LENGTH_LONG).show();
}
else{
alert.showAlertDialog(SIGNUP.this, "Signup failed..", "Username/Email already exists.", false);
}
}
else{
alert.showAlertDialog(SIGNUP.this,"Signup failed..", "Email address is not in such form.", false);
}
}
else{
alert.showAlertDialog(SIGNUP.this, "Signup failed..", "Please enter empty fields.", false);
}
}
}
});
}
}
DbHelper.java reads(why 'count' is not returned as count of number of rows in table?):
package com.bishal.android.taskmanager;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
//import android.widget.Toast;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class DbHelper extends SQLiteOpenHelper{
private static final String TAG=DbHelper.class.getSimpleName();
public static final String DB_NAME="Store Account.db";
public static final int DB_VERSION=1;
public static final String TABLE="Account_Info";
public static final String COL_ID="Id"; //special for ID
public static final String COL_NAME="Name";
public static final String COL_EMAIL="Email";
//public static final String COL_UNAME="Username";
public static final String COL_PASSWORD="Password";
public DbHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
String CREATE_ACCOUNT_INFORMATION = "CREATE TABLE " + TABLE + "("
+ COL_ID + " INTEGER PRIMARY KEY," + COL_NAME + " String,"
+ COL_EMAIL + " String," + COL_PASSWORD + " String" + ")";
Log.d(TAG, "onCreate sql: "+CREATE_ACCOUNT_INFORMATION);
db.execSQL(CREATE_ACCOUNT_INFORMATION);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("Drop Table If Exists " + TABLE);
Log.d(TAG,"onUpdate dropped table "+ TABLE);
onCreate(db);
}
void addAccount(ACCOUNT_INFO account){
SQLiteDatabase db=this.getWritableDatabase();
ContentValues values=new ContentValues();
values.put(COL_NAME,account.getNAME());
values.put(COL_EMAIL,account.getEMAIL());
//values.put(COL_UNAME, account.getUSERNAME());
values.put(COL_PASSWORD, account.getPASSWORD());
db.insert(TABLE, null, values);
db.close();
}
public boolean validateuser(String email,String password){
Cursor c=getReadableDatabase().rawQuery("SELECT * FROM " + TABLE + " WHERE "
+ COL_EMAIL + "='" + email +"'AND "+COL_PASSWORD+"='" + password+"'" , null);
if(c.getCount()>0)
return true;
else
return false;
}
public boolean validateregister(String email){
Cursor c=getReadableDatabase().rawQuery("SELECT * FROM " + TABLE + " WHERE "
+ COL_EMAIL + "='" + email+"'" , null);
if(c.getCount()>0)
return false;
else
return true;
}
public boolean eMailValidation(String emailValue) {
final String EMAIL_PATTERN =
"^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*#"
+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
Pattern pattern=Pattern.compile(EMAIL_PATTERN);;
Matcher matcher;
matcher = pattern.matcher(emailValue);
return matcher.matches();
}
public int NoOfUser() {
Cursor c=getReadableDatabase().rawQuery("SELECT count(*) FROM " + TABLE, null);
int count=Integer.parseInt(c.getString(0));
return count;
}
}

Android populate string array from SQLite database

I have tried to adapt the Google notepad tutorial ( http://developer.android.com/resources/tutorials/notepad/index.html ) for using SQLite databases to store GPS co-ords when the user tags current location. I've had no trouble getting the location added to the database but currently having trouble populating an array from the database in order to draw the locations on the map
private void fillData() {
/**
* Get all of the geotags from the database and populate the strarrlatitude and strarrlongitude arrays
* Also calls 'drawpins' to draw the geotags on the map
*/
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
strarrlatitude = new String[] { LocationsDbAdapter.COL_LATITUDE};
System.out.println(strarrlatitude);
strarrlongitude = new String[] { LocationsDbAdapter.COL_LONGITUDE };
drawpins();
}
I'm using a separate class called LocationsDbAdapter for handling database management as demonstrated in the notepad tutorial. The COL_LATITUDE and COL_LONGITUDE variables point to the column titles.
I've used a for loop to determine that nothing seems to be going into the strarrlatitude array but using the SQLite CLI I've checked that the database is being determined
Any help would be most gratefully received - if any more information is required I'll upload it as quick as possible
Many thanks
EDIT: Added the main two classes below for extra reference. I was trying not to overload with too much information but that was an error in judgement.
package com.nick.locationapp;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.text.AlteredCharSequence;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.nick.androidsoar.R;
public class AndroidSoarActivity extends MapActivity {
/** Called when the activity is first created. */
LinearLayout linearLayout;
MapView mapView;
TextView LocationText;
double dbllatitude;
double dbllongitude;
double dblaltitude;
String debugstring;
String strlatitude = "0";
String strlongitude = "0";
String[] strarrlatitude;
String[] strarrlongitude;
String[] strarrlatitude1 = {"50.0","40.0","43.0","100.0"};
String[] strarrlongitude1 = {"12.4","123.4","60.2","72.0"};
Double[] debuglat = {50.0,40.0,43.0,100.0};
Double[] debuglong = {12.4,123.4,60.2,72.0};
Double dbllat;
Double dbllong;
int intlatitude;
int intlongitude;
private LocationsDbAdapter mDbHelper;
public static final int INSERT_ID = Menu.FIRST;
List<Overlay> mapOverlays;
Drawable drawable;
HelloItemizedOverlay itemizedOverlay;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Identifies the textview as variable 'LocationText'
LocationText = (TextView)findViewById(R.id.locationtext);
//mDbHelper points to the LocationsDbAdapter class used for handling the database
mDbHelper = new LocationsDbAdapter (this);
mDbHelper.open();
//defines the mapview as variable 'mapView' and enables zoom controls
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
//points variable 'drawable' to the icon resource of a pushpin, used for marking tags on the map
drawable = this.getResources().getDrawable(R.drawable.pushpin);
//Adds a current location overlay to the map 'mapView' and turns on the map's compass
MyLocationOverlay myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableCompass();
mapView.postInvalidate();
/**
* Code required to receive gps location. Activates GPS provider, and is set to update only after
* at least 10 seconds and a position change of at least 10 metres
*/
LocationListener locationListener = new MyLocationListener();
//setting up the location manager
LocationManager locman = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locman.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000, 10, locationListener);
//fillData();
}
/**
* Generates the menu from the resource 'mainmenu.xml'
*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
/**
* Code to run depending on the menu button pressed
*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.new_tag:
createTag();
fillData();
//Toast.makeText(getApplicationContext(), "geotag added to db", Toast.LENGTH_SHORT).show();
return true;
case R.id.draw_pins:
//fillData();
drawpins();
return true;
case R.id.create_tag:
Intent intent = new Intent(AndroidSoarActivity.this, TagCreate.class);
startActivity(intent);
}
return super.onOptionsItemSelected(item);
}
/**
* Create a new geotag pin from the current location
*/
private void createTag() {
//String titleName = "title " + titleNumber++;
mDbHelper.createNote(strlatitude, strlongitude);
Toast.makeText(getApplicationContext(), "geotag of lat: "+dbllatitude+" long: "+dbllongitude+" added to db ", Toast.LENGTH_SHORT).show();
fillData();
}
private void fillData() {
/**
* Get all of the geotags from the database and populate the strarrlatitude and strarrlongitude arrays
* Also calls 'drawpins' to draw the geotags on the map
*/
System.out.println("Fetching data");
Cursor c = mDbHelper.fetchAllNotes();
System.out.println(c.toString());
startManagingCursor(c);
strarrlatitude = new String[] { LocationsDbAdapter.COL_LATITUDE };
//System.out.println(strarrlatitude);
strarrlongitude = new String[] { LocationsDbAdapter.COL_LONGITUDE };
}
/**
* Creates an array of geopoints, pulling the locations from strarrlatitude and strarrlongitude
* and creates a mapview overlay using the geopoints
*/
private void drawpins() {
itemizedOverlay = new HelloItemizedOverlay(drawable);
GeoPoint[] mapPoints = new GeoPoint[strarrlatitude.length];
OverlayItem[] mapItems = new OverlayItem[strarrlatitude.length];
for(int i=1; i<strarrlatitude.length;i++){
dbllat = Double.parseDouble(strarrlatitude[i]);
dbllong = Double.parseDouble(strarrlongitude[i]);
System.out.println(i);
mapPoints[i] = new GeoPoint((int) (dbllat * 1E6), (int) (dbllong * 1E6));
mapItems[i] = new OverlayItem(mapPoints[i], "", "");
itemizedOverlay.addOverlay(mapItems[i]);
mapOverlays.add(itemizedOverlay);
}
}
private final class MyLocationListener implements LocationListener {
/**
* Code to run when the listener receives a new location
*/
#Override
public void onLocationChanged(Location locFromGps) {
Toast.makeText(getApplicationContext(), "Location changed, Lat: "+locFromGps.getLatitude()+" Long: "+ locFromGps.getLongitude(), Toast.LENGTH_SHORT).show();
//LocationText.setText("Your Location: Latitude " +locFromGps.getLatitude() + " Longitude: " +locFromGps.getLongitude());
dbllatitude = locFromGps.getLatitude();
dbllongitude = locFromGps.getLongitude();
dblaltitude = locFromGps.getAltitude();
strlatitude = Double.toString(dbllatitude);
strlongitude = Double.toString(dbllongitude);
dblaltitude = (dblaltitude / 0.3048);
LocationText.setText("Your Location: Latitude " + dbllatitude + " Longitude: " +dbllongitude + " Altitude " + dblaltitude);
}
#Override
public void onProviderDisabled(String provider) {
// called when the GPS provider is turned off (user turning off the GPS on the phone)
}
#Override
public void onProviderEnabled(String provider) {
// called when the GPS provider is turned on (user turning on the GPS on the phone)
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// called when the status of the GPS provider changes
}
}
}
/**
* Following class has been adapted from Google's Android Notepad tutorial: http://developer.android.com/resources/tutorials/notepad/index.html
*
*/
package com.nick.locationapp;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class LocationsDbAdapter {
public static final String COL_LATITUDE = "latitude";
public static final String COL_LONGITUDE = "longitude";
//public static final String KEY_NOTE = "note";
public static final String COL_TITLE = "title";
public static final String COL_ROWID = "_id";
//public static final String TABLE_LOC = "locations";
private static final String TAG = "LocationsDbAdapter";
private DatabaseHelper mDbHelper;
private SQLiteDatabase mDb;
/**
* Database creation sql statement
*/
private static final String DATABASE_CREATE =
"CREATE TABLE locations (_id integer primary key autoincrement, "
+ "latitude text not null, longitude text not null);";
private static final String DATABASE_NAME = "data";
private static final String DATABASE_TABLE = "locations";
private static final int DATABASE_VERSION = 1;
private final Context mCtx;
private static class DatabaseHelper extends SQLiteOpenHelper {
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
/**
* SQL for creating the table. Table and column names are declared as variables
*/
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE "+DATABASE_TABLE+" ("+COL_ROWID+ " INTEGER PRIMARY KEY AUTOINCREMENT, "+COL_LATITUDE+ " TEXT, "+COL_LONGITUDE+" TEXT "+COL_TITLE+" TEXT)");
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS location");
onCreate(db);
}
}
public LocationsDbAdapter(Context ctx) {
this.mCtx = ctx;
}
public LocationsDbAdapter open() throws SQLException {
mDbHelper = new DatabaseHelper(mCtx);
mDb = mDbHelper.getWritableDatabase();
return this;
}
public void close() {
mDbHelper.close();
}
/**
* Code for adding latitude and longitude into the database
* #param latitude
* #param longitude
* #return
*/
public long createNote(String latitude, String longitude) {
ContentValues geotagValues = new ContentValues();
geotagValues.put(COL_LATITUDE, latitude);
geotagValues.put(COL_LONGITUDE, longitude);
//geotagValues.put(COL_TITLE, title);
return mDb.insert(DATABASE_TABLE, null, geotagValues);
}
/**
* Query to return all data
* #return
*/
public Cursor fetchAllNotes() {
return mDb.query(DATABASE_TABLE, new String[] {COL_ROWID, COL_LATITUDE, COL_LONGITUDE}, null, null, null, null, null);
}
}
*
public void getData()
{
List<String> labels = new ArrayList<String>();
placeData = new PlaceDataSQL(MainActivity.this);
String selectQuery = "SELECT * FROM xmlTable;";
SQLiteDatabase db = placeData.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
{
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
labels.add(cursor.getString(1));
Log.i("imagespath",arr[i]);
i++;
} while (cursor.moveToNext());
}
cursor.close();enter code here
db.close();
}
}
*

Categories