2017-01-29 2 views
-1

У меня есть активность, которая извлекает содержимое из json URI (http://api.androidhive.info/feed/feed.json) и отображает содержимое в виде списка.Open Json url on webview Activity

Содержание включает изображения, URI сообщения, описание и т. Д. Каждый элемент контента имеет свой собственный URI.

Вместо того, чтобы открывать URI с использованием URI с помощью веб-браузера, я бы хотел открыть его в еще один вид деятельности, у которого есть веб-просмотр.

Извините за повторное задание этого вопроса У меня проблема. Я получил исходный код от http:// www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley, который хорошо работает и отличный исходный код. У меня проблема с попыткой передать ссылку на ссылку, чтобы открыть ее в веб-приложении приложения.

это 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; 
    } 

} 

и это webview.java я создал, когда ссылки получил от http:// api.androidhive.info/feed/feed.json быть принят и открыт в 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); 
        } 
       }); 
} 
} 
+0

Отформатируйте _все_ вашего кода в качестве кода. –

+0

чего вы хотите достичь? открыть в другом действии или в том же webview? –

+0

MainActivity не является веб-просмотром, он извлекает данные из json-сервера и отображает его. Я хочу, чтобы URL-адрес был открыт в другой Activity, содержащей webview. –

ответ

0

Это может быть не совсем то, что вы ищете вот как я сделал свое. этот ответ имеет отношение к тому, что вам нужно на сто процентов, что вам нужно.

Я понимаю, что вы хотите, чтобы ссылка, чтобы открыть на WebView, а не андроид веб-браузер я взял libaty реструктурировать выше кодирование с помощью шеста http://www.androidhive.info/2013/11/android-working-with-action-bar/

повторяю еще раз этот код не может быть 100 процентов что вам нужно, а также его для в основном для людей, которые хотят использовать приведенный выше код для WordPress или веб-сайт с URL, как www.example.com/page.php?1d=10

это будет MainActivity .java Открытый класс 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"; 

// 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;

общественный класс SearchResultsActivity расширяет активность {

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> 

+0

Надеюсь, что этот ответ может помочь – Cashlex

+0

ответ не совсем то, что мне нужно, но это лучше, чем ничего –