-1

I have recently used Content Provider in my project. I want to Register a User in the local storage, so I created a util.java class for all constants, and there is another Bean class of the User.
As soon as I run my code, the application force stops.

The Android monitor says:-

  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) 

My Util.java class is as follows:-

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);
}

Actually there are 3 Activities, two are for register and login and other is the main Activity.

You might want to see the Manifest.xml too:

    <?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>

My Content Provider Class is as follows:-

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) {

        }
    }
}

The registeration Activity is as follows:

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);
    }
}

Please help me, I have been trying from like 2 hours, could not be able to find any bug.

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • The "bug" is `at DBHelper.onCreate(UserProvider.java:64)` like the logs say... – OneCricketeer Apr 11 '17 at 19:11
  • The bug is known to me, I have checked my code for like 100 times, still, it's egregious. The Query statement is fine, So does my Bean class, I don't know what to do further. It is actually killing me. – Ripudaman Apr 11 '17 at 19:16
  • It's a NullPointerException. And the solution to them is always the same. Initialize your object! – OneCricketeer Apr 11 '17 at 19:16

1 Answers1

0

You have not yet assigned sqLiteDatabase, so you can't call 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;
}

Solution: Use the non-null database reference...

    @Override
    public void onCreate(SQLiteDatabase db) {
        // sqLiteDatabase.execSQL(Util.CREATE_TAB_QUERY); 
        db.execSQL(Util.CREATE_TAB_QUERY); 
    }
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • It actually solved my exception. Thank you so much! Appreciate your response. Have a great Day/Night ahead. :) – Ripudaman Apr 11 '17 at 19:26