2017-01-29 5 views
-1

J'ai une activité qui récupère le contenu d'un URI json (http://api.androidhive.info/feed/feed.json) et affiche le contenu dans une vue de liste.Ouvrir l'URL JSON sur la Webview Activité

Le contenu comprend des images, l'URI du message, la description, etc. Chaque élément de contenu possède son propre URI. Au lieu d'ouvrir les URI cliqués en utilisant un navigateur Web, je voudrais plutôt l'ouvrir en autre activité qui a une vue web.

Désolé pour re-poser cette question j'ai un problème.je obtenu un code source de http:// www.androidhive.info/2014/06/android-facebook-like-custom-listview-feed-using-volley qui fonctionne bien et un grand code source j'ai un problème en essayant de passer le lien cliquez pour ouvrir dans l'application webview.

c'est le 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": "" 
     } 
    ] 
} 

c'est le 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; 
    } 

} 

et c'est le webview.java i créé lorsque les liens de http:// api.androidhive.info/feed/feed.json être acquis passés et ouvert dans WebView lorsqu'on clique dessus

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

S'il vous plaît formater _all_ de votre code code. –

+0

qu'est-ce que vous voulez accomplir? ouvert dans une autre activité ou dans le même webview? –

+0

le MainActivity n'est pas un webview, il récupère des données du serveur de json et l'affiche je veux que l'URL soit ouverte dans une autre activité contenant le webview –

Répondre

0

Ceci n'est pas nécessairement ce que vous recherchez mais C'est ainsi que j'ai fait le mien. Cette réponse est un peu liée à ce dont vous avez besoin, pas à cent pour cent de ce dont vous avez besoin.

Je comprends que vous voulez que le lien pour ouvrir le WebView plutôt que navigateur web android je pris le libaty pour restructurer le codage ci-dessus à l'aide du poste http://www.androidhive.info/2013/11/android-working-with-action-bar/

je le répète encore une fois ce code pourrait ne pas être à 100 pour cent de ce que vous avez besoin et aussi pour son principalement pour les personnes qui veulent utiliser le code ci-dessus pour wordpress ou site web avec l'url www.example.com/page.php?1d=10

ce sera le MainActivity .java public class MainActivity étend l'activité {

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); 
    } 
} 

}

pour le côté webview cela est le code complet

SearchResultsActivity.java

paquet info.androidhive.listviewfeed;

SearchResultsActivity public class activité {

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

Espérons que cette réponse peut aider – Cashlex

+0

la réponse n'est pas exactement ce dont j'ai besoin mais c'est mieux que rien –