-2

NUllpointer Exception and stack overflow exception on line which has has sql query.

display.java

 import android.app.Activity;
 import android.content.Context;
 import android.os.Bundle;
 import android.view.Menu;
 import android.view.MenuItem;
 import android.widget.TextView;

  public class display extends Activity {
  private Context context;
  MyDBHandler helper

 @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display);
    helper = new MyDBHandler(context);

    Bundle nameValue=getIntent().getExtras();
    String vname=nameValue.getString("Name");
    TextView tvname=(TextView)findViewById(R.id.TVname);
    tvname.setText(vname);

    String dispname=helper.onSelect(vname);
    TextView tvaddress=(TextView)findViewById(R.id.TVaddress);
    tvaddress.setText(dispname);


  }
   /*public void onDisplay(){
    Bundle nameValue=getIntent().getExtras();
    if(nameValue==null){

    }
    String vname=nameValue.getString("Name");
    String dispname=helper.onSelect(vname);
    TextView tvaddress=(TextView)findViewById(R.id.TVaddress);
    tvaddress.setText(dispname);
}*/




@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.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);
}
}

MyDBHandler

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

public class MyDBHandler extends SQLiteOpenHelper {

private static final int DATABASE_VERSION = 1;
private static final String DATABASE_NAME = "productDB.db";
public static final String TABLE_PRODUCTS = "products";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAME = "name";
public static final String COLUMN_ADDRESS = "address";


private final Context myContext;
public MyDBHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
    this.myContext = context;
}


    @Override
     public void onCreate(SQLiteDatabase db) {
    String query = "CREATE TABLE " + TABLE_PRODUCTS + "(" +
            COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
            COLUMN_NAME + " TEXT, " +
            COLUMN_ADDRESS + " TEXT " +
            ");";
    db.execSQL(query);
    String query1="INSERT INTO"+ TABLE_PRODUCTS + "(name,address) VALUES   
    ('name1,address1');";
    String query2="INSERT INTO"+ TABLE_PRODUCTS + "(name,address) VALUES   
    ('name2,address2');";
    db.execSQL(query1);
    db.execSQL(query2);

}

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

public String onSelect(String sname){
    String dbString = "";
    SQLiteDatabase db = getWritableDatabase();
    String displayname= "SELECT address FROM"+ TABLE_PRODUCTS + " WHERE "+       


    COLUMN_NAME + "=\""+ sname + "\";";
    Cursor c = db.rawQuery(displayname, null);

   if (c.getString(c.getColumnIndex("address")) != null) {
           dbString = c.getString(c.getColumnIndex("address"));
   }
    db.close();
    return dbString;
   }

   }

NullPointerExcepion

E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.arjun.tablesqlite/com.example.arjun.tablesqlite.display}: java.lang.NullPointerException
at com.example.arjun.tablesqlite.MyDBHandler.onSelect(MyDBHandler.java:57)
at com.example.arjun.tablesqlite.display.onCreate(display.java:27)

I'm getting NullPointerException at this line in MyDbHandler.java

SQLiteDatabase db = getWritableDatabase();  

and at this line in display.java....

String dispname=helper.onSelect(vname); 
arjun
  • 69
  • 1
  • 6

2 Answers2

2

Try this,

You haven't initialized the context, and directly you have tried to intialize the DBHandler with that context, so it was throwing NLP.

public class display extends Activity {

MyDBHandler helper;


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

    helper = new MyDBHandler(this);
   .... //your code
}
Raghavendra
  • 2,305
  • 25
  • 30
  • this has worked!!!But now I'm getting this ==>E/SQLiteLog: (1) near "INTOproducts": syntax error D/AndroidRuntime: Shutting down VM W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4100b2b8) E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.arjun.tablesqlite/com.example.arjun.tablesqlite.display}: android.database.sqlite.SQLiteException: near "INTOproducts": syntax error (code 1): , while compiling: INSERT INTOproducts(name,address) VALUES ('name1,address1'); – arjun Nov 17 '16 at 08:21
  • @arjun give space after INTO in that query – Raghavendra Nov 17 '16 at 08:52
  • @arjun try this: "INSERT INTO "+ TABLE_PRODUCTS + "(name,address) VALUES ('name1,address1');" and String query2="INSERT INTO "+ TABLE_PRODUCTS + "(name,address) VALUES ('name2,address2');"; – Raghavendra Nov 17 '16 at 08:55
  • @Raghavendra..it worked !!!Now I'm going to try similar concepts with php and mysql through servers.... I have a doubt bro.. should I memorize all the coding to develop an app?... – arjun Nov 17 '16 at 09:17
1

Please try below onSelect Method and let me know any error in it:-

  public String onSelect(String sname) {
        String dbString = "";
        SQLiteDatabase db = this.getWritableDatabase();
        String displayname = "SELECT address FROM" + TABLE_PRODUCTS + " WHERE " +


                COLUMN_NAME + "='" + sname + "'";
        Cursor c = db.rawQuery(displayname, null);

/*
        if (c.getString(c.getColumnIndex("address")) != null) {
            dbString = c.getString(c.getColumnIndex("address"));
        }
*/
        if (c.moveToFirst()) {
            if (c.getString(c.getColumnIndex("address")) != null) {
                dbString = c.getString(c.getColumnIndex("address"));
            }else{
                dbString="No Address";
            }
        }else{
            dbString="No Address Found";
        }
        db.close();
        return dbString;
    }

And this:-

MyDBHandler helper = new MyDBHandler(this);

Change this line like below

String query1="INSERT INTO "+ TABLE_PRODUCTS + "(name,address) VALUES   
    ('name1','address1');";
String query2="INSERT INTO "+ TABLE_PRODUCTS + "(name,address) VALUES   
    ('name2','address2')";

Your database query is like below(for reference):-

INSERT INTO products (name,address) VALUES ('name1','address1');

and your query build like this:-

INSERT INTOproducts (name,address) VALUES ('name1','address1');

so you have get below error.

Anil Ravsaheb Ghodake
  • 1,587
  • 2
  • 27
  • 45
  • I think **this.getWritableDatabase()** should solve your problem. – Anil Ravsaheb Ghodake Nov 17 '16 at 06:24
  • I had done those corretions..Now I'm getting this syntax error..... E/SQLiteLog: (1) near "INTOproducts": syntax error D/AndroidRuntime: Shutting down VM W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x4100b2b8) E/AndroidRuntime: FATAL EXCEPTION: main java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.arjun.tablesqlite/com.example.arjun.tablesqlite.display}: android.database.sqlite.SQLiteException: near "INTOproducts": syntax error (code 1): , while compiling: INSERT INTOproducts(name,address) VALUES ('name1,address1'); – arjun Nov 17 '16 at 08:22
  • @arjun you have forget to add space after INTO in your insert query so please print query once and run it on external sqlite db so that you will able to get the error from queries – Anil Ravsaheb Ghodake Nov 17 '16 at 08:58
  • It worked bro!! – arjun Nov 17 '16 at 09:29
  • great,but always aware about white space insertion in query – Anil Ravsaheb Ghodake Nov 17 '16 at 09:32