0

I am trying to retrieve data from the sqlite but then my application keeps on crashing. I don't know what is the error. I'm just a beginner in android programming .Here's my code:

MainActivity.java

package com.the.voiceapplock;

import com.the.voiceapplock.adapter.*;
import com.the.voiceapplock.db.ProtectAppProvider;
import com.the.voiceapplock.domain.Model;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.app.Activity;
import android.content.pm.*;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.*;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class MainActivity extends Activity implements OnCheckedChangeListener
{
    private ListView list;
    ArrayList<Model> data;
    ApkAdapter adapter;
    private PackageManager packageManager;
    TextView tView;
    ProtectAppProvider pap;
    CheckBox chk;
    ArrayList<String> protectedApps;
    List<PackageInfo> appsList;


    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        packageManager = getPackageManager();
        tView = (TextView) findViewById(R.id.appname);
        list = (ListView) findViewById(R.id.applist);
        appsList = getPackageManager().getInstalledPackages(0);
        data = new ArrayList<Model>();
        for (int i = 0; i < appsList.size(); i++) 
        {
            PackageInfo p = appsList.get(i);
            if (((packageManager.getLaunchIntentForPackage(p.packageName) != null)))
            {
                Model model  = new Model();
                model.setAppName(p.applicationInfo.loadLabel(getPackageManager()).toString());
                model.setAppIcon(p.applicationInfo.loadIcon((getPackageManager())));
                data.add(model);

                Collections.sort(data,Model.AppComparator);

            }
        }
        adapter = new ApkAdapter(MainActivity.this, data,packageManager,protectedApps);
        adapter.notifyDataSetChanged();
        list.setAdapter(adapter);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main_activity_bar, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
    {
     boolean diditwork = true;
     int getPosition = (Integer) buttonView.getTag();
     Model obj = data.get(getPosition);
     data.get(getPosition).setSelected(isChecked);
     String apps = obj.getAppName();
     protectedApps = new ArrayList<String>();
     pap = new ProtectAppProvider(getApplicationContext());
        if(((CheckBox) buttonView).isChecked()){
            try {   
                protectedApps.add(apps);
                ProtectAppProvider entry = new ProtectAppProvider(MainActivity.this);
                entry.open();
                entry.createEntry(apps);
                entry.close();
            }catch(Exception e){
                diditwork = false;
            }finally{
                if(diditwork){
                    Toast.makeText(this, "Success", Toast.LENGTH_SHORT).show();
                }
                else{
                    Toast.makeText(this, "Fail", Toast.LENGTH_SHORT).show();
                }
            }

        }

    }
}

ApkAdapter.java

package com.the.voiceapplock.adapter;

    import java.util.ArrayList;
    import java.util.List;

    import com.the.voiceapplock.MainActivity;
    import com.the.voiceapplock.R;
    import com.the.voiceapplock.db.ProtectAppProvider;
    import com.the.voiceapplock.domain.Model;

    import android.app.*;
    import android.content.ContentValues;
    import android.content.Context;
    import android.content.pm.*;
    import android.database.Cursor;
    import android.graphics.Color;
    import android.graphics.drawable.*;
    import android.view.*;
    import android.widget.*;
    import android.widget.CompoundButton.OnCheckedChangeListener;


    public class ApkAdapter extends BaseAdapter {
    Context ctx;
    LayoutInflater inflater;
    public ArrayList<Model> data;
    PackageManager p;
    ProtectAppProvider pap;
    private ArrayList<String> protectapps;

    public ApkAdapter(Context c, ArrayList<Model> arraylist, PackageManager p, ArrayList<String> protectApps ) {
        this.ctx = c;
        this.data = arraylist;
        this.p = p;
        this.protectapps = protectApps;
        this.pap = new ProtectAppProvider(ctx);
    }

    @Override
    public int getCount() {
        return data.size();
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        inflater = (LayoutInflater) ctx.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View itemView = inflater.inflate(R.layout.apklist_item, parent, false);
        final CheckBox checks = (CheckBox) itemView.findViewById(R.id.checkBox1);
        final TextView setappname = (TextView) itemView.findViewById(R.id.appname);
        final ImageView appicon = (ImageView) itemView.findViewById(R.id.appicon);
        checks.setChecked(data.get(position).isSelected());

        Model obj = data.get(position);
        setappname.setTextColor(Color.BLACK);
        setappname.setText(obj.getAppName());
        setappname.setCompoundDrawablePadding(15);
        appicon.setImageDrawable(obj.getAppIcon());
        checks.setTag(position);
        checks.setOnCheckedChangeListener((MainActivity)ctx);
        String appname = "";
        pap.open();
        Cursor c = pap.getData();
        if(c.moveToFirst())
        {
            do{
                appname = c.getString(0);
                protectapps.add(appname);
            }while(c.moveToNext());

        }
        pap.close();

       return itemView;
    }

    }

ProtectAppProvider.java

package com.the.voiceapplock.db;

import android.content.*;
import android.database.*;
import android.database.sqlite.*;

public class ProtectAppProvider {

    public static final String KEY_NAME = "appName";

    public static final String DATABASE_NAME = "AppLock";
    public static final String DATABASE_TABLE = "appTable";
    public static final int DATABASE_VERSION = 1;

    private DBHelper dbHelper;
    private final Context context;
    private SQLiteDatabase sqlDB;

    private static class DBHelper extends SQLiteOpenHelper{

