База данных:
Я пытаюсь получить данные из базы данных для отображения в Listview, но они не отображаются.Он принудительно закрывается, поэтому я смотрю на Logcat и он говорит, что мои populateFrom()
и bindView()
- исключение нулевой точки, но я не думаю, что в этом проблема.Затем я пытаюсь их отладить и замечаю, что это пришло из query()
, я думаю.Потому что он получил ссылку с запросом, поэтому метод не может работать, таким образом, показывает ошибку?Может быть.
Я пытаюсь найти полезные ресурсы, но их запрос почти такой же, как у меня.Я сейчас потерян.Может кто-нибудь мне помочь.?Это просто отображение имен всех data(food)
в базе данных.Я проверяю и орфографических ошибок тоже нет.; (
TestDatabaseMain.java:
public class TestDatabaseMain extends Activity
{
private ListViewHelperTest dbListFoodHelper = null;
private Cursor OurCursor = null;
private ListFoodAdapter adapter=null;
public void onCreate(Bundle savedInstanceState)
{
try
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView myListView = (ListView)findViewById(R.id.listfood);
//create the database helper
dbListFoodHelper=new ListViewHelperTest(this);
//create the database if user runs the first time
dbListFoodHelper.createDataBase();
dbListFoodHelper.openDataBase();
OurCursor=dbListFoodHelper.getCursor();
startManagingCursor(OurCursor);
adapter = new ListFoodAdapter(OurCursor);
myListView.setAdapter(adapter);
}
catch(Exception e)
{
Log.e ("ERROR","ERROR IN CODE: " + e.toString());
e.printStackTrace();
}
}
class ListFoodAdapter extends CursorAdapter
{
ListFoodAdapter(Cursor c)
{
super(TestDatabaseMain.this, c);
}
@Override
public void bindView(View row, Context ctxt, Cursor c)
{
ListFoodHolder holder = (ListFoodHolder)row.getTag();
holder.populateFrom(c, dbListFoodHelper);
}
@Override
public View newView(Context ctxt, Cursor c, ViewGroup parent)
{
LayoutInflater inflater =getLayoutInflater();
View row = inflater.inflate(R.layout.row, parent, false);
ListFoodHolder holder = new ListFoodHolder(row);
row.setTag(holder);
return(row);
}
}
static class ListFoodHolder
{
private TextView name = null;
ListFoodHolder(View displayfood)
{
name = (TextView)displayfood.findViewById(R.id.listfood);
}
public void populateFrom(Cursor c, ListViewHelperTest r)
{
//to list out the data from the database
name.setText(r.getName(c));
}
}
ListViewHelperTest.java:
public class ListViewHelperTest extends SQLiteOpenHelper
{
//declare constants of the paths
private static String DB_PATH = "/data/data/sg.edu.tp.iit.mns/databases/";
private static String DB_NAME = "ListFoodItem";
private static int SCHEMA_VERSION=1;
private static final String TABLE_NAME = "listfooditem";
private static final String FOOD_TITLE = "FoodItem";
private static final String FOOD_ID = "_id";
private SQLiteDatabase myDataBase;
private final Context myContext;
public ListViewHelperTest(Context context)
{
super(context, DB_NAME, null, SCHEMA_VERSION);
this.myContext = context;
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db)
{
// TODO Auto-generated method stub
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
// TODO Auto-generated method stub
}
public void createDataBase()
{
createDB();
}
public void createDB()
{
boolean dbExist = DBExists();
if (!dbExist)
{
//overwrite the database with the previous database
this.getReadableDatabase();
//copy the overwrite
copyDBFromRecource();
}
}
private boolean DBExists()
{
SQLiteDatabase checkDB = null;
try
{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
checkDB.setLocale(Locale.getDefault());
checkDB.setLockingEnabled(true);
checkDB.setVersion(1);
}
catch(SQLiteException e)
{
Log.e("SqlHelper","database not found");
}
if(checkDB != null)
{
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDBFromRecource()
{
InputStream myInput=null;
// Path to the just created empty db
try
{
//Open your local db as the input stream
myInput = myContext.getAssets().open(DB_NAME);
OutputStream myOutput=null;
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
//Open the empty db as the output stream
myOutput = new FileOutputStream(outFileName);
//transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0)
{
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
catch (Exception e)
{
throw new Error("Problem coping folders");
}
}
public void openDataBase() throws SQLException
{
String MyPath = DB_PATH + DB_NAME ;
myDataBase = SQLiteDatabase.openDatabase(MyPath, null,
SQLiteDatabase.OPEN_READWRITE);
}
@Override
public synchronized void close()
{
if (myDataBase != null)
{
myDataBase.close();
}
super.close();
}
//important!
public Cursor getCursor()
{
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setTables(TABLE_NAME);
String[] ColumnReturn = new String[] {FOOD_ID, FOOD_TITLE};
//search by string pass(*important*)
Cursor MYCursor = queryBuilder.query(myDataBase, ColumnReturn, null,
null, null, null, "FoodItem ASC");
return MYCursor;
}
public String getName(Cursor c)
{
return(c.getString(1));
}
}