无法从片段中的 SQLite 获取数据

Posted

技术标签:

【中文标题】无法从片段中的 SQLite 获取数据【英文标题】:Unable to get data from SQLite in fragment 【发布时间】:2020-12-06 17:17:24 【问题描述】:

我在 android Studio 中创建了一个 SQLite 数据库,我想将数据从 EditText 插入到表中,并将该数据传递给另一个 Activity。当我在一个活动上执行此操作并尝试从另一个活动中获取时,它正在工作。但是当我尝试从另一个片段中获取数据时出现错误。

我的数据库助手类

 package  fragments;

    import android.content.ContentValues;
    import android.content.Context;
    import android.database.Cursor;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.util.Log;

public class createDBHelper extends SQLiteOpenHelper 

    public static final String KEY_ID = "_id";
    public static final String ITEM_NAME_COLUMN = "ITEM_NAME_COLUMN";
    public static final String ITEM_GRADE_COLUMN = "ITEM_GRADE_COLUMN";
    public static final String ITEM_CATEGORY_COLUMN = "ITEM_CATEGORY_COLUMN";


    public static final String DATABASE_NAME = "myItemDatabase.db";
    public static final String DATABASE_TABLE = "ItemInfo";
    public static final int DATABASE_VERSION = 7;

    private static final String DATABASE_CREATE ="create table " + DATABASE_TABLE + " (" +
            KEY_ID + " text, " +
            ITEM_NAME_COLUMN + " text, " +
            ITEM_GRADE_COLUMN + " text);";






    public createDBHelper(Context context)
        super(context, DATABASE_NAME, null, DATABASE_VERSION);


    


    @Override
    public void onCreate(SQLiteDatabase db) 

        db.execSQL((DATABASE_CREATE));
    

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) 

        Log.w("TaskDBAdapter", "Upgrading from version" +
                oldVersion + ",which will destroy all old data");

        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);

    

    public boolean insertData(String firstname,String lastname,String message)

        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues(); //instance of class
        contentValues.put(KEY_ID,firstname);//2 parameters(Column name in which you
        contentValues.put(ITEM_NAME_COLUMN,lastname);//2 parameters(Column name in which you
        contentValues.put(ITEM_GRADE_COLUMN,message);//2 parameters(Column name in which you
        //you want to insert data
        // and second is the value itself


        long result = db.insert(DATABASE_TABLE,null,contentValues);
        if(result == -1) 
            return false;
        
        else 

            return true;
        
    //ends insertData functin

    public Cursor getAllData()
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor result = db.rawQuery("select * from " + DATABASE_TABLE,null);
        return result;
    //ends cursor


    public boolean updateData(String id,String firstname,String lastname,String credits)
        SQLiteDatabase db = this.getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(KEY_ID,id);
        contentValues.put(ITEM_NAME_COLUMN,firstname);//2 parameters(Column name in which you
        //you want to insert data
        // and second is the value itself

        contentValues.put(ITEM_GRADE_COLUMN, credits);

        db.update(DATABASE_TABLE,contentValues,"_id = ?",new String[]id);

        return true;
    

    public Integer deleteData()
        SQLiteDatabase db = this.getWritableDatabase();
        return db.delete(DATABASE_TABLE,null,null);
    

我输入数据的活动

package fragments;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.navigation.ui.AppBarConfiguration;

import android.app.ActionBar;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;


import com.example.workflowbexfa.R;

