我希望在片段中的列表中显示数据库表中的所有值。为此,我使用自定义列表适配器在片段列表中显示光标中存在的值。
片段类在我的DatabaseHandler类和适配器类中显示了一些与构造函数相关的错误(表示构造函数未定义)。
我猜错误是由于我在Databasehandler类中使用的上下文变量。而且我认为我们需要为片段声明一些其他变量类型。 这也有助于其他人在片段中使用自定义列表适配器和listview,因为我几乎没有在网上找到任何好的教程。
所以当我在我的Handler类中创建一个像这样的新构造函数时 -
public Database_Schema(Fragment_Java fragment_Java) {
context = fragment_Java;
dbHelper = new DatabaseHelper(context);
}
编辑器再次抱怨要将上下文的类型更改为fragment_java。
这是我在我的应用程序中使用的DatabaseHandler类:
package info.aea.database;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper{
// Called when no database exists in disk and the helper class needs
// to create a new one.
SQLiteDatabase sqldb;
public long r;
public void onCreate(SQLiteDatabase _db)
{
// _db.execSQL(LoginTable.DATABASE_CREATE);
// sqldb = this.getWritableDatabase();
}
/* public LoginDatabaseHelper(Context context, String name,CursorFactory factory, int version) {
super(context, name, factory, version);
}*/
public DatabaseHelper(Context context) {
super(context, "java.db", null, 1);
sqldb = this.getWritableDatabase();
try {
sqldb.execSQL("CREATE TABLE if not exists SourceCodes (CodeID text PRIMARY KEY NOT NULL , " +
"CodeLang text NOT NULL, CodeTitle text NOT NULL , CodeSource text NOT NULL , " +
"CodeOutput text NOT NULL);");
ContentValues cv = new ContentValues();
cv.put("CodeID", "t1");
cv.put("CodeLang", "java");
cv.put("CodeTitle", "title1");
cv.put("CodeSource", "source code here1");
cv.put("CodeOutput", "output here1");
r = sqldb.insert("SourceCodes", null, cv);
//ContentValues cv2 = new ContentValues();
cv.put("CodeID", "t2");
cv.put("CodeLang", "java");
cv.put("CodeTitle", "title2");
cv.put("CodeSource", "source code here2");
cv.put("CodeOutput", "output here2");
r = sqldb.insert("SourceCodes", null, cv);
} catch (Exception e) {
// TODO: handle exception
}
}
// Called when there is a database version mismatch meaning that the version
// of the database on disk needs to be upgraded to the current version.
@Override
public void onUpgrade(SQLiteDatabase _db, int _oldVersion, int _newVersion)
{
// Log the version upgrade.
Log.w("TaskDBAdapter", "Upgrading from version " +_oldVersion + " to " +_newVersion + ", which will destroy all old data");
// Upgrade the existing database to conform to the new version. Multiple
// previous versions can be handled by comparing _oldVersion and _newVersion
// values.
// The simplest case is to drop the old table and create a new one.
_db.execSQL("DROP TABLE IF EXISTS " + Database_Schema.DATABASE_CREATE);
// Create a new one.
onCreate(_db);
}
}
下面是定义数据库模式并包含与表相关的CRUD操作方法的类 -
package info.aea.database;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
public class Database_Schema {
static final String DATABASE_NAME = "login.db";
static final int DATABASE_VERSION = 1;
public static final int NAME_COLUMN = 1;
// TODO: Create public field for each column in your table.
// SQL Statement to create a new database.
static final String DATABASE_CREATE = "create table "+" LOGIN "+
"( " +"ID"+" integer primary key autoincrement," + "USERNAME char unique,PASSWORD text, USERTYPE text); ";
// Variable to hold the database instance
public SQLiteDatabase db;
// Context of the application using the database.
private final Context context;
// Database open/upgrade helper
private DatabaseHelper dbHelper;
public Database_Schema(Context _context) {
context = _context;
dbHelper = new DatabaseHelper(context);
}
public Database_Schema open() throws SQLException {
db = dbHelper.getWritableDatabase();
return this;
}
public void close() {
db.close();
}
public SQLiteDatabase getDatabaseInstance(){
return db;
}
//---------------------CRUD Operations---------------------//
// get all query
public List<SourceCode_Table> getall(String lang) {
List<SourceCode_Table> codelist = new ArrayList<SourceCode_Table>();
String selectQuery = "SELECT * FROM SourceCodes where codelang='java'" ; // Select All Query
db = dbHelper.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to Vector
if (cursor.moveToFirst()) {
do {
SourceCode_Table a = new SourceCode_Table();
a.setCodeID(cursor.getString(0));
a.setCodeTitle(cursor.getString(1));
a.setCodeSource(cursor.getString(3));
a.setCodeOutput(cursor.getString(4));
codelist.add(a);
} while (cursor.moveToNext());
}
return codelist;
}
}
此外,我希望在单个DB_handler类中合并这些DB_related类。但它会产生一些奇怪的错误,或者如果没有错误编译则不会创建数据库。在这方面也需要帮助。我只是想删除那个额外的类,因为它在声明数据库模式和应用查询时会产生混淆。
对于名为源代码的表,我已经创建了一个适配器类。这是列表适配器类 -
package info.aea.database;
import info.devey.java.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class SourceCode_Adapter extends ArrayAdapter<String> {
private final Context context;
private final String[] CodeID;
private final String[] CodeLang;
private final String[] CodeTitle;
private final String[] CodeSource;
private final String[] CodeOutput;
public SourceCode_Adapter(Context context, String[] codeid, String[] codelang, String[] codetitle, String[] codesource, String[] codeoutput) {
super(context, R.layout.list_items, codeid);
this.context = context;
this.CodeID = codeid;
this.CodeLang = codelang;
this.CodeTitle = codetitle;
this.CodeSource = codesource;
this.CodeOutput = codeoutput;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.list_items, parent, false);
TextView textView = (TextView) rowView.findViewById(R.id.tvPat);
String test=(" code ID: "+ CodeID[position]+ "\n code Language: "+ CodeLang[position]+ "\n Code Title: "+
CodeTitle[position]+ "\n code Source: "+ CodeSource[position]+ "\n code output: "+ CodeOutput[position]);
textView.setText(test);
System.out.println("list values ------->> " + CodeID[position] + CodeLang[position] + CodeOutput[position] + CodeSource[position] + CodeTitle[position] );
return rowView;
}
}
最后这里是Fragment类,我想在列表中显示数据库值。但是当我尝试实例化一个新的DB对象时,编辑器会显示一个错误标记,并建议更改构造函数声明和上下文类型。
猜测所有这些都是由于那些写得不好的数据库类。
package info.aea.drawer;
import info.aea.database.Database_Schema;
import info.aea.database.SourceCode_Adapter;
import info.aea.database.SourceCode_Table;
import info.devey.java.R;
import java.util.List;
import android.app.AlertDialog;
import android.app.Fragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
public class Fragment_Java extends Fragment {
String[] codeid;
String codelang[];
String codetitle[];
String codesource[];
String codeoutput[];
ListView listview;
SQLiteDatabase db;
Database_Schema logindb;
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_java, container,false);
logindb=new Database_Schema(this);
logindb=logindb.open();
String lang="java";
List<SourceCode_Table> ls = logindb.getall(lang);
codeid = new String[ls.size()];
codelang = new String[ls.size()];
codetitle = new String[ls.size()];
codesource = new String[ls.size()];
codeoutput = new String[ls.size()];
for(int i = 0; i<ls.size();i++) {
codeid[i]= ls.get(i).getCodeID();
codelang[i]= ls.get(i).getCodeLang();
codetitle[i]= ls.get(i).getCodeTitle();
codesource[i]= ls.get(i).getCodeSource();
codeoutput[i]= ls.get(i).getCodeOutput();
Log.v("code id","-------"+ls.get(i).getCodeID());
Log.v("code lang","-------"+ls.get(i).getCodeLang());
System.out.println("patname==============+++++++++++++++++++"+ codeid);
System.out.println("date==============+++++++++++++++++++"+ codelang);
}
SourceCode_Adapter adapter = new SourceCode_Adapter(this, codeid, codelang, codetitle, codesource, codeoutput);
listview.setAdapter(adapter);
}
}
因此需要帮助来纠正这些错误。我愿意将整个项目作为导出文件共享,以便使调试变得简单。
答案 0 :(得分:0)
如果您的活动类扩展了Activity,则可以使用getApplicatoinContext()获取应用程序上下文。但是当您的Activity从Fragment扩展时,此方法将不可用。 当您的活动扩展Fragment时,使用getActivity()来获取活动的上下文。
public class MainActivity extends Fragment {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Getting application context
Context context = getActivity();
}
}
所以我换了
logindb=new Database_Schema(this);
logindb=logindb.open();
带
logindb = new Database_Schema(getActivity());
logindb = logindb.open()