-2

I am using a navigation bar activity.the user enters data in the LoginFragment which gets checked in the database DextroDb class Student Table st_activation key column.If success and if successful.I am getting the following null pointer exception.I have used Fragment interaction and I have used normal fragment to fragment replacement but it does not work out.pls help me.I am attaching all the codes I did using Fragment Interaction at the moment.pls help me.

08-22 16:48:09.482 27969-27969/dextrosoft.com.schoolmobileapp E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            java.lang.NullPointerException
                                                                                at dextrosoft.com.schoolmobileapp.LoginFragment.canSignIn(LoginFragment.java:102)
                                                                                at dextrosoft.com.schoolmobileapp.LoginFragment.onLogin(LoginFragment.java:55)
                                                                                at dextrosoft.com.schoolmobileapp.LoginFragment$1.onClick(LoginFragment.java:33)
                                                                                at android.view.View.performClick(View.java:4281)
                                                                                at android.widget.Button.performClick(Button.java:140)
                                                                                at android.view.View$PerformClick.run(View.java:17513)
                                                                                at android.os.Handler.handleCallback(Handler.java:725)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                                at android.os.Looper.loop(Looper.java:137)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5216)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:511)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:798)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:565)
                                                                                at dalvik.system.NativeStart.main(Native Method)

DextroDb.javastrong text

package dextrosoft.com.schoolmobileapp.database;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;


 public class  DextroDb extends SQLiteOpenHelper {
public static final int DB_VERSION = 1;
public static final String DB_NAME = "SchoolDb";
private Context context;

public DextroDb(Context context)
{
    super(context,DB_NAME , null ,DB_VERSION);
    context = this.context;
}
@Override
public void onCreate(SQLiteDatabase db) {

    String CREATE_STUDENT_TABLE = "Create table Student(" +
            " _id INTEGER AUTO INCREMENT PRIMARY KEY, "+
            " st_activationkey TEXT ,"+
            "st_name TEXT,"+"st_class TEXT,"+"st_class_classteacher TEXT"+" st_rollno INT,"+
            " gender TEXT,"+
            " d.o.b. DATETIME ,"+
            " Admission Date DATETIME,"+
            " address TEXT,"+
            " contact_no BIGINT,"+
            " m_contact_no TEXT)";

    db.execSQL(CREATE_STUDENT_TABLE);

    db.execSQL(" INSERT INTO STUDENT VALUES(1,'871212','Kripa Sharma','X-A','Vandana Bhanot',12,'F','2000-12-12','2007-04-07','ABC COLONY','9830545790','9681206091',letstalk.payal@gmail.com);");


}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

}

}

LoginFragment.java package dextrosoft.com.schoolmobileapp;

  import android.app.Fragment;
  import android.content.Context;
  import android.database.Cursor;
  import android.database.sqlite.SQLiteDatabase;
  import android.os.Bundle;
  import android.view.LayoutInflater;
  import android.view.View;
  import android.view.ViewGroup;
  import android.widget.Button;
  import android.widget.EditText;

  import dextrosoft.com.schoolmobileapp.database.DextroDb;

  public class LoginFragment extends Fragment{
  private String key_act;
  Button login;
  EditText A_key;
  DextroDb mDbHelper;
  private OnFragmentInteractionListener  mListener;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.loginpage, container, false);
    login=(Button)v.findViewById(R.id.loginbt);
    A_key=(EditText)v.findViewById(R.id.a_key);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onLogin();
        }
    });
    Utils.destroyLoginSession(getActivity());
    return v;
}
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

