在本文中,我们将为您详细介绍Android错误从LocationListener类将位置数据写入SQLite数据库的相关知识,此外,我们还会提供一些关于AndroidExpandableListVie
在本文中,我们将为您详细介绍Android错误从LocationListener类将位置数据写入SQLite数据库的相关知识,此外,我们还会提供一些关于Android ExpandableListView和SQLite数据库、Android GPS Location with Listener、Android Location LocationListener始终调用onProviderDisabled、android SQLite使用SQLiteOpenHelper类对数据库进行操作的有用信息。
本文目录一览:- Android错误从LocationListener类将位置数据写入SQLite数据库
- Android ExpandableListView和SQLite数据库
- Android GPS Location with Listener
- Android Location LocationListener始终调用onProviderDisabled
- android SQLite使用SQLiteOpenHelper类对数据库进行操作
Android错误从LocationListener类将位置数据写入SQLite数据库
@Override public void onLocationChanged(Location loc) {//Spits out single location for current disconnect System.out.println("location equals "+loc); latitude=Double.toString(loc.getLatitude()); longitude=Double.toString(loc.getLongitude()); writetoDb(MyLocListener.this,latitude,longitude); man.removeUpdates(listener);//Stops location manager from listening for updates listener=null; man=null; } public void writetoDb(Context context,String latitude,String longitude){ db=new DbAdapter(context); db.openToWrite(); db.deleteall(); db.insert(latitude); db.insert(longitude); db.close(); }
但这没用,每次都会在db.openToWrite()行上给我一个nullPointerException. getApplicationContext()在这里也不起作用.
我现在修改它以在一个线程中写入DB:
@Override public void onLocationChanged(Location loc) {//Spits out single location for current disconnect System.out.println("location equals "+loc); latitude=Double.toString(loc.getLatitude()); longitude=Double.toString(loc.getLongitude()); Runnable runner=new SaveLocation(latitude,longitude); new Thread(runner).start(); man.removeUpdates(listener);//Stops location manager from listening for updates listener=null; man=null; } public class SaveLocation implements Runnable{ String latitude; String longitude; // DbAdapter db; public SaveLocation(String latitude,String longitude){ this.latitude=latitude; this.longitude=longitude; } @Override public void run() { db.openToWrite(); db.deleteall(); db.insert(latitude); db.insert(longitude); db.close(); } }
我在onCreate()方法中初始化数据库为:
public class MyLocListener extends Service implements LocationListener{ static LocationManager man; static LocationListener listener; static Location location; public DbAdapter db; @Override public void onCreate() { super.onCreate(); this.db=new DbAdapter(MyLocListener.this); }
但是现在,第二次尝试一直给我一个更加精简的错误,但它仍然在我试图打开数据库可写的行上出错.行MyLocListener.java:92引用行db.openToWrite();
错误是:
05-30 15:35:19.698: W/dalvikvm(4557): threadid=9: thread exiting with uncaught exception (group=0x4001d7e0) 05-30 15:35:19.706: E/AndroidRuntime(4557): FATAL EXCEPTION: Thread-10 05-30 15:35:19.706: E/AndroidRuntime(4557): java.lang.NullPointerException 05-30 15:35:19.706: E/AndroidRuntime(4557): at com.phonehalo.proto.MyLocListener$SaveLocation.run(MyLocListener.java:92) 05-30 15:35:19.706: E/AndroidRuntime(4557): at java.lang.Thread.run(Thread.java:1096)
解决方法
Android ExpandableListView和SQLite数据库
任何人都可以给我一个简单的想法,因为我是Android的新手,所有教程都很难
这是我的数据库:
public void onCreate(sqliteDatabase db) { db.execsql("create table if not exists rooms ( id_room integer primary key autoincrement," + "name_room text not null" + ");"); db.execsql("create table if not exists devices ( id_device integer primary key autoincrement," + "name_device text not null," + "state_device text not null," + "id_room references rooms" + ");"); }
解决方法
db helper类中需要两个方法来收集所需的游标.
public Cursor fetchGroup() { String query = "SELECT * FROM rooms" return mDb.rawQuery(query,null); } public Cursor fetchChildren(String room) { String query = "SELECT * FROM devices WHERE id_room = '" + room + "'"; return mDb.rawQuery(query,null); }
然后你需要设置你的适配器(在你的活动中):
public class Myexpandablelistadapter extends SimpleCursorTreeAdapter { public Myexpandablelistadapter(Cursor cursor,Context context,int groupLayout,int childLayout,String[] groupFrom,int[] groupTo,String[] childrenFrom,int[] childrenTo) { super(context,cursor,groupLayout,groupFrom,groupTo,childLayout,childrenFrom,childrenTo); } } @Override protected Cursor getChildrenCursor(Cursor groupCursor) { Cursor childCursor = mDbHelper.fetchChildren(groupCursor.getString(groupCursor.getColumnIndex("id_room")); getActivity().startManagingCursor(childCursor); childCursor.movetoFirst(); return childCursor; } }
最后调用适配器并将其设置到列表中(在您的活动中):
private void fillData() { mGroupsCursor = mDbHelper.fetchGroup(); getActivity().startManagingCursor(mGroupsCursor); mGroupsCursor.movetoFirst(); ExpandableListView elv = (ExpandableListView) getActivity().findViewById(android.R.id.list); mAdapter = new Myexpandablelistadapter(mGroupsCursor,getActivity(),R.layout.rowlayout_expgroup,// Your row layout for a group R.layout.rowlayout_itemlist_exp,// Your row layout for a child new String[] { "id_room" },// Field(s) to use from group cursor new int[] { android.R.id.room },// Widget ids to put group data into new String[] { "name_device","state_device" },// Field(s) to use from child cursors new int[] { R.id.device,R.id.state }); // Widget ids to put child data into lv.setAdapter(mAdapter); // set the list adapter. } }
希望这可以帮助!
编辑
它应该像这样聚集在一起:
public class List_Exp extends Activity { @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mDbHelper = new YourDB(getActivity()); mDbHelper.open(); fillData(); } private void fillData() { // set list adapter here } public class Myexpandablelistadapter extends SimpleCursorTreeAdapter { // Your adapter } }
编辑2
要捕获点击次数,请在您的活动中设置侦听器:
lv.setonChildClickListener(new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent,View v,int groupPosition,int childPosition,long id) { // Your child click code here return true; } }); lv.setonGroupClickListener(new ExpandableListView.OnGroupClickListener() { @Override public boolean onGroupClick(ExpandableListView parent,long id) { // Your group click code here return true; } });
Android GPS Location with Listener
/****
* GPS Process
*
* First of all call listener of Location
* then checking for GPS_PROVIDER
* if not available then check for NETWORK_PROVIDER
* and if its also not available then pass 0.00,0.00 to longitude and latitude
*
****
*/
/** PROCESS for Get Longitude and Latitude **/
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Define a listener that responds to location updates(定义一个更新位置监听)
locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.()
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
Log.d(TAG, "changed Loc : " + longitude + ":" + latitude);
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
};
// getting GPS status
isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
// check if GPS enabled
if (isGPSEnabled) {
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);//最后一次知道的位置信息
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);//然后更新位置
} else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
longitude = String.valueOf(location.getLongitude());
latitude = String.valueOf(location.getLatitude());
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
} else {
longitude = "0.00";
latitude = "0.00";
}
}
}
// see http://androidsnippets.com/android-gps-location-with-listener
Android Location LocationListener始终调用onProviderDisabled
compileSdkVersion 24 buildToolsversion "24.0.1" minSdkVersion 21 targetSdkVersion 24
从不调用LocationListener onLocationChanged().它总是调用onProviderdisabled().
这是MainActivity.java
TextView mTextView; LocationManager mLocationManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTextView = (TextView) findViewById(R.id.tv); if (ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { return; } mLocationManager = (LocationManager) this .getSystemService(Context.LOCATION_SERVICE); mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,1 * 1000,0.00001F,locationListener); } private void updateUIToNewLocation(Location location) { Log.d("hello","updateUIToNewLocation = "); if (location != null) { mTextView.setText("Latitude:" + location.getLatitude() + "\nLongitude:" + location.getLongitude()); } else { mTextView.setText("error"); } } LocationListener locationListener = new LocationListener() { public void onLocationChanged(Location location) { Log.d("hello","onLocationChanged"); System.out.println("onLocationChanged"); System.out.println("Latitude:" + location.getLatitude() + "\nLongitude" + location.getLongitude()); updateUIToNewLocation(location); } public void onStatusChanged(String provider,int status,Bundle extras) { Log.d("hello","onStatusChanged"); System.out.println("onStatusChanged"); System.out.println("privider:" + provider); System.out.println("status:" + status); System.out.println("extras:" + extras); } public void onProviderEnabled(String provider) { Log.d("hello","onProviderEnabled"); System.out.println("onProviderEnabled"); System.out.println("privider:" + provider); } public void onProviderdisabled(String provider) { Log.d("hello","onProviderdisabled"); System.out.println("onProviderdisabled"); System.out.println("privider:" + provider); } };
这是manifest xml中的权限和Activity标签.
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/> <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <!-- Needed only if your app targets Android 5.0 (API level 21) or higher. --> <uses-feature android:name="android.hardware.location.network"/> <uses-feature android:name="android.hardware.location.gps" /> <uses-sdk android:minSdkVersion="23" android:targetSdkVersion="24"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <activity android:name=".MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> </application>
此应用程序可以在Android 5.1上运行,但在Android 6.0.1中不起作用.希望有人可以帮助我.我不明白这个问题.
解决方法
android SQLite使用SQLiteOpenHelper类对数据库进行操作
一、 SQLite介绍
SQLite是android内置的一个很小的关系型数据库。
SQLite的官网是http://www.sqlite.org/,可以去下载一些文档或相关信息。
博客中有一篇有稍微详细一点的介绍,大家可以去看一下。
二、 SQLiteOpenHelper的使用方法
SQLiteOpenHelper是一个辅助类来管理数据库的创建和版本。
可以通过继承这个类,实现它的一些方法来对数据库进行一些操作。
所有继承了这个类的类都必须实现下面这样的一个构造方法:
public DatabaseHelper(Context context, String name, CursorFactory factory, int version)
第一个参数:Context类型,上下文对象。
第二个参数:String类型,数据库的名称
第三个参数:CursorFactory类型
第四个参数:int类型,数据库版本
下面是这个类的几个方法:
方法名 返回类型 描述 备注
getReadableDatabase() synchronized SQLiteDatabase 创建或打开一个数据库 可以通过这两个方法返回的SQLiteDatabase对象对数据库进行一系列的操作,如新建一个表,插入一条数据等
getWritableDatabase() synchronized SQLiteDatabase 创建或打开一个可以读写的数据库
onCreate(SQLiteDatabase db) abstract void 第一次创建的时候调用
onOpen(SQLiteDatabase db) void 打开数据库
onUpgrade(SQLiteDatabase db,int oldVersion,int newVersion) abstract void 升级数据库
close() synchronized void 关闭所有打开的数据库对象
下面有一个例子,当点击按钮时进行相应的操作,效果图如下:
介于代码中有详细备注了,在此我就不多写了,直接贴代码了,代码如下:
DatabaseHelper类:
package android.sqlite;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
/**
* SQLiteOpenHelper是一个辅助类,用来管理数据库的创建和版本他,它提供两个方面的功能
* 第一,getReadableDatabase()、getWritableDatabase()可以获得SQLiteDatabase对象,通过该对象可以对数据库进行操作
* 第二,提供了onCreate()、onUpgrade()两个回调函数,允许我们再创建和升级数据库时,进行自己的操作
*/
public class DatabaseHelper extends SQLiteOpenHelper {
private static final int VERSION = 1;
/**
* 在SQLiteOpenHelper的子类当中,必须有该构造函数
* @param context 上下文对象
* @param name 数据库名称
* @param factory
* @param version 当前数据库的版本,值必须是整数并且是递增的状态
*/
public DatabaseHelper(Context context, String name, CursorFactory factory,
int version) {
//必须通过super调用父类当中的构造函数
super(context, name, factory, version);
}
public DatabaseHelper(Context context, String name, int version){
this(context,name,null,version);
}
public DatabaseHelper(Context context, String name){
this(context,name,VERSION);
}
//该函数是在第一次创建的时候执行,实际上是第一次得到SQLiteDatabase对象的时候才会调用这个方法
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
System.out.println("create a database");
//execSQL用于执行SQL语句
db.execSQL("create table user(id int,name varchar(20))");
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
// TODO Auto-generated method stub
System.out.println("upgrade a database");
}
}
Activity类:
package android.sqlite;
import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class SQLiteActivity extends Activity {
/** Called when the activity is first created. */
private Button createDatabaseButton = null;
private Button updateDatabaseButton = null;
private Button insertButton = null;
private Button updateButton = null;
private Button selectButton = null;
private Button deleteButton = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// 根据控件id获得相应的控件对象
createDatabaseButton = (Button) findViewById(R.id.createDatabase);
updateDatabaseButton = (Button) findViewById(R.id.updateDatabase);
insertButton = (Button) findViewById(R.id.insert);
updateButton = (Button) findViewById(R.id.update);
selectButton = (Button) findViewById(R.id.select);
deleteButton = (Button) findViewById(R.id.delete);
// 为按钮设置监听器
createDatabaseButton
.setOnClickListener(new CreateDatabaseOnClickListener());
updateDatabaseButton
.setOnClickListener(new UpdateDatabaseOnClickListener());
insertButton.setOnClickListener(new InsertOnClickListener());
updateButton.setOnClickListener(new UpdateOnClickListener());
selectButton.setOnClickListener(new SelectOnClickListener());
deleteButton.setOnClickListener(new DeleteOnClickListener());
}
// createDatabaseButton点击事件监听器
class CreateDatabaseOnClickListener implements OnClickListener {
public void onClick(View v) {
// 创建了一个DatabaseHelper对象,只执行这句话是不会创建或打开连接的
DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,
"test_yangyz_db");
// 只有调用了DatabaseHelper的getWritableDatabase()方法或者getReadableDatabase()方法之后,才会创建或打开一个连接
SQLiteDatabase sqliteDatabase = dbHelper.getReadableDatabase();
}
}
// updateDatabaseButton点击事件监听器
class UpdateDatabaseOnClickListener implements OnClickListener {
public void onClick(View v) {
// TODO Auto-generated method stub
DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,
"test_yangyz_db", 2);
// 得到一个只读的SQLiteDatabase对象
SQLiteDatabase sqliteDatabase = dbHelper.getReadableDatabase();
}
}
// insertButton点击事件监听器
class InsertOnClickListener implements OnClickListener {
public void onClick(View v) {
// 创建ContentValues对象
ContentValues values = new ContentValues();
// 向该对象中插入键值对,其中键是列名,值是希望插入到这一列的值,值必须和数据库当中的数据类型一致
values.put("id", 1);
values.put("name", "yangyz");
// 创建DatabaseHelper对象
DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,
"test_yangyz_db", 2);
// 得到一个可写的SQLiteDatabase对象
SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase();
// 调用insert方法,就可以将数据插入到数据库当中
// 第一个参数:表名称
// 第二个参数:SQl不允许一个空列,如果ContentValues是空的,那么这一列被明确的指明为NULL值
// 第三个参数:ContentValues对象
sqliteDatabase.insert("user", null, values);
}
}
// updateButton点击事件监听器
class UpdateOnClickListener implements OnClickListener {
public void onClick(View v) {
// 创建一个DatabaseHelper对象
DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,
"test_yangyz_db", 2);
// 得到一个可写的SQLiteDatabase对象
SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase();
// 创建一个ContentValues对象
ContentValues values = new ContentValues();
values.put("name", "zhangsan");
// 调用update方法
// 第一个参数String:表名
// 第二个参数ContentValues:ContentValues对象
// 第三个参数String:where字句,相当于sql语句where后面的语句,?号是占位符
// 第四个参数String[]:占位符的值
sqliteDatabase.update("user", values, "id=?", new String[] { "1" });
System.out.println("-----------update------------");
}
}
// selectButton点击事件监听器
class SelectOnClickListener implements OnClickListener {
public void onClick(View v) {
String id = null;
String name = null;
//创建DatabaseHelper对象
DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,
"test_yangyz_db", 2);
// 得到一个只读的SQLiteDatabase对象
SQLiteDatabase sqliteDatabase = dbHelper.getReadableDatabase();
// 调用SQLiteDatabase对象的query方法进行查询,返回一个Cursor对象:由数据库查询返回的结果集对象
// 第一个参数String:表名
// 第二个参数String[]:要查询的列名
// 第三个参数String:查询条件
// 第四个参数String[]:查询条件的参数
// 第五个参数String:对查询的结果进行分组
// 第六个参数String:对分组的结果进行限制
// 第七个参数String:对查询的结果进行排序
Cursor cursor = sqliteDatabase.query("user", new String[] { "id",
"name" }, "id=?", new String[] { "1" }, null, null, null);
// 将光标移动到下一行,从而判断该结果集是否还有下一条数据,如果有则返回true,没有则返回false
while (cursor.moveToNext()) {
id = cursor.getString(cursor.getColumnIndex("id"));
name = cursor.getString(cursor.getColumnIndex("name"));
}
System.out.println("-------------select------------");
System.out.println("id: "+id);
System.out.println("name: "+name);
}
}
// deleteButton点击事件监听器
class DeleteOnClickListener implements OnClickListener {
public void onClick(View v) {
//创建DatabaseHelper对象
DatabaseHelper dbHelper = new DatabaseHelper(SQLiteActivity.this,"test_yangyz_db",2);
//获得可写的SQLiteDatabase对象
SQLiteDatabase sqliteDatabase = dbHelper.getWritableDatabase();
//调用SQLiteDatabase对象的delete方法进行删除操作
//第一个参数String:表名
//第二个参数String:条件语句
//第三个参数String[]:条件值
sqliteDatabase.delete("user", "id=?", new String[]{"1"});
System.out.println("----------delete----------");
}
}
}
布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/createDatabase"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/createDatabaseButton"
/>
<Button
android:id="@+id/updateDatabase"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/updateDatabaseButton"
/>
<Button
android:id="@+id/insert"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/insertButton"
/>
<Button
android:id="@+id/update"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/updateButton"
/>
<Button
android:id="@+id/select"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/selectButton"
/>
<Button
android:id="@+id/delete"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/deleteButton"
/>
</LinearLayout>
String文件:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, SQLiteActivity!</string>
<string name="app_name">SQLiteTest</string>
<string name="createDatabaseButton">createDatabase</string>
<string name="updateDatabaseButton">updateDatabase</string>
<string name="insertButton">insert</string>
<string name="updateButton">update</string>
<string name="selectButton">select</string>
<string name="deleteButton">delete</string>
</resources>
关于Android错误从LocationListener类将位置数据写入SQLite数据库的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于Android ExpandableListView和SQLite数据库、Android GPS Location with Listener、Android Location LocationListener始终调用onProviderDisabled、android SQLite使用SQLiteOpenHelper类对数据库进行操作等相关知识的信息别忘了在本站进行查找喔。
本文标签: