不幸的是,应用程序在片段视图中单击已添加书签的项目时停止了我正在使用 json 来存储标题和链接

Application unfortunately stopped on clicking bookmarked item in fragment view Im using json to store title & links

您好,我正在开发带有书签的 Webview 应用程序。使用 fab 按钮为页面添加书签。单击 fab 按钮标题和 links 存储在 json 中,书签页面 link 和标题可以在 fragment_fav.xml 中查看 但是当我点击保存的项目应用程序停止。我希望 links 加载到 webview 而不是停止。 如下所述的代码列表和 logcat 错误 我是 android 的新手,请评论您的答案。

LOGCAT

03-07 12:44:12.088 14138-14138/seacoders.abhilash.bogguru E/dalvikvm: Could not find class 'android.support.v4.app.ActivityCompat$SharedElementCallback23Impl', referenced from method android.support.v4.app.ActivityCompat.setEnterSharedElementCallback
03-07 12:44:12.089 14138-14138/seacoders.abhilash.bogguru E/dalvikvm: Could not find class 'android.support.v4.app.ActivityCompat$SharedElementCallback21Impl', referenced from method android.support.v4.app.ActivityCompat.setEnterSharedElementCallback
03-07 12:44:12.090 14138-14138/seacoders.abhilash.bogguru E/dalvikvm: Could not find class 'android.support.v4.app.ActivityCompat$SharedElementCallback23Impl', referenced from method android.support.v4.app.ActivityCompat.setExitSharedElementCallback
03-07 12:44:12.092 14138-14138/seacoders.abhilash.bogguru E/dalvikvm: Could not find class 'android.support.v4.app.ActivityCompat$SharedElementCallback21Impl', referenced from method android.support.v4.app.ActivityCompat.setExitSharedElementCallback
03-07 12:44:12.169 14138-14138/seacoders.abhilash.bogguru E/AndroidRuntime: FATAL EXCEPTION: main
                                                                            android.content.ActivityNotFoundException: Unable to find explicit activity class {seacoders.abhilash.bogguru/seacoders.abhilash.bogguru.HomeFragment}; have you declared this activity in your AndroidManifest.xml?
                                                                                at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1624)
                                                                                at android.app.Instrumentation.execStartActivity(Instrumentation.java:1423)
                                                                                at android.app.Activity.startActivityForResult(Activity.java:3488)
                                                                                at android.support.v4.app.BaseFragmentActivityApi16.startActivityForResult(BaseFragmentActivityApi16.java:54)
                                                                                at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:67)
                                                                                at android.support.v4.app.ActivityCompat.startActivityForResult(ActivityCompat.java:152)
                                                                                at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:793)
                                                                                at android.support.v4.app.FragmentActivity$HostCallbacks.onStartActivityFromFragment(FragmentActivity.java:907)
                                                                                at android.support.v4.app.Fragment.startActivity(Fragment.java:1009)
                                                                                at android.support.v4.app.Fragment.startActivity(Fragment.java:998)
                                                                                at seacoders.abhilash.bogguru.FavFragment.onItemClick(FavFragment.java:82)
                                                                                at android.widget.AdapterView.performItemClick(AdapterView.java:298)
                                                                                at android.widget.AbsListView.performItemClick(AbsListView.java:1128)
                                                                                at android.widget.AbsListView$PerformClick.run(AbsListView.java:2815)
                                                                                at android.widget.AbsListView.run(AbsListView.java:3574)
                                                                                at android.os.Handler.handleCallback(Handler.java:800)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:100)
                                                                                at android.os.Looper.loop(Looper.java:194)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5371)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:525)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                                                                                at dalvik.system.NativeStart.main(Native Method)

FavFragment.java

package seacoders.abhilash.bogguru;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;


public class FavFragment extends Fragment {

    ArrayList<HashMap<String, String>> listRowData;
    public static final String PREFERENCES = "PREFERENCES_NAME";
    public static final String WEB_LINKS = "links";
    public static final String WEB_TITLE = "title";
    public static String TAG_TITLE = "title";
    public static String TAG_LINK = "link";

