在webview Activity上打开Json url

时间:2017-01-29 21:11:25

标签: java android json webview move

我有一个从json URI(http://api.androidhive.info/feed/feed.json)获取内容的活动,并在列表视图中显示内容。

内容包括图片,帖子的URI,描述等。每个内容项目都有自己的URI。

我不想使用网络浏览器打开点击的URI,而是在具有网页浏览功能的另一个活动中打开它。

很抱歉重新提出这个问题我有一个问题。我从http:// www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley获得了一个很好的源代码和一个很棒的源代码我试图通过点击链接在app webview中打开时遇到问题

这是JSON DATA

{
    "feed": [


        {
            "id": 2,
            "name": "TIME",
            "image": "http://api.androidhive.info/feed/img/time_best.jpg",
            "status": "30 years of Cirque du Soleil's best photos",
            "profilePic": "http://api.androidhive.info/feed/img/time.png",
            "timeStamp": "1403375851930",
            "url": "http://ti.me/1qW8MLB"
        },
        {
            "id": 11,
            "name": "A. R. rahman",
            "image": "http://api.androidhive.info/feed/img/ar_bw.jpg",
            "status": "",
            "profilePic": "http://api.androidhive.info/feed/img/ar.jpg",
            "timeStamp": "1403375851930",
            "url": ""
        }
    ]
}

这是MainActivity.java

package info.androidhive.listviewfeed;

public class MainActivity extends Activity {

private static final String TAG = MainActivity.class.getSimpleName();

private ListView listView;

private FeedListAdapter listAdapter;

private List<FeedItem> feedItems;

private String URL_FEED = "http://api.androidhive.info/feed/feed.json";

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listView = (ListView) findViewById(R.id.list);

        feedItems = new ArrayList<FeedItem>();

        listAdapter = new FeedListAdapter(this, feedItems);
        listView.setAdapter(listAdapter);

        // These two lines not needed,
        // just to get the look of facebook (changing background color & hiding the icon)
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
        getActionBar().setIcon(
                   new ColorDrawable(getResources().getColor(android.R.color.transparent)));

        // We first check for cached request
        Cache cache = AppController.getInstance().getRequestQueue().getCache();
        Entry entry = cache.get(URL_FEED);
        if (entry != null) {
            // fetch the data from cache
            try {
                String data = new String(entry.data, "UTF-8");
                try {
                    parseJsonFeed(new JSONObject(data));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

        } else {
            // making fresh volley request and getting json
            JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                    URL_FEED, null, new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            VolleyLog.d(TAG, "Response: " + response.toString());
                            if (response != null) {
                                parseJsonFeed(response);
                            }
                        }
                    }, new Response.ErrorListener() {

                        @Override
                        public void onErrorResponse(VolleyError error) {
                            VolleyLog.d(TAG, "Error: " + error.getMessage());
                        }
                    });

            // Adding request to volley request queue
            AppController.getInstance().addToRequestQueue(jsonReq);
        }

    }

    /**
     * Parsing json reponse and passing the data to feed view list adapter
     * */
    private void parseJsonFeed(JSONObject response) {
        try {
            JSONArray feedArray = response.getJSONArray("feed");

            for (int i = 0; i < feedArray.length(); i++) {
                JSONObject feedObj = (JSONObject) feedArray.get(i);

                FeedItem item = new FeedItem();
                item.setId(feedObj.getInt("id"));
                item.setName(feedObj.getString("name"));

                // Image might be null sometimes
                String image = feedObj.isNull("image") ? null : feedObj
                        .getString("image");
                item.setImge(image);
                item.setStatus(feedObj.getString("status"));
                item.setProfilePic(feedObj.getString("profilePic"));
                item.setTimeStamp(feedObj.getString("timeStamp"));

                // url might be null sometimes
                String feedUrl = feedObj.isNull("url") ? null : feedObj
                        .getString("url");
                item.setUrl(feedUrl);

                feedItems.add(item);
            }

            // notify data changes to list adapater
            listAdapter.notifyDataSetChanged();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

这是我在http:// api.androidhive.info/feed/feed.json获取链接时创建的webview.java,点击后在webview中打开

public class webview extends Activity{

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webview);
        String getStringFromEdittext = "https:// www.google.co.in"+      getIntent().getExtras().getString("text");
        WebView wb = (WebView)findViewById(R.id.webView1);

        wb.setWebViewClient(new WebViewClient());
        System.out.println("URL"+getStringFromEdittext);
        wb.loadUrl(getStringFromEdittext );
        wb.getSettings().setJavaScriptEnabled(true);
        Button button = (Button)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                           Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                           startActivity(intent);
                    }
                });
}
}

1 个答案:

答案 0 :(得分:0)

这可能不是你想要的,但这就是我自己做的。这个答案有点与你需要的东西有关,而不是你所需要的百分之百。

据我所知,你希望链接在webview上打开而不是在android web浏览器上我借助帖子http://www.androidhive.info/2013/11/android-working-with-action-bar/

利用libaty重构上述编码

我再说一遍,这段代码可能不是您需要的100%,也适用于那些想要将上述代码用于wordpress或网站的人,如 www.example.com/page.php ?1D = 10

