我正在尝试从sqlite数据库加载学校列表并在自动完成textview中显示它我得到一个空对象错误。我已经从资产文件夹加载了sqlite数据,因为数据太高我已加载它来自assests文件夹。
代码:
public class Profileeditpage extends AppCompatActivity implements GoogleApiClient.OnConnectionFailedListener, GoogleApiClient.ConnectionCallbacks{
EditText name,email;
SQLiteDatabase db;
List<Schoolname> nameschool;
AutoCompleteTextView grade,location,schoolname;
Toolbar mtool;
private static final String LOG_TAG = "MainActivity";
private static final int GOOGLE_API_CLIENT_ID = 0;
private GoogleApiClient mGoogleApiClient;
private PlaceArrayAdapter mPlaceArrayAdapter;
private static final LatLngBounds BOUNDS_MOUNTAIN_VIEW = new LatLngBounds(
new LatLng(37.398160, -122.180831), new LatLng(37.430610, -121.972090));
String[] grad={"Grade1","Grade2","Grade3","Grade4","Grade5","Grade6","Grade7"};
private static final String TAG = Profileeditpage.class.getSimpleName();
Schoolname currentq;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editprofile);
mtool=(Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(mtool);
getSupportActionBar().setDisplayShowHomeEnabled(true);
init();
}
private void init() {
SchoolDatabaseHelper db=new SchoolDatabaseHelper(this);
db.openDatabase();
nameschool=getAllSchools();
name = (EditText) findViewById(R.id.edtprofilename);
email = (EditText) findViewById(R.id.edtprofilemail);
location = (AutoCompleteTextView) findViewById(R.id.edtlocation);
schoolname = (AutoCompleteTextView) findViewById(R.id.tvschoolname);
grade = (AutoCompleteTextView) findViewById(R.id.tvgrade);
// schoolname.setThreshold(1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>
(this,android.R.layout.select_dialog_item,grad);
grade.setThreshold(0);
grade.setDropDownWidth(-1);
grade.setDropDownVerticalOffset(5);
grade.setAdapter(adapter);
mGoogleApiClient = new GoogleApiClient.Builder(Profileeditpage.this)
.addApi(Places.GEO_DATA_API)
.enableAutoManage(this, GOOGLE_API_CLIENT_ID, this)
.addConnectionCallbacks(this)
.build();
location.setThreshold(1);
location.setOnItemClickListener(mAutocompleteClickListener);
mPlaceArrayAdapter = new PlaceArrayAdapter(this, android.R.layout.simple_list_item_1,
BOUNDS_MOUNTAIN_VIEW, null);
location.setDropDownWidth(-1);
location.setAdapter(mPlaceArrayAdapter);
}
public List<Schoolname> getAllSchools() {
List<Schoolname>nameschool= new ArrayList<Schoolname>();
// Select All Query
String selectQuery = "SELECT DISTINCT schoolname FROM schooldet ORDER BY schoolname ASC";
//db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Schoolname quest = new Schoolname();
quest.setNames(cursor.getString(0));
nameschool.add(quest);
} while (cursor.moveToNext());
}
// return quest list
String[] stockArr = new String[nameschool.size()];
stockArr = nameschool.toArray(stockArr);
ArrayAdapter<String> sadapter = new ArrayAdapter<String>
(this,android.R.layout.select_dialog_item,stockArr);
schoolname.setAdapter(sadapter);
return nameschool;
}
private AdapterView.OnItemClickListener mAutocompleteClickListener
= new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final PlaceArrayAdapter.PlaceAutocomplete item = mPlaceArrayAdapter.getItem(position);
final String placeId = String.valueOf(item.placeId);
Log.i(LOG_TAG, "Selected: " + item.description);
PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi
.getPlaceById(mGoogleApiClient, placeId);
placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
Log.i(LOG_TAG, "Fetching details for ID: " + item.placeId);
}
};
private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback
= new ResultCallback<PlaceBuffer>() {
@Override
public void onResult(PlaceBuffer places) {
if (!places.getStatus().isSuccess()) {
Log.e(LOG_TAG, "Place query did not complete. Error: " +
places.getStatus().toString());
return;
}
// Selecting the first object buffer.
final Place place = places.get(0);
CharSequence attributions = places.getAttributions();
}
};
@Override
public void onConnected(Bundle bundle) {
mPlaceArrayAdapter.setGoogleApiClient(mGoogleApiClient);
Log.i(LOG_TAG, "Google Places API connected.");
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.e(LOG_TAG, "Google Places API connection failed with error code: "
+ connectionResult.getErrorCode());
Toast.makeText(this,
"Google Places API connection failed with error code:" +
connectionResult.getErrorCode(),
Toast.LENGTH_LONG).show();
}
@Override
public void onConnectionSuspended(int i) {
mPlaceArrayAdapter.setGoogleApiClient(null);
Log.e(LOG_TAG, "Google Places API connection suspended.");
}
数据库:
public class SchoolDatabaseHelper extends Activity{
private static final String DB_NAME = "school.sqlite";
private Context context;
public SchoolDatabaseHelper(Context context) {
this.context = context;
}
public SQLiteDatabase openDatabase() {
File dbFile = context.getDatabasePath(DB_NAME);
if (!dbFile.exists()) {
try {
SQLiteDatabase checkDB = context.openOrCreateDatabase(DB_NAME, context.MODE_PRIVATE, null);
if(checkDB != null){
checkDB.close();
}
copyDatabase(dbFile);
} catch (IOException e) {
throw new RuntimeException("Error creating source database", e);
}
}
return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
}
private void copyDatabase(File dbFile) throws IOException {
InputStream is = context.getAssets().open(DB_NAME);
OutputStream os = new FileOutputStream(dbFile);
byte[] buffer = new byte[1024];
while (is.read(buffer) > 0) {
os.write(buffer);
}
os.flush();
os.close();
is.close();
}
}
错误:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.Cursor android.database.sqlite.SQLiteDatabase.rawQuery(java.lang.String, java.lang.String[])' on a null object reference
at nidhinkumar.gridcam.logindetails.Profileeditpage.getAllSchools(Profileeditpage.java:104)
at nidhinkumar.gridcam.logindetails.Profileeditpage.onCreate(Profileeditpage.java:63)
at android.app.Activity.performCreate(Activity.java:6092)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1112)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2468)
答案 0 :(得分:0)
成员变量db
未初始化。在init方法中,您创建了一个局部变量,该变量无法从方法getAllSchools()
所以尝试这样的事情:
SchoolDatabaseHelper db =new SchoolDatabaseHelper(this);
this.db = db.getReadableDatabase();
nameschool=getAllSchools();