public class createMessage extends AppCompatActivity implements View.OnClickListener 
    public static final int REQUEST_CODE = 1;


    createDBHelper myDataBase= new createDBHelper(this);


    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_message);
        getSupportActionBar().hide();




        ImageView imageViewgoback=(ImageView) findViewById(R.id.button_back);
        imageViewgoback.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                finish();
            
        );

        EditText receiver_id= findViewById(R.id.receiver_id);
        final String receiver=receiver_id.getText().toString();
        EditText mailcontent= findViewById(R.id.mail_content);
        final String mail_content=mailcontent.getText().toString();


        ImageView imageViewsend=(ImageView) findViewById(R.id.button_send);
        imageViewsend.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                myDataBase.deleteData();
                EditText receiver_id= findViewById(R.id.receiver_id);
                final String receiver=receiver_id.getText().toString();
                EditText mailcontent= findViewById(R.id.mail_content);
                final String mail_content=mailcontent.getText().toString();
                EditText subjectedit=findViewById(R.id.subjectedit);
                final String subjectcontext=subjectedit.getText().toString();
                myDataBase.insertData(receiver,subjectcontext,mail_content);

               //myDataBase.insertData("Tolgaaaaaasa","TUTAR");
               //myDataBase.insertData("TUTAAAAR","TOLGAAA");
                Intent intent = new Intent(createMessage.this,db_deneme.class);
                startActivity(intent);
            
        );

        ImageView imageViewattach=(ImageView) findViewById(R.id.attach);
        imageViewattach.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT);
                chooseFile.setType("*/*");
                chooseFile = Intent.createChooser(chooseFile, "Choose a file");
                startActivity(chooseFile);
            
        );
    



    @Override
    public void onClick(View view) 

    

当我这样做时没有问题

package fragments;

import androidx.appcompat.app.AppCompatActivity;

import android.database.Cursor;
import android.os.Bundle;
import android.widget.TextView;

import com.example.workflowbexfa.R;

import java.util.ArrayList;
import java.util.List;

import static fragments.createDBHelper.ITEM_GRADE_COLUMN;
import static fragments.createDBHelper.ITEM_NAME_COLUMN;
import static fragments.createDBHelper.KEY_ID;

public class db_deneme extends AppCompatActivity 
    createDBHelper myDataBase= new createDBHelper(this);
    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_db_deneme);
        TextView id_text=(TextView) findViewById(R.id.textView10);
        TextView id_text2=(TextView) findViewById(R.id.textView11);
        TextView id_text3=(TextView) findViewById(R.id.textView3);
        Cursor resultset= myDataBase.getAllData();

        List<String > myList= new ArrayList();
        if (resultset.moveToFirst()) 
while(!resultset.isAfterLast())
                String dbdeneme=resultset.getString(resultset.getColumnIndex(KEY_ID));
                myList.add(dbdeneme);
                String dbdeneme2=resultset.getString(resultset.getColumnIndex(ITEM_NAME_COLUMN));
                myList.add(dbdeneme2);
    String dbdeneme3=resultset.getString(resultset.getColumnIndex(ITEM_GRADE_COLUMN));
    myList.add(dbdeneme3);
                resultset.moveToNext();
            

        
        id_text.setText(myList.get(0));
        id_text2.setText(myList.get(1));
        id_text3.setText(myList.get(2));
        //id_text2.setText(myList.get(3));










    

但是当我尝试在这个片段中这样做时

package fragments;

import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;

import com.example.workflowbexfa.R;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static fragments.createDBHelper.ITEM_GRADE_COLUMN;
import static fragments.createDBHelper.ITEM_NAME_COLUMN;
import static fragments.createDBHelper.KEY_ID;