    ListView listView;
    ListAdapter adapter;
    LinearLayout linearLayout;
    SwipeRefreshLayout mSwipeRefreshLayout;

    public static final String TITLE = "BOOKMARKS";

    public static FavFragment newInstance() {

        return new FavFragment();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View v=inflater.inflate(R.layout.fragment_fav, container, false);
        listView = v.findViewById(R.id.listView);
        linearLayout = v.findViewById(R.id.emptyList);
        mSwipeRefreshLayout = v.findViewById(R.id.swipeToRefresh);
        mSwipeRefreshLayout.setColorSchemeResources(R.color.colorAccent);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                new LoadBookmarks().execute();

            }
        });
        new LoadBookmarks().execute();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Object o = listView.getAdapter().getItem(position);
                if (o instanceof Map) {
                    Map map = (Map) o;
                    Intent in = new Intent(getActivity(),HomeFragment.class);
                   in.putExtra("url", String.valueOf(map.get(TAG_LINK)));
                    String.valueOf(map.get(TAG_LINK));

                    startActivity(in);
                }
            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
                Object o = listView.getAdapter().getItem(i);
                if (o instanceof Map) {
                    Map map = (Map) o;
                    deleteBookmark(String.valueOf(map.get(TAG_TITLE)), String.valueOf(map.get(TAG_LINK)));
                }
                return true;
            }
        });
        return v;
    }

    private void deleteBookmark(final String title, final String link) {
        new AlertDialog.Builder(getActivity())
                .setTitle("DELETE")
                .setMessage("Confirm that you want to delete this bookmark?")
                .setPositiveButton("YES", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
                        String jsonLink = sharedPreferences.getString(WEB_LINKS, null);
                        String jsonTitle = sharedPreferences.getString(WEB_TITLE, null);
                        if (jsonLink != null && jsonTitle != null) {
                            Gson gson = new Gson();
                            ArrayList<String> linkArray = gson.fromJson(jsonLink, new TypeToken<ArrayList<String>>() {
                            }.getType());

                            ArrayList<String> titleArray = gson.fromJson(jsonTitle, new TypeToken<ArrayList<String>>() {
                            }.getType());
                            linkArray.remove(link);
                            titleArray.remove(title);
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString(WEB_LINKS, new Gson().toJson(linkArray));
                            editor.putString(WEB_TITLE, new Gson().toJson(titleArray));
                            editor.apply();

                            new LoadBookmarks().execute();
                        }
                        dialogInterface.dismiss();
                    }
                }).setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();
            }
        }).show();
    }



    private class LoadBookmarks extends AsyncTask<String, String, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... args) {
            // updating UI from Background Thread
            getActivity().runOnUiThread(new Runnable() {
                public void run() {
                    SharedPreferences sharedPreferences = getActivity().getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
                    String jsonLink = sharedPreferences.getString(WEB_LINKS, null);
                    String jsonTitle = sharedPreferences.getString(WEB_TITLE, null);
                    listRowData = new ArrayList<>();

                    if (jsonLink != null && jsonTitle != null) {
                        Gson gson = new Gson();
                        ArrayList<String> linkArray = gson.fromJson(jsonLink, new TypeToken<ArrayList<String>>() {
                        }.getType());

                        ArrayList<String> titleArray = gson.fromJson(jsonTitle, new TypeToken<ArrayList<String>>() {
                        }.getType());

                        for (int i = 0; i < linkArray.size(); i++) {
                            HashMap<String, String> map = new HashMap<>();

                            if (titleArray.get(i).length() == 0)
                                map.put(TAG_TITLE, "Bookmark " + (i + 1));
                            else
                                map.put(TAG_TITLE, titleArray.get(i));
                                map.put(TAG_LINK, linkArray.get(i));
                            listRowData.add(map);
                        }

                        adapter = new SimpleAdapter(getActivity(),
                                listRowData, R.layout.bookmark_list_row,
                                new String[]{TAG_TITLE, TAG_LINK},
                                new int[]{R.id.title, R.id.link});
                        listView.setAdapter(adapter);
                    }

                    linearLayout.setVisibility(View.VISIBLE);
                    listView.setEmptyView(linearLayout);
                }
            });
            return null;
        }

        protected void onPostExecute(String args) {
            mSwipeRefreshLayout.setRefreshing(false);
        }

    }
}