public static LoginFragment newInstance(int page, String text) {

    LoginFragment loginfrag = new LoginFragment();
    Bundle b = new Bundle();
    b.putString("msg", text);
    loginfrag.setArguments(b);
    return loginfrag;
}
public void onLogin()
{
    key_act=A_key.getText().toString();
    if (doValidation()) {
        if (canSignIn()) {
           //Intent i = new Intent(getActivity(), MainActivity.class);
            //i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            //startActivity(i);*/
             mListener.OnValidationSuccessful(key_act);

        }
    }

}
public boolean doValidation() {
    boolean isValid = true;
    if (key_act.equals("")) {
        isValid = false;
        // uname.setError("Please enter  user name");
        A_key.setError("Please enter  activation key");
        //inputlayoutusername.requestFocus();
        return false;
    }

    return isValid;
}
public boolean canSignIn()
{
    boolean tempCanSignIn = false;
    SQLiteDatabase database = null;
    Cursor findEntry = null;
    try{
        mDbHelper = new DextroDb(getActivity());
        database = mDbHelper.getWritableDatabase();
        findEntry = database.query("Student", new String[]{"st_activationkey"}, "st_activation=?", new String[]{key_act}, null, null, null);
        if(findEntry.getCount() > 0){

            Utils.createLoginSession(getActivity(),key_act);
            tempCanSignIn = true;
            Utils.showAlert(getActivity(), "login succesfully");
        }
        else{
           Utils.showAlert(getActivity()," Invalid Activation Key");
        }

    }
    catch(Exception e)
    {
        Utils.showAlert(getActivity()," Login Failed ,Please try after sometime.");
    }
    finally {
        findEntry.close();
        database.close();
        return tempCanSignIn ;
    }

}
@Override
public void onAttach(Context context) {
    super.onAttach(context);
    if (context instanceof OnFragmentInteractionListener) {
        mListener = (OnFragmentInteractionListener) context;
    } else {
        throw new RuntimeException(context.toString()
                + " must implement OnFragmentInteractionListener");
    }
}
@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

public interface OnFragmentInteractionListener {
    public void OnValidationSuccessful(String akey);

}

}

MainActivity.java

package dextrosoft.com.schoolmobileapp;

 import android.app.FragmentManager;
 import android.app.FragmentTransaction;
 import android.os.Bundle;
 import android.support.design.widget.FloatingActionButton;
 import android.support.design.widget.NavigationView;
 import android.support.design.widget.Snackbar;
 import android.support.v4.view.GravityCompat;
 import android.support.v4.widget.DrawerLayout;
 import android.support.v7.app.ActionBarActivity;
 import android.support.v7.app.ActionBarDrawerToggle;
 import android.support.v7.widget.Toolbar;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.view.View;

    public class MainActivity extends ActionBarActivity
    implements NavigationView.OnNavigationItemSelectedListener,LoginFragment.OnFragmentInteractionListener {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                    .setAction("Action", null).show();
        }
    });

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
    drawer.setDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
}

@Override
public void onBackPressed() {
    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

@SuppressWarnings("StatementWithEmptyBody")
@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    if (id == R.id.nav_camera) {
        // Handle the camera action
    } else if (id == R.id.nav_gallery) {

    } else if (id == R.id.nav_slideshow) {

    } else if (id == R.id.nav_manage) {

    } else if (id == R.id.nav_share) {

    } else if (id == R.id.nav_send) {

    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}
public void onClick_myacc(View v)
{
    FragmentManager fragmentManager = getFragmentManager();
    LoginFragment loginfrag=new LoginFragment();
    FragmentTransaction ft = fragmentManager.beginTransaction();
    ft.replace(R.id.content_frame, loginfrag);
    ft.commit();

}
public void OnValidationSuccessful(String akey)
{
    FragmentManager fragmentManager = getFragmentManager();
    MyAccountFragment accountfrag=new MyAccountFragment();
    Bundle param = new Bundle();
    param.putString("TITLE", akey);
    accountfrag.setArguments(param);
    FragmentTransaction ft1 = fragmentManager.beginTransaction();
    ft1.replace(R.id.content_frame, accountfrag);
    accountfrag.setArguments(param);
    ft1.commit();

}

}

MyAccountFragment.java

  package dextrosoft.com.schoolmobileapp;

  import android.app.Fragment;
  import android.os.Bundle;
  import android.view.LayoutInflater;
  import android.view.View;
  import android.view.ViewGroup;
  import android.widget.Button;
  import android.widget.EditText;


  public class MyAccountFragment extends Fragment {
private int imageRes;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.myacc_frag, container, false);

    return v;
}
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
}

public static MyAccountFragment newInstance(int page, String title) {

    MyAccountFragment accountfrag = new MyAccountFragment();
    Bundle b = new Bundle();
    b.putString("msg", title);
    accountfrag.getArguments().getString("TITLE");
    return accountfrag;
}

}

Utils.java