public class Sentfragment extends Fragment implements View.OnClickListener 
    createDBHelper myDataBase= new createDBHelper(getActivity());
    List<SentMessage> sentMessageList;
    ListView listView;
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState )
        View rootView = inflater .inflate(R.layout.sentfragment,container,false);











        listView = (ListView) rootView.findViewById(R.id.listView_sent);
        ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Gönderilenler");





        sentMessageList=new ArrayList<>();

        List<String > myList= new ArrayList();
        //sentMessageList.add(new SentMessage(R.drawable.sentmailicon,"Alıcı:Ahmet","Üzgünüm şu anda cevap veremiyorum.","12:00","Proje Hk.",R.drawable.staricon));
        Cursor resultset=myDataBase.getAllData();
        if (resultset.moveToFirst()) 
            while(!resultset.isAfterLast())
                while(!resultset.isAfterLast())
                    String dbdeneme=resultset.getString(resultset.getColumnIndex(KEY_ID));
                    myList.add(dbdeneme);
                    String dbdeneme2=resultset.getString(resultset.getColumnIndex(ITEM_NAME_COLUMN));
                    myList.add(dbdeneme2);
                    String dbdeneme3=resultset.getString(resultset.getColumnIndex(ITEM_GRADE_COLUMN));
                    myList.add(dbdeneme3);
                    resultset.moveToNext();
                
            

        





        List<HashMap<String, String>> listItems = new ArrayList<>();

        final SentMyCustomListAdapter adapter=new SentMyCustomListAdapter(getContext(),R.layout.my_list_item_sent,sentMessageList);
        listView.setAdapter(adapter);

        ImageView imageViewCreate=(ImageView) rootView.findViewById(R.id.addicon);
        imageViewCreate.setOnClickListener(new View.OnClickListener() 
            @Override
            public void onClick(View view) 
                sentMessageList.add(new SentMessage(R.drawable.sentmailicon,"asd","Üzgünüm şu anda cevap veremiyorum.","12:00","Proje Hkkk.",R.drawable.staricon));
                adapter.notifyDataSetChanged();
            
        );

        return rootView;
    

    @Override
    public void onClick(View view) 

    

我收到此错误

