我最近在我的项目中使用了Content Provider。我想在本地存储中注册用户,因此我为所有常量创建了一个util.java类,并且还有另一个用户的Bean类。
一旦我运行我的代码,应用程序就会停止。
Android监视器说: -
04-12 00:15:26.008 21542-21542/com.daman.farmify E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.daman.farmify, PID: 21542
java.lang.RuntimeException: Unable to get provider com.daman.farmify.UserProvider: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)' on a null object reference
at android.app.ActivityThread.installProvider(ActivityThread.java:5572)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:5140)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5080)
at android.app.ActivityThread.access$1600(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1464)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:168)
at android.app.ActivityThread.main(ActivityThread.java:5885)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:797)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:687)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.database.sqlite.SQLiteDatabase.execSQL(java.lang.String)' on a null object reference
at com.daman.farmify.UserProvider$DBHelper.onCreate(UserProvider.java:64)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
at com.daman.farmify.UserProvider.onCreate(UserProvider.java:38)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1790)
at android.content.ContentProvider.attachInfo(ContentProvider.java:1759)
at android.app.ActivityThread.installProvider(ActivityThread.java:5569)
at android.app.ActivityThread.installContentProviders(ActivityThread.java:5140)
at android.app.ActivityThread.handleBindApplication(ActivityThread.java:5080)
at android.app.ActivityThread.access$1600(ActivityThread.java:150)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1464)
at android.os.Handler.dispatchMessage(Handler.java:102)
我的Util.java类如下: -
package com.daman.farmify;
import android.net.Uri;
/**
* Created by Daman on 11-04-2017.
*/
public class Util {
//Database Info
public static final int DB_VERSION =1;
public static final String DB_NAME ="Farmify.db";
//Table info
public static final String TAB_NAME = "Users";
public static final String COL_ID = "_ID";
public static final String COL_NAME = "NAME";
public static final String Col_ADDRESS ="ADDRESS";
public static final String COL_PHONE = "PHONE";
public static final String COL_EMAIL = "EMAIL";
public static final String COL_PASSWORD = "PASSWORD";
public static final String COL_STATE = "STATE";
public static final String CREATE_TAB_QUERY ="create table Users(" +
"_ID integer primary key autoincrement," +
"NAME varchar(256)," +
"ADDRESS varchar(256)," +
"PHONE varchar(40)," +
"EMAIL varchar(40)," +
"PASSWORD varchar(40)," +
"STATE varchar(20)" +
")";
public static final Uri User_URI = Uri.parse("content://com.daman.farmify.userprovider/"+TAB_NAME);
}
实际上有3个活动,其中两个用于注册和登录,另一个是主要活动。
您可能也希望看到Manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.daman.farmify">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity
android:name=".MainActivity"
android:theme="@style/AppTheme.Dark"></activity>
<activity
android:name=".SignupActivity"
android:theme="@style/AppTheme.Dark" />
<activity
android:name=".LoginActivity"
android:theme="@style/AppTheme.Dark">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<provider
android:name=".UserProvider"
android:authorities="com.daman.farmify.userprovider"
android:enabled="true"
android:exported="true"></provider>
</application>
</manifest>
我的内容提供商类如下: -
package com.daman.farmify;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;
public class UserProvider extends ContentProvider {
DBHelper dbHelper;
SQLiteDatabase sqLiteDatabase;
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
// Implement this to handle requests to delete one or more rows.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public String getType(Uri uri) {
// TODO: Implement this to handle requests for the MIME type of the data
// at the given URI.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public Uri insert(Uri uri, ContentValues values) {
Long myUriLastPath=sqLiteDatabase.insert(uri.getLastPathSegment(),null,values);
Uri dummy = Uri.parse("dummy/"+myUriLastPath);
return dummy;
}
@Override
public boolean onCreate() {
dbHelper= new DBHelper(getContext(),Util.DB_NAME,null,Util.DB_VERSION);
sqLiteDatabase=dbHelper.getWritableDatabase();
return false;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
// TODO: Implement this to handle query requests from clients.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
// TODO: Implement this to handle requests to update one or more rows.
throw new UnsupportedOperationException("Not yet implemented");
}
class DBHelper extends SQLiteOpenHelper{
public DBHelper(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) {
super(context, name, factory, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
sqLiteDatabase.execSQL(Util.CREATE_TAB_QUERY);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
}
注册活动如下:
package com.daman.farmify;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.ButterKnife;
import butterknife.InjectView;
public class SignupActivity extends AppCompatActivity implements View.OnClickListener{
@InjectView(R.id.input_name) EditText nameText;
@InjectView(R.id.input_address) EditText addressText;
@InjectView(R.id.input_email) EditText emailText;
@InjectView(R.id.input_mobile) EditText phoneText;
@InjectView(R.id.input_password) EditText passwordText;
@InjectView(R.id.input_state) Spinner state;
@InjectView(R.id.btn_signup) Button signupButton;
@InjectView(R.id.link_login) TextView loginLink;
UserBean userBean;
ArrayAdapter<String> adapter;
ContentResolver resolver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup);
ButterKnife.inject(this);
loginLink.setOnClickListener(this);
signupButton.setOnClickListener(this);
userBean=new UserBean();
adapter=new ArrayAdapter<String>(this,R.layout.support_simple_spinner_dropdown_item);
adapter.add("Select State");
adapter.add("New Delhi");
adapter.add("Punjab");
adapter.add("Chennai");
adapter.add("Mumbai");
adapter.add("bangluru");
state.setAdapter(adapter);
state.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
if(position!=0){
userBean.setState(adapter.getItem(position));
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
resolver=getContentResolver();
}
@Override
public void onClick(View v) {
int id=v.getId();
if(id==R.id.link_login){
Intent intent = new Intent(SignupActivity.this,LoginActivity.class);
startActivity(intent);
} else if (id==R.id.btn_signup){
userBean.setName(nameText.getText().toString().trim());
userBean.setAddress(addressText.getText().toString().trim());
userBean.setEmail(emailText.getText().toString().trim());
userBean.setPhone(phoneText.getText().toString().trim());
userBean.setPassword(passwordText.getText().toString().trim());
insertIntoDB();
}
}
void insertIntoDB(){
ContentValues contentValues = new ContentValues();
contentValues.put(Util.COL_NAME,userBean.getName());
contentValues.put(Util.Col_ADDRESS,userBean.getAddress());
contentValues.put(Util.COL_EMAIL,userBean.getEmail());
contentValues.put(Util.COL_PHONE,userBean.getPhone());
contentValues.put(Util.COL_PASSWORD,userBean.getPassword());
contentValues.put(Util.COL_STATE,userBean.getState());
Uri dummy = resolver.insert(Util.User_URI,contentValues);
Toast.makeText(this,userBean.getName()+"Registered Successfully"+dummy.getLastPathSegment(),Toast.LENGTH_LONG).show();
clearFields();
}
void clearFields(){
nameText.setText("");
addressText.setText("");
emailText.setText("");
phoneText.setText("");
passwordText.setText("");
state.setSelection(0);
}
}
请帮助我,我已经尝试了2个小时,无法找到任何错误。
答案 0 :(得分:0)
您尚未分配sqLiteDatabase
,因此无法致电execSQL
。
@Override
public boolean onCreate() {
dbHelper= new DBHelper(getContext(),Util.DB_NAME,null,Util.DB_VERSION); // This is your error
sqLiteDatabase=dbHelper.getWritableDatabase();
return false;
}
解决方案:使用非空数据库引用...
@Override
public void onCreate(SQLiteDatabase db) {
// sqLiteDatabase.execSQL(Util.CREATE_TAB_QUERY);
db.execSQL(Util.CREATE_TAB_QUERY);
}