I am trying to populate ListView from database, as I am using Navigation drawer so I need to use Fragment to show my View instead of Activity. Everything is fine but when I run my application it shows me a error that column _id does not exits but my query is SELECT city_name, country_name, favorite FROM city;. My database table is.
My Android application screen is:
When I click All City (position=3) I want to populate my List with city_name and country_name from my database. But It shows error column _id does not exits but did not use _id in my query and also my table contains _id. So why this error?
My Code section is given below:
selectItem() method from MyActivity.java Class, When I select All City position=3
private void selectItem(int position) {
if (position == 0) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
args.putInt(MyFragment.ARG_OS, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
mDrawerList.setItemChecked(position, true);
getSupportActionBar().setTitle((navMenuTitles[position]));
mDrawerLayout.closeDrawer(mDrawerList);
} else if (position == 3) {
AllCityListFragment myfragment = new AllCityListFragment();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_frame, myfragment).commit();
mDrawerList.setItemChecked(position, true);
getSupportActionBar().setTitle((navMenuTitles[position]));
mDrawerLayout.closeDrawer(mDrawerList);
}
}
DatabaseHelper.java: This is working fine, In this question I require createdatabase(), opendatabase() and getResult() method getResult returns a Cursor.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
public class DatabaseHelper extends SQLiteOpenHelper {
private static String PACKAGE_NAME;
private static String DB_PATH;
private static String DB_NAME = "weatherbd.db";
private SQLiteDatabase myDataBase;
private final Context myContext;
public DatabaseHelper(Context context) {
super(context, DB_NAME, null, 1);
this.myContext = context;
PACKAGE_NAME = myContext.getPackageName();
DB_PATH = "/data/data/" + PACKAGE_NAME + "/databases/";
}
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
// do nothing - database already exist
} else {
// By calling this method and empty database will be created into
// the default system path
// of your application so we are gonna be able to overwrite that
// database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
private boolean checkDataBase() {
SQLiteDatabase checkDB = null;
try {
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
} catch (SQLiteException e) {
// database does't exist yet.
}
if (checkDB != null) {
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDataBase() throws IOException {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open(DB_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DB_NAME;
// Open the empty db as the output stream
OutputStream 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();
}
public void openDataBase() throws SQLException {
// Open the database
String myPath = DB_PATH + DB_NAME;
myDataBase = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READONLY);
}
@Override
public synchronized void close() {
if (myDataBase != null)
myDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
public Cursor getResult(String sql) {
Cursor c = myDataBase.rawQuery(sql, null);
return c;
}
}
AllListFragment.java Class to show populated list from database, Here error is coming from the query SELECT city_name, country_name, favorite FROM city;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
public class AllCityListFragment extends Fragment {
private CustomList customAdapter;
private DatabaseHelper databaseHelper;
ListView list;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.all_city_layout, null);
databaseHelper = new DatabaseHelper(view.getContext());
try {
databaseHelper.createDataBase();
Toast.makeText(view.getContext(), "Database Created",
Toast.LENGTH_LONG).show();
databaseHelper.openDataBase();
Toast.makeText(view.getContext(), "Database Opened",
Toast.LENGTH_LONG).show();
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(view.getContext(), "Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
list = (ListView) view.findViewById(R.id.citylist);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(view.getContext(),
"Cliked on item: " + position, Toast.LENGTH_LONG)
.show();
}
});
new Handler().post(new Runnable() {
@Override
public void run() {
customAdapter = new CustomList(
view.getContext(),
databaseHelper
.getResult("SELECT city_name, country_name, favorite FROM city;"));
list.setAdapter(customAdapter);
}
});
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
CustomList.java class extends CursorAdapter
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CursorAdapter;
import android.widget.TextView;
public class CustomList extends CursorAdapter {
@SuppressWarnings("deprecation")
public CustomList(Context context, Cursor c) {
super(context, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.all_city_list, parent, false);
return retView;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView cityName = (TextView) view.findViewById(R.id.cityName);
cityName.setText(cursor.getString(cursor.getColumnIndex("city_name")));
TextView countryName = (TextView) view.findViewById(R.id.countryName);
countryName.setText(cursor.getString(cursor.getColumnIndex("country_name")));
CheckBox favoriteBox = (CheckBox) view
.findViewById(R.id.favoriteCheckBox);
if (cursor.getInt(cursor.getColumnIndex("favorite")) == 0) {
favoriteBox.setSelected(false);
} else {
favoriteBox.setSelected(true);
}
}
}
LogCat:
I restarted my Eclipse IDE but still I have this problem.
Aucun commentaire:
Enregistrer un commentaire