这将是MainActivity.java 公共类MainActivity扩展了Activity {

private static final String TAG = MainActivity.class.getSimpleName();
private ListView listView;
private FeedListAdapter listAdapter;
private List<FeedItem> feedItems;
private String URL_FEED = "http://api.androidhive.info/feed/feed.json";

// action bar
    private ActionBar actionBar;

@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    listView = (ListView) findViewById(R.id.list);
    feedItems = new ArrayList<FeedItem>();

    listAdapter = new FeedListAdapter(this, feedItems);
    listView.setAdapter(listAdapter);

    actionBar = getActionBar();

    // Hide the action bar title
            actionBar.setDisplayShowTitleEnabled(false);

    // These two lines not needed,
    // just to get the look of facebook (changing background color & hiding the icon)
    getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#3b5998")));
    getActionBar().setIcon(
               new ColorDrawable(getResources().getColor(android.R.color.transparent)));

    // We first check for cached request
    Cache cache = AppController.getInstance().getRequestQueue().getCache();
    Entry entry = cache.get(URL_FEED);
    if (entry != null) {
        // fetch the data from cache
        try {
            String data = new String(entry.data, "UTF-8");
            try {
                parseJsonFeed(new JSONObject(data));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

    } else {
        // making fresh volley request and getting json
        JsonObjectRequest jsonReq = new JsonObjectRequest(Method.GET,
                URL_FEED, null, new Response.Listener<JSONObject>() {

                    @Override
                    public void onResponse(JSONObject response) {
                        VolleyLog.d(TAG, "Response: " + response.toString());
                        if (response != null) {
                            parseJsonFeed(response);
                        }
                    }
                }, new Response.ErrorListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                    }
                });

        // Adding request to volley request queue
        AppController.getInstance().addToRequestQueue(jsonReq);
    }

}

/**
 * Parsing json reponse and passing the data to feed view list adapter
 * */
private void parseJsonFeed(JSONObject response) {
    try {
        JSONArray feedArray = response.getJSONArray("feed");

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            FeedItem item = new FeedItem();
            item.setId(feedObj.getInt("id"));
            item.setName(feedObj.getString("name"));

            // Image might be null sometimes
            String image = feedObj.isNull("image") ? null : feedObj
                    .getString("image");
            item.setImge(image);
            item.setStatus(feedObj.getString("status"));
            item.setProfilePic(feedObj.getString("profilePic"));
            item.setTimeStamp(feedObj.getString("timeStamp"));

            // url might be null sometimes
            String feedUrl = feedObj.isNull("url") ? null : feedObj
                    .getString("url");
            item.setUrl(feedUrl);
            feedItems.add(item);

            //Intent intent = new Intent(MainActivity.this, webview.class);
            //intent.putExtra("text", feedUrl.toString());
            //startActivity(intent);
        }

        // notify data changes to list adapater
        listAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.activity_main_actions, menu);

    // Associate searchable configuration with the SearchView
    SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView = (SearchView) menu.findItem(R.id.action_search)
            .getActionView();
    searchView.setSearchableInfo(searchManager
            .getSearchableInfo(getComponentName()));

    return super.onCreateOptionsMenu(menu);
}

/**
 * On selecting action bar icons
 * */
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Take appropriate action for each action item click
    switch (item.getItemId()) {
    case R.id.action_search:
        // search action
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

}

对于webview端,这是完整代码

SearchResultsActivity.java

包info.androidhive.listviewfeed;

public class SearchResultsActivity extends Activity {

private TextView txtQuery;

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

    // get the action bar
    ActionBar actionBar = getActionBar();

    // Enabling Back navigation on Action Bar icon
    actionBar.setDisplayHomeAsUpEnabled(true);

    txtQuery = (TextView) findViewById(R.id.txtQuery);

    handleIntent(getIntent());
}

@Override
protected void onNewIntent(Intent intent) {
    setIntent(intent);
    handleIntent(intent);
}

/**
 * Handling intent data
 */
private void handleIntent(Intent intent) {
    if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
        String query = "http://www.guruslodge.com/"+ intent.getStringExtra(SearchManager.QUERY);

        /**
         * Use this query to display search results like 
         * 1. Getting the data from SQLite and showing in listview 
         * 2. Making webrequest and displaying the data 
         * For now we just display the query only
         */
        txtQuery.setText("Search Query: " + query);

        WebView wb = (WebView)findViewById(R.id.webView1);

        wb.setWebViewClient(new WebViewClient());
        System.out.println("URL"+query);
        wb.loadUrl(query );
        wb.getSettings().setJavaScriptEnabled(true);

        wb.setWebViewClient(new WebViewClient() {
            public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) {
                try {
                    webView.stopLoading();
                } catch (Exception e) {
                }

                if (webView.canGoBack()) {
                    webView.goBack();
                }

                webView.loadUrl("about:blank");
                AlertDialog alertDialog = new AlertDialog.Builder(SearchResultsActivity.this).create();
                alertDialog.setTitle("Error");
                alertDialog.setMessage("Cannot connect to the Elitesbase Server. Check your internet connection and try again.");
                alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Try Again", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                        startActivity(getIntent());
                    }
                });

                alertDialog.show();
                super.onReceivedError(webView, errorCode, description, failingUrl);
            }
        });

    }

}

}

的AndroidManifest.xml

<uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="19" />

<uses-permission android:name="android.permission.INTERNET" />

<application
    android:name=".app.AppController"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <meta-data
            android:name="android.app.default_searchable"
            android:value=".SearchResultsActivity" />
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <!-- Search results activity -->
    <activity android:name=".SearchResultsActivity"
        android:parentActivityName=".MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.SEARCH" />
        </intent-filter>

        <meta-data
            android:name="android.app.searchable"
            android:resource="@xml/searchable" />

    </activity>
 <activity
        android:name=".webview"
        android:label="@string/app_name" >

        <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />

        <data
            android:host="elitesbase.com"
            android:pathPrefix="/cgi-sys/"
            android:scheme="http" />
        <data
            android:host="www.elitesbase.com"
            android:pathPrefix="/cgi-sys/"
            android:scheme="http" />
    </intent-filter>
    </activity>
</application>