package dextrosoft.com.schoolmobileapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Environment;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;


 public class Utils {
public static final String DEXTRO_PREFERENCE_NAME = "dextroPrefence";
public static void showAlert(Activity context, String message){
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
    alertDialogBuilder.setMessage(message);

    alertDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface arg0, int arg1) {

        }
    });

    alertDialogBuilder.setNegativeButton("CANCEL",new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();
}
public static void exportDatabse(Context context, String databaseName) {
    try {
        File sd = Environment.getExternalStorageDirectory();
        File data = Environment.getDataDirectory();

        if (sd.canWrite()) {
            String currentDBPath = "//data//"+context.getPackageName()+"//databases//"+databaseName+"";
            String backupDBPath = "Schooldb.db";
            File currentDB = new File(data, currentDBPath);
            File backupDB = new File(sd, backupDBPath);

            if (currentDB.exists()) {
                FileChannel src = new FileInputStream(currentDB).getChannel();
                FileChannel dst = new FileOutputStream(backupDB).getChannel();
                dst.transferFrom(src, 0, src.size());
                src.close();
                dst.close();
                Log.e("db export","success");
            }
        }
    } catch (Exception e) {
        Log.e("db export","failure "+e.getMessage());
    }
}

public static String isUserLoggedIn(Context context){
    SharedPreferences prefs = context.getSharedPreferences(Utils.DEXTRO_PREFERENCE_NAME, context.MODE_PRIVATE);
    String key1 = prefs.getString("st_activationkey", null);
    return key1 ;
}

public static void  createLoginSession(Context context,String key1){
    SharedPreferences sharedpreferences = context.getSharedPreferences(Utils.DEXTRO_PREFERENCE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString("st_activationkey", key1);
    editor.commit();
}

public static void destroyLoginSession(Context context){
    SharedPreferences sharedpreferences = context.getSharedPreferences(Utils.DEXTRO_PREFERENCE_NAME, Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.remove("st_activationkey");
    editor.commit();
}

}

Payal Garg
  • 31
  • 5
  • Where exactly are you getting the nullpointer ? better add the stacktrace as well. and Nullpointers are generally easiest issues to solve. – Tarun Gupta Aug 22 '16 at 10:10
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Phantômaxx Aug 22 '16 at 10:19
  • please post your crash log here – karan Aug 22 '16 at 10:28
  • @tarun and karan.I have edited my query with the post of the exception shown.pls chk – Payal Garg Aug 22 '16 at 10:48
  • @rotwang I know what is a null pointer but I cannot trace it over here as all my ids and database entries,variable values are ok i checked,,,,So my question is different.I think it has something to do with fragment replacement – Payal Garg Aug 22 '16 at 10:50
  • **NO**. **Every NPE is the same**: an object is used before it has been instantiated. **And also the solution is always the same**: find that object and instance it BEFORE using it. – Phantômaxx Aug 22 '16 at 10:58
  • @tarun and karan i have also added my database class in case u want to check – Payal Garg Aug 22 '16 at 11:23
  • @rotwang i cudnt find that object i tried a lot.can i pls post my xml files as well – Payal Garg Aug 22 '16 at 11:26
  • You can post whatever you feel is related to your project issue. Anyway an NPE is surely located in some Java code. also bear in mind that you should only publish an [MCVE](http://stackoverflow.com/help/mcve). Your logcat tells me that your error is located ina Button click event handler in your LoginFragment: `at dextrosoft.com.schoolmobileapp.LoginFragment$1.onClick(LoginFragment.java:33)` – Phantômaxx Aug 22 '16 at 11:38
  • Thanks.I will check it – Payal Garg Aug 23 '16 at 05:12
  • pls help me with this issue http://stackoverflow.com/questions/40017700/cursorboundexception-whille-displaying-listview-from-content-provider?noredirect=1#comment67354557_40017700 – Payal Garg Oct 14 '16 at 11:55

1 Answers1

0

Looks like you are getting NPE at the following line :

findEntry.close();

I think some code inside the try block is throwing an exception and you are not logging/printing it in your catch block ( just before the finally block). And because of this exception when control reaches the Finally block, 'findEntry' object remains to be null and you get a Nullpointer Exception.

What you should do is :

  1. Almost always log the exception in your catch blocks.
  2. You should check if findEntry is null before calling .close() on it.
  3. Improve the Exception handling in your code - instead of catching the generic Exception catch(Exception e). Please check what are possible exceptions (specific exception classes like SQLException etc) that can be thrown from the code inside try block and handle them appropriately.
Tarun Gupta
  • 1,629
  • 1
  • 22
  • 39
  • well i think i am close to it.There is no getWritableDatabase in the DextroDb database class.Now this same database in working on some other project as in that project all the methods regarding insert,delete,find are in respective classes as required.Now pls guide me how do I add that entry in this database so that the database connection can start from LoginFragment.class – Payal Garg Aug 23 '16 at 05:16