        public DBHelper(Context context){
            super(context,DATABASE_NAME ,null,DATABASE_VERSION);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            db.execSQL("CREATE TABLE "+DATABASE_TABLE+" ("+KEY_NAME+" TEXT NOT NULL)" );

        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            db.execSQL("DROP TABLE IF EXISTS "+DATABASE_NAME);
            onCreate(db);
        }

    }
    public ProtectAppProvider(Context context){
         this.context = context;
     }
    public ProtectAppProvider open() throws SQLException{
        dbHelper = new DBHelper(context);
        sqlDB = dbHelper.getWritableDatabase();
        return this;
    }
    public void close(){
        dbHelper.close();
    }
    public long createEntry(String apps) {
        ContentValues cv = new ContentValues();
        cv.put(KEY_NAME, apps);
        return sqlDB.insert(DATABASE_TABLE, null, cv);
    }
    public Cursor getData(){
        String[] columns = new String[]{KEY_NAME};
        return sqlDB.query(DATABASE_TABLE,columns, null, null, null, null, null);

    }
    }

LogCat (Here's the message in the logcat)

 09-09 10:54:22.975: D/AbsListView(12413): Get MotionRecognitionManager
09-09 10:54:23.665: I/dalvikvm-heap(12413): Grow heap (frag case) to 23.887MB for 4194320-byte allocation
09-09 10:54:24.085: D/TextLayoutCache(12413): Enable myanmar Zawgyi converter
09-09 10:54:24.095: D/TextLayoutCache(12413): Enable myanmar Zawgyi converter
09-09 10:54:24.105: D/AndroidRuntime(12413): Shutting down VM
09-09 10:54:24.105: W/dalvikvm(12413): threadid=1: thread exiting with uncaught exception (group=0x4184ada0)
09-09 10:54:24.115: E/AndroidRuntime(12413): FATAL EXCEPTION: main
09-09 10:54:24.115: E/AndroidRuntime(12413): Process: com.the.voiceapplock, PID: 12413
09-09 10:54:24.115: E/AndroidRuntime(12413): java.lang.NullPointerException
09-09 10:54:24.115: E/AndroidRuntime(12413):    at com.the.voiceapplock.adapter.ApkAdapter.getView(ApkAdapter.java:78)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.widget.AbsListView.obtainView(AbsListView.java:2758)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.widget.ListView.measureHeightOfChildren(ListView.java:1274)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.widget.ListView.onMeasure(ListView.java:1186)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.View.measure(View.java:17515)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:719)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:455)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.View.measure(View.java:17515)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5380)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.View.measure(View.java:17515)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5380)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at com.android.internal.widget.ActionBarOverlayLayout.onMeasure(ActionBarOverlayLayout.java:412)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.View.measure(View.java:17515)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:5380)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2567)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.View.measure(View.java:17515)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2287)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1398)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1597)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1256)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6652)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:813)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.Choreographer.doCallbacks(Choreographer.java:613)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.Choreographer.doFrame(Choreographer.java:583)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:799)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.os.Handler.handleCallback(Handler.java:733)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.os.Handler.dispatchMessage(Handler.java:95)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.os.Looper.loop(Looper.java:146)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at android.app.ActivityThread.main(ActivityThread.java:5653)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at java.lang.reflect.Method.invokeNative(Native Method)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at java.lang.reflect.Method.invoke(Method.java:515)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
09-09 10:54:24.115: E/AndroidRuntime(12413):    at dalvik.system.NativeStart.main(Native Method)
Apn17
  • 15
  • 1
  • 6
  • where is it crashing? where's the stack trace? – Eugene S Sep 09 '14 at 02:46
  • @unluddite it keeps on crashing on my device whenever I run it. – Apn17 Sep 09 '14 at 02:47
  • I understand, but until you provide the stack trace from logcat, you won't find much help here. How can we know where it's crashing without this information? – Eugene S Sep 09 '14 at 02:48
  • @unluddite how will I provide a stack trace on logcat .. sorry but I'm just a beginner – Apn17 Sep 09 '14 at 02:49
  • Copy your logcat messages here, so we can understand what is the problem. – Alok Nair Sep 09 '14 at 02:52
  • You need to connect your phone to your PC and reproduce the crash within the Eclipse debugger (or on the emulator). Just Google "Android logcat tutorial." – Eugene S Sep 09 '14 at 02:53
  • What is the code on line 78 of ApkAdapter.java? – Andrew T. Sep 09 '14 at 03:12
  • protectapps.add(appname); is it this one @AndrewT.?it is where the retrieval of data will be placed because i'm developing an application lock – Apn17 Sep 09 '14 at 03:42
  • It seems that `protectapps` is null on that line. From what I observed, when you call `adapter = new ApkAdapter(MainActivity.this, data,packageManager,protectedApps);` inside `onCreate()`, `protectedApps` is still null; it's not yet instantiated. Hence the `NullPointerException`. – Andrew T. Sep 09 '14 at 03:52
  • @AndrewT. Thank you for your help .. it solves the issue now :) – Apn17 Sep 10 '14 at 02:34

1 Answers1

1

From your logcat stacktrace,

 java.lang.NullPointerException at com.the.voiceapplock.adapter.ApkAdapter.getView(ApkAdapter.java:78)

On line 78 of ApkAdapter class why it is showing NullPointerException because you haven't instantiated your ArrayList there.If you see your MainActivity, on line 78 you have instantiated your ArrayList.You will need to do something like that in your ApkAdapter too.

In ApkAdapter class, inside getView(final int position, View convertView, ViewGroup parent), add this line

protectedApps = new ArrayList<String>();
Sash_KP
  • 5,551
  • 2
  • 25
  • 34
  • If this answer solved your issue then please accept it as a correct answer so that anyone who see this question can clearly know that this is the correct answer. – Sash_KP Sep 10 '14 at 10:07