如何将浏览器标签数据保存到Room数据库?

时间:2019-10-30 01:47:57

标签: android database android-room

我想将打开的浏览器选项卡保存到“房间”,以便在重新启动设备或长时间关闭应用程序后这些选项卡仍然存在。在运行时,应用程序崩溃,调试器显示空指针异常,该异常指向我试图使数据库保存数据的代码。我还注意到,它指向引用webview的一行,但是webview实际上处于不同的活动中。我什至不确定是否在正确的位置插入了此代码,可能还需要将其放在代码的其他位置,这是我要问的另一件事。我还想弄清楚如何向Room添加图像。我不得不注释掉这些行,因为我在图像上遇到了编译时错误。我考虑过尝试使用共享的首选项保存选项卡数据,但恐怕在设备重启时数据将不会持久。

MainActivity ...我将主要的Room代码放置在这些位置,如果需要,我可以发布整个课程。

     myappdatabase = Room.databaseBuilder(MainActivity.this,Myappdatabase.class,"userdb").allowMainThreadQueries().build();


public void loadWebFragment(String url)
    {

        if(!isValid(url))
        {
            url=defaultURL+url;
        }

        FragmentManager fm=getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        WebFragment frag = new WebFragment();
        Bundle args = new Bundle();
        args.putString("URL",url);
        frag.setArguments(args);
        webFragments.add(frag);
        ft.replace(R.id.frameLayout, frag);
        ft.commit();

        TabData TabData = new TabData();
        TabData.setTitle(webView.getTitle());
        TabData.setDesc(webView.getUrl());
        myappdatabase.mydao().insert_tab(TabData);

        CacheClass.cureWebFragment++;
        refreshTabCount();

    }

 @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId())
        {
            case R.id.opitonExit:
                finish();
                break;

            case R.id.optionTab: 

              WebFragment webFragment = new WebFragment();
              TabData TabData = new TabData();
              TabData.setTitle(webView.getTitle());
              TabData.setDesc(webView.getUrl());

              myappdatabase.mydao().insert_tab(TabData);
                loadWebFragment("");
                break;

TabData

    @Entity(tableName = "tabss")
public class TabData {
    public TabData() {

    }

    // public Bitmap image;
   // public String title,desc;



    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @PrimaryKey(autoGenerate = true)
    private int id;


    @ColumnInfo(name = "tabTitle")
    private String title;

    @ColumnInfo(name = "tabUrl")
    private String desc;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDesc() {
        return desc;
    }

    public void setDesc(String desc) {
        this.desc = desc;
    }

    public TabData(String title, String desc) {
        //this.image = image;
        this.title = title;
        this.desc = desc;
    }
}

WebTabs整个课程

 public class WebTabs extends AppCompatActivity {
   // public static ListView tabList;
    public static StackView tabList;
    ImageView homeBtn;

    public static StackAdapter adapter;

    public SQLiteDatabase mydatabase ;
    public static boolean goToMain=false;

    public boolean isRemovedTab = false;
    public int removedTab=-1;

    public static ArrayList<TabData>  tabss=new ArrayList<TabData>();



    String title,url;
    TabData TabData;
    public static Myappdatabase myappdatabase;
    List<TabData> datas;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web_tabs);

        homeBtn=findViewById(R.id.homeBtn);

        tabList=findViewById(R.id.stackView);

        myappdatabase = Room.databaseBuilder(WebTabs.this,Myappdatabase.class,"userdb").allowMainThreadQueries().build();

        homeBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
               loadMain();


            }
        });

        adapter=new StackAdapter(this,tabss);;

        tabList.setAdapter(adapter);

        tabList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

            //    if (title.contains("null") || url.contains("null"))
            //    {

                Intent mc=new Intent(WebTabs.this,MainActivity.class);

                TabData dt = (TabData) adapterView.getAdapter().getItem(i);

                mc.putExtra("URLfromTAB",dt.getDesc());
                mc.putExtra("SELECTEDFRAG",i);
                mc.putExtra("TOADD",false);
                MainActivity.curWebFragmentIsNewPage=true;



                startActivity(mc);
             //   }else {
                    TabData = new TabData();
                    TabData.setTitle(title);
                    TabData.setDesc(url);

                    myappdatabase.mydao().insert_tab(TabData);
             //       startActivity(new Intent(WebTabs.this,MainActivity.class));
                    finish();
                }
             // }
        //});

     //   tabss = (ArrayList<com.webb.ajp.webbrowser.TabData>) myappdatabase.mydao().tables();


         //   }
        });

        loadTabs();

    }

    public static void loadTabs(){
        {
            if(adapter==null)return;


            tabss.clear();

            for(WebFragment w:CacheClass.getWebFragments())
            {

                TabData obj=null;



                obj = new TabData(w.webView.getTitle(),w.webView.getUrl());

                if(obj!=null)
                    tabss.add(obj);


            }
            adapter.notifyDataSetChanged();
        }
    }


    public void loadMain(){
        Intent homeB=new Intent(WebTabs.this,MainActivity.class);
        homeB.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);

        CacheClass.cureWebFragment=-1;
        startActivity(homeB);
        finish();
    }


    public class StackAdapter extends BaseAdapter{

        ArrayList<TabData> datas=null;
        private Context mContext;

        StackAdapter( Context c , ArrayList<TabData> data){
            mContext=c;
            datas=data;
        }

        public StackAdapter(WebTabs webTabs) {

        }


        @Override
        public int getCount() {
            return datas.size();
        }

        @Override
        public TabData getItem(int i) {
            return datas.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(final int position, View view, ViewGroup viewGroup) {
            View grid;
            LayoutInflater inflater = (LayoutInflater) mContext
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if(goToMain)
            {

                goToMain=false;
                loadMain();
            }


            if (view == null ) {

                grid = new View(mContext);
                grid = inflater.inflate(R.layout.tabstacksingle, null);

                if(tabss.size()==0)
                {
                    grid.setVisibility(View.INVISIBLE);
                    grid.setEnabled(false);
                    return grid ;

                }

                TabData obj=datas.get(position);

                TextView title,desc;
                ImageView img,cls;

                title=grid.findViewById(R.id.tabTitle);
                desc=grid.findViewById(R.id.tabdesc);
                img=grid.findViewById(R.id.tabPic);
                cls=grid.findViewById(R.id.tabClose);




                title.setText(obj.getTitle());
                desc.setText(obj.getDesc());
             //   img.setImageBitmap(obj.getImage());


                cls.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        tabss.remove(position);
                        CacheClass.removeFragment(position);


                        isRemovedTab=true;
                        removedTab=position;
                        MainActivity.refreshTabCount();
                        adapter.notifyDataSetChanged();

                    }
                });


            } else {
                grid = (View) view;
            }



            return grid;
        }
    }


    public class TabAdapter extends ArrayAdapter<TabData> {

        Context mContext;

        int layoutResourceId;

        ArrayList<TabData> data = null;

        public TabAdapter(@NonNull Context context, int resource, ArrayList<TabData> objects) {
            super(context, resource, objects);
            mContext=context;
            layoutResourceId=resource;
            data=objects;


        }


        @NonNull
        @Override
        public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {



            if(convertView==null)
            {
                LayoutInflater inflater=((Activity)mContext).getLayoutInflater();
                convertView=inflater.inflate(layoutResourceId,parent,false);
            }

            TabData obj=data.get(position);

            TextView title,desc;
            ImageView img,cls;

            title=convertView.findViewById(R.id.tabTitle);
            desc=convertView.findViewById(R.id.tabdesc);
            img=convertView.findViewById(R.id.tabPic);
            cls=convertView.findViewById(R.id.tabClose);




            title.setText(obj.getTitle());
            desc.setText(obj.getDesc());
       //     img.setImageBitmap(obj.getImage());


            cls.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    tabss.remove(position);
                    CacheClass.removeFragment(position);
                    adapter.notifyDataSetChanged();
                    isRemovedTab=true;
                    removedTab=position;
                    MainActivity.refreshTabCount();

                }
            });
            TabData temp1 = data.get(position);



            return convertView;

        }
    }


    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if(isRemovedTab && CacheClass.cureWebFragment==-1)
        {
            loadMain();
        }
        else if(isRemovedTab && removedTab==CacheClass.cureWebFragment)
        {
            loadMain();
        }
    }
}

Logcat ...如果需要,我还可以提供整个logcat

E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.webb.ajp.webbrowser, PID: 26155
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.webkit.WebView.getTitle()' on a null object reference
    at com.webb.ajp.webbrowser.MainActivity.loadWebFragment(MainActivity.java:287)
    at com.webb.ajp.webbrowser.MainActivity$3.onEditorAction(MainActivity.java:152)
    at android.widget.TextView.onEditorAction(TextView.java:6292)
    at com.android.internal.widget.EditableInputConnection.performEditorAction(EditableInputConnection.java:138)
    at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:360)
    at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:85)
    at android.os.Handler.dispatchMessage(Handler.java:106)
    at android.os.Looper.loop(Looper.java:193)
    at android.app.ActivityThread.main(ActivityThread.java:6923)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:870)

0 个答案:

没有答案