2020-08-17 17:31:02.551 3495-3495/? E/Zygote: GL_OOM reserved vma failed, errno:22
2020-08-17 17:31:02.687 3495-3495/? E/e.workflowbexf: Unknown bits set in runtime_flags: 0x28000
2020-08-17 17:31:02.749 3495-3495/? E/RefClass: java.lang.reflect.InvocationTargetException
2020-08-17 17:31:03.096 3495-3495/com.example.workflowbexfa E/PswScreenModeFeature: failed to get oppposcreenmode service:binder null
2020-08-17 17:31:03.096 3495-3495/com.example.workflowbexfa E/PswScreenModeFeature: failed to get oppposcreenmode service:interface null.
2020-08-17 17:31:05.962 3495-3495/com.example.workflowbexfa E/ANR_LOG: >>> msg's executing time is too long
2020-08-17 17:31:05.962 3495-3495/com.example.workflowbexfa E/ANR_LOG: Blocked msg =  when=-2s30ms what=0 target=android.view.Choreographer$FrameHandler callback=android.view.Choreographer$FrameDisplayEventReceiver  , cost  = 2014 ms
2020-08-17 17:31:05.962 3495-3495/com.example.workflowbexfa E/ANR_LOG: >>>Current msg List is:
2020-08-17 17:31:05.962 3495-3495/com.example.workflowbexfa E/ANR_LOG: Current msg <1> =  when=-14h29m13s993ms what=0 target=android.view.ViewRootImpl$ViewRootHandler callback=android.view.-$$Lambda$ViewRootImpl$7A_3tkr_Kw4TZAeIUGVlOoTcZhg 
2020-08-17 17:31:05.962 3495-3495/com.example.workflowbexfa E/ANR_LOG: Current msg <2> =  when=-2s5ms what=0 target=android.view.ViewRootImpl$ViewRootHandler callback=androidx.appcompat.app.AppCompatDelegateImpl$2 
2020-08-17 17:31:05.962 3495-3495/com.example.workflowbexfa E/ANR_LOG: Current msg <3> =  when=-1s998ms what=0 target=android.view.ViewRootImpl$ViewRootHandler callback=androidx.appcompat.app.ToolbarActionBar$1 
2020-08-17 17:31:05.962 3495-3495/com.example.workflowbexfa E/ANR_LOG: Current msg <4> =  when=-1s957ms what=0 target=android.os.Handler callback=androidx.core.content.res.ResourcesCompat$FontCallback$2 
2020-08-17 17:31:05.962 3495-3495/com.example.workflowbexfa E/ANR_LOG: Current msg <5> =  when=-1s956ms what=0 target=android.os.Handler callback=androidx.core.content.res.ResourcesCompat$FontCallback$1 
2020-08-17 17:31:05.962 3495-3495/com.example.workflowbexfa E/ANR_LOG: Current msg <6> =  when=-1s951ms what=0 target=android.os.Handler callback=androidx.core.content.res.ResourcesCompat$FontCallback$2 
2020-08-17 17:31:05.962 3495-3495/com.example.workflowbexfa E/ANR_LOG: Current msg <7> =  when=-1s951ms what=0 target=android.os.Handler callback=androidx.core.content.res.ResourcesCompat$FontCallback$1 
2020-08-17 17:31:05.962 3495-3495/com.example.workflowbexfa E/ANR_LOG: Current msg <8> =  when=-1s947ms what=0 target=android.os.Handler callback=androidx.core.content.res.ResourcesCompat$FontCallback$2 
2020-08-17 17:31:05.963 3495-3495/com.example.workflowbexfa E/ANR_LOG: Current msg <9> =  when=-1s946ms what=0 target=android.os.Handler callback=androidx.core.content.res.ResourcesCompat$FontCallback$1 
2020-08-17 17:31:05.963 3495-3495/com.example.workflowbexfa E/ANR_LOG: Current msg <10> =  when=-1s943ms what=0 target=android.os.Handler callback=androidx.core.content.res.ResourcesCompat$FontCallback$2 
2020-08-17 17:31:05.963 3495-3495/com.example.workflowbexfa E/ANR_LOG: >>>CURRENT MSG DUMP OVER<<<
2020-08-17 17:31:08.374 3495-3495/com.example.workflowbexfa E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.workflowbexfa, PID: 3495
    java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.File android.content.Context.getDatabasePath(java.lang.String)' on a null object reference
        at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:371)
        at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:317)
        at fragments.createDBHelper.getAllData(createDBHelper.java:88)
        at fragments.Sentfragment.onCreateView(Sentfragment.java:55)
        at androidx.fragment.app.Fragment.performCreateView(Fragment.java:2698)
        at androidx.fragment.app.FragmentStateManager.createView(FragmentStateManager.java:320)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1187)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1356)
        at androidx.fragment.app.FragmentManager.moveFragmentToExpectedState(FragmentManager.java:1434)
        at androidx.fragment.app.FragmentManager.moveToState(FragmentManager.java:1497)
        at androidx.fragment.app.BackStackRecord.executeOps(BackStackRecord.java:447)
        at androidx.fragment.app.FragmentManager.executeOps(FragmentManager.java:2169)
        at androidx.fragment.app.FragmentManager.executeOpsTogether(FragmentManager.java:1992)
        at androidx.fragment.app.FragmentManager.removeRedundantOperationsAndExecute(FragmentManager.java:1947)
        at androidx.fragment.app.FragmentManager.execPendingActions(FragmentManager.java:1849)
        at androidx.fragment.app.FragmentManager$4.run(FragmentManager.java:413)
        at android.os.Handler.handleCallback(Handler.java:899)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:238)
        at android.app.ActivityThread.main(ActivityThread.java:7864)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:998)

【问题讨论】:

【参考方案1】:

您正在尝试在主线程内使用数据库。您应该在后台线程中执行此操作。

【讨论】:

【参考方案2】:

我通过不在 Sentfragment 而是在 onCreateView 中初始化我的 DBHelper 解决了这个问题。

【讨论】:

以上是关于无法从片段中的 SQLite 获取数据的主要内容,如果未能解决你的问题,请参考以下文章

当我从用户获取数据并将其保存到 SQLite 数据库中时,我应该怎么做才能使列表视图在片段中工作

从 2 个不同片段的 sqlite 中的 2 个表中获取信息

如何从 Javascript 中的 SQLite 数据库中获取表数据?

如何在片段内的 recylerview 列表中显示 SQLite 数据库数据?

如何从 Firebase 获取数据到 Recyclerview 中的片段?

如何从片段中的 JSON 响应中的对象获取数据