gpt4 book ai didi

java - 为什么Fragment无法连接数据库

转载 作者:行者123 更新时间:2023-12-01 19:28:21 25 4
gpt4 key购买 nike

我有 2 个类似的项目。第一个,我可以连接数据库。然而,在第二个我不能。

它们之间的区别:

第一个项目:我在 mainActivity 中使用 dbconnection

第二个项目:我在fragment中使用dbconnection,然后将数据传递给cardAdapter

fragment :

public class Frag1 extends Fragment {
private RecyclerView rv;
private CardAdapter adapter;
private EditText editText;
private ImageButton imageButton;
private DbConnection db= new DbConnection(getActivity());

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {


View view =inflater.inflate(R.layout.fragment_frag1, container,false);
rv= (RecyclerView)view.findViewById(R.id.rv);
editText=view.findViewById(R.id.editText);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));


final ArrayList<Word> words = new ArrayList<>() ;
dbCopy();

final ArrayList<Word> wordArrayList = new WordData().AllWords(db);

adapter= new CardAdapter(getActivity(),wordArrayList);
rv.setAdapter(adapter);

return view;
}
public void dbCopy(){
DatabaseCopyHelper helper = new DatabaseCopyHelper(getActivity()) ;
try {
helper.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
helper.openDataBase();
}
}

卡适配器:

public class CardAdapter extends RecyclerView.Adapter<CardAdapter.CardTasarimTutucu> {
private Context mContext;
private ArrayList<Word> words;


public CardAdapter(Context mContext, ArrayList<Word> words) {
this.mContext = mContext;
this.words = words;
}


public class CardTasarimTutucu extends RecyclerView.ViewHolder{
private CardView rowCard;
private CheckedTextView rowText;

public CardTasarimTutucu(@NonNull View itemView) {
super(itemView);
this.rowCard = itemView.findViewById(R.id.rowCard);
this.rowText = itemView.findViewById(R.id.rowText);
}
}
@NonNull
@Override
public CardTasarimTutucu onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_design,parent,false);
return new CardTasarimTutucu(v);
}

@Override
public void onBindViewHolder(@NonNull final CardTasarimTutucu holder, int position) {
String word = words.get(position).getMean();
holder.rowText.setText(word);
holder.rowText.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (holder.rowText.isChecked()) {
// set cheek mark drawable and set checked property to false

holder.rowText.setCheckMarkDrawable(null);
holder.rowText.setChecked(false);
} else {
// set cheek mark drawable and set checked property to true

holder.rowText.setCheckMarkDrawable(R.drawable.ic_check_black_24dp);
holder.rowText.setChecked(true);
}

}
});

}

@Override
public int getItemCount() {
return words.size();
}

}

DatabaseCopyHelper

public class DatabaseCopyHelper extends SQLiteOpenHelper  {


//The Android's default system path of your application database.
String DB_PATH =null;

private static String DB_NAME = "dictionary.db";

private SQLiteDatabase myDataBase;

private final Context myContext;

/**
* Constructor
* Takes and keeps a reference of the passed context in order to access to the application assets and resources.
* @param context
*/
public DatabaseCopyHelper(Context context) {

super(context, DB_NAME, null, 1);
this.myContext = context;
DB_PATH="/data/data/"+context.getPackageName()+"/"+"databases/";


}

/**
* Creates a empty database on the system and rewrites it with your own database.
* */
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");

}
}

}

/**
* Check if the database already exist to avoid re-copying the file each time you open the application.
* @return true if it exists, false if it doesn't
*/
private boolean checkDataBase(){

SQLiteDatabase checkDB = null;

try{
String myPath = DB_PATH + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);

}catch(SQLiteException e){

//database does't exist yet.

}

if(checkDB != null){

checkDB.close();

}

return checkDB != null ? true : false;
}

/**
* Copies your database from your local assets-folder to the just created empty database in the
* system folder, from where it can be accessed and handled.
* This is done by transfering bytestream.
* */
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) {

}


@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
db.disableWriteAheadLogging();
}
//return cursor

}

DbConnection

public class DbConnection extends SQLiteOpenHelper {

public DbConnection (@Nullable Context context) {

super(context, "dictionary.db", null, 1);


}

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE IF NOT EXISTS \"Words\" (\n" +
"\t\"Id\"\tINTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,\n" +
"\t\"Name\"\tTEXT,\n" +
"\t\"Mean\"\tTEXT\n" +
");");
db.execSQL("CREATE TABLE IF NOT EXISTS \"MyList\" (\n" +
"\t\"Id\"\tINTEGER NOT NULL,\n" +
"\t\"Name\"\tTEXT,\n" +
"\t\"Mean\"\tTEXT,\n" +
"\tFOREIGN KEY(\"Id\") REFERENCES \"Words\"(\"Id\"),\n" +
"\tPRIMARY KEY(\"Id\")\n" +
");");


}

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

}
}

这些是相同的:

dbConnection
databaseCopyHelper
word(object)
wordData(includes sql query)
dbCopy method
database

where is my fault?

最佳答案

您有可能在 getActivity() 中得到 null,因为它需要在创建 Fragment 的 Activity 阶段调用。

这是我给你的建议

public class Frag1 extends Fragment {
private RecyclerView rv;
private CardAdapter adapter;
private EditText editText;
private ImageButton imageButton;
private DbConnection db;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {


View view = inflater.inflate(R.layout.fragment_frag1, container, false);
rv = (RecyclerView) view.findViewById(R.id.rv);
editText = view.findViewById(R.id.editText);
rv.setHasFixedSize(true);
rv.setLayoutManager(new LinearLayoutManager(this.getActivity()));




return view;
}

@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
db = new DbConnection(getActivity());
final ArrayList<Word> words = new ArrayList<>();
dbCopy();

final ArrayList<Word> wordArrayList = new WordData().AllWords(db);

adapter = new CardAdapter(getActivity(), wordArrayList);
rv.setAdapter(adapter);
}

public void dbCopy() {
DatabaseCopyHelper helper = new DatabaseCopyHelper(getActivity());
try {
helper.createDataBase();
} catch (IOException e) {
e.printStackTrace();
}
helper.openDataBase();
}

}

关于java - 为什么Fragment无法连接数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59286549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com