fragment_fav.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/favourite"
    android:layout_width="match_parent"
    android:layout_height="match_parent">


    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeToRefresh"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="@dimen/fab_margin">

        <ListView
            android:id="@+id/listView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </android.support.v4.widget.SwipeRefreshLayout>

    <LinearLayout
        android:id="@+id/emptyList"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:gravity="center"
        android:orientation="vertical"
        android:visibility="gone">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="WHOOPS"
            android:textColor="#212121"
            android:textSize="20sp"
            android:textStyle="bold" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:gravity="center"
            android:text="There are no bookmarks at the moment"
            android:textColor="#212121" />

    </LinearLayout>

</android.support.constraint.ConstraintLayout>

HomeFragment.java

package seacoders.abhilash.bogguru;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.app.Fragment;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.net.URI;
import java.util.ArrayList;

import static android.content.Intent.getIntent;

public class HomeFragment extends Fragment {
    WebView wv;
    TextView txt;
    ProgressBar pbar;
    DatabaseHelper myDb;

    public static final String PREFERENCES = "PREFERENCES_NAME";
    String WEB_LINKS = "links";
    String WEB_TITLE = "title";
    String current_page_url;
    public static final String TITLE = "Home";

    public static HomeFragment newInstance() {
        return new HomeFragment();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        //return inflater.inflate(R.layout.fragment_home, container, false);
        View v=inflater.inflate(R.layout.fragment_home, container, false);
        wv = (WebView)v.findViewById(R.id.webview);
        wv.loadUrl("http://www.google.com");
        current_page_url = wv.getUrl();
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
        String links = sharedPreferences.getString(WEB_LINKS, null);
        if (links != null) {
            Gson gson = new Gson();
            ArrayList<String> linkList = gson.fromJson(links, new TypeToken<ArrayList<String>>() {
            }.getType());
        }

        FloatingActionButton fab = (FloatingActionButton)v.findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {
                SharedPreferences sharedPreferences = getActivity().getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
                String jsonLink = sharedPreferences.getString(WEB_LINKS, null);
                String jsonTitle = sharedPreferences.getString(WEB_TITLE, null);

                if (jsonLink != null && jsonTitle != null) {
                    Gson gson = new Gson();
                    ArrayList<String> linkList = gson.fromJson(jsonLink, new TypeToken<ArrayList<String>>() {
                    }.getType());
                    ArrayList<String> titleList = gson.fromJson(jsonTitle, new TypeToken<ArrayList<String>>() {
                    }.getType());

                    if (linkList.contains(current_page_url)) {
                        linkList.remove(wv.getUrl());
                        titleList.remove(wv.getTitle().trim());
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString(WEB_LINKS, new Gson().toJson(linkList));
                        editor.putString(WEB_TITLE, new Gson().toJson(titleList));
                        editor.apply();
                        Snackbar.make(view, "Bookmark removed from favourites", Snackbar.LENGTH_LONG)
                                .setAction("Action", null).show();
                    } else {
                        linkList.add(wv.getUrl());
                        titleList.add(wv.getTitle().trim());
                        SharedPreferences.Editor editor = sharedPreferences.edit();
                        editor.putString(WEB_LINKS, new Gson().toJson(linkList));
                        editor.putString(WEB_TITLE, new Gson().toJson(titleList));
                        editor.apply();
                        Snackbar.make(view, "Bookmark added, view in favourites", Snackbar.LENGTH_LONG)
                                .setAction("Action", null).show();
                    }
                } else {

                    ArrayList<String> linkList = new ArrayList<>();
                    ArrayList<String> titleList = new ArrayList<>();
                    linkList.add(wv.getUrl());
                    titleList.add(wv.getTitle());
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(WEB_LINKS, new Gson().toJson(linkList));
                    editor.putString(WEB_TITLE, new Gson().toJson(titleList));
                    editor.apply();
                    Snackbar.make(view, "Bookmark added, view in favourites", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            }
        });

        WebSettings webSettings = wv.getSettings();
        webSettings.setJavaScriptEnabled(true);
        pbar = (ProgressBar) v.findViewById(R.id.pg1);
        txt = (TextView) v.findViewById(R.id.txtload);
        wv.setWebViewClient(new MyWebViewClient());
        wv.setOnKeyListener(new View.OnKeyListener()
        {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event)
            {
                if(event.getAction() == KeyEvent.ACTION_DOWN)
                {
                    switch(keyCode)
                    {
                        case KeyEvent.KEYCODE_BACK:
                            if(wv.canGoBack())
                            {
                                wv.goBack();

                                return true;
                            }
                            break;
                    }
                }
                return false;
            }
        });
        return v;

    }

        public class MyWebViewClient extends WebViewClient {

            public void onReceivedError(WebView v, int errorCode, String description, String failingUrl) {
                wv.loadUrl("file:///android_asset/error.html");
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                System.out.println("loading... please wait");
                pbar.setVisibility(View.VISIBLE);
                txt.setVisibility(View.VISIBLE);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                System.out.println("finished loading");
                pbar.setVisibility(View.GONE);
                txt.setVisibility(View.GONE);
            }
        }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="seacoders.abhilash.bogguru">
    <uses-permission android:name="android.permission.INTERNET"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"></uses-permission>
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.READ_HISTORY_BOOKMARKS"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_HISTORY_BOOKMARKS"></uses-permission>
    <uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>

    <application
        android:largeHeap="true"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

