I tried to call the method of another class, it is in the same package but when I test it on my phone, it will force close.
basically I create an object of LocalSQLite class, sqlite and use sqlite.method()
below is my code:
Sqlitetest2Activity.java
package com.test.test;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Toast;
public class Sqlitetest2Activity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LocalSQLite sqlite = new LocalSQLite();
sqlite.createTable();
}
}
LocalSQLite.java
package com.test.test;
import android.app.Activity;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.widget.Toast;
public class LocalSQLite extends Activity {
SQLiteDatabase mydb;
private static String DBNAME = "city.db"; // SQLITE DATABASE FILE NAME.
private static String TABLE = "citytable"; // TABLE NAME
/* CREATE TABLE IF NOT EXISTS */
public void createTable(){
try{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
mydb.execSQL("CREATE TABLE IF NOT EXISTS "+ TABLE +" (ID INTEGER PRIMARY KEY, CITY TEXT);");
mydb.close();
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Error in creating table", Toast.LENGTH_LONG);
}
}
/* DROPS TABLE */
public void dropTable(){
try{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
mydb.execSQL("DROP TABLE " + TABLE);
mydb.close();
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Error encountered while dropping table.", Toast.LENGTH_LONG);
}
}
/* THIS FUNCTION INSERTS DATA TO THE DATABASE */
public void insertIntoTable(String city_id, String city_name){
try{
mydb = openOrCreateDatabase(DBNAME, Context.MODE_PRIVATE,null);
mydb.execSQL("INSERT INTO " + TABLE + "(ID, CITY) VALUES('"+city_id+"','"+city_name+"')");
mydb.close();
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Error in inserting into table", Toast.LENGTH_LONG);
}
}
}
You can’t instantiate an Activity’s class object. To call a method, what you can do is –
Put the method as static, and call it using LocalSQLite.createTable();
I see an other mistake in your LocalSQLite class. You don’t have to extend Activity, when there is no screen associated with it. So just remove extends Activity, and that should solve your problem! 🙂
Let me know if you have any questions.