错误来自 listview clicklistner

在 google 上搜索 call fragment in fragment 您可以尝试以下代码

// Create fragment and give it an argument specifying the article it should show
ArticleFragment newFragment = new ArticleFragment();  
Bundle args = new Bundle();  
args.putInt(ArticleFragment.ARG_POSITION, position);  
newFragment.setArguments(args);

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack so the user can navigate back
transaction.replace(R.id.fragment_container, newFragment);  
transaction.addToBackStack(null);

// Commit the transaction
transaction.commit(); 

现在你的代码看起来像

 new LoadBookmarks().execute();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {

                Object o = listView.getAdapter().getItem(position);
                if (o instanceof Map) {
                    Map map = (Map) o;
                    HomeFragment newFragment = new HomeFragment();  
                    Bundle args = new Bundle();  
                    args.puString("url", String.valueOf(map.get(TAG_LINK)));  
                    newFragment.setArguments(args);

                   FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

                   transaction.replace(R.id.fragment_container, newFragment);  
                   transaction.addToBackStack(null);

                   transaction.commit(); 

                }
            }
        });

大家好,我使用了以下代码,我的问题已经解决了

 listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Object o = listView.getAdapter().getItem(position);
                 if (o instanceof Map) {
                    final Map map = (Map) o;
                    Intent in = new Intent(getActivity(),HomeFragment.class);
                    in.putExtra("url", String.valueOf(map.get(TAG_LINK)));

                     System.out.println("loading url..."+String.valueOf(map.get(TAG_LINK))+" please wait");
                     HomeFragment.wv.post(new Runnable() {
                         public void run() {
                             HomeFragment.wv.loadUrl(String.valueOf(map.get(TAG_LINK)));
                         }
                     });

                     seacoders.abhilash.bogguru.MainActivity.changefrag();

                }

            }

        });

MainActivity 中的以下代码。

 private static int getItem(int i) {
    return mViewPager.getCurrentItem() + i;
  }

  public static void changefrag() {
    mViewPager.setCurrentItem(getItem(-1),true);
  }