문제

데이터는 다 얻었는데..하지만 webview url(UrlWeb) 을 사용할 수 없습니다. 즉, 목록 항목을 클릭하면 웹 보기에서 열립니다. 목록을 클릭하면 해당 URL이 WebView 활동에 전달되어야 합니다..이를 달성하는 방법, 해당 URL을 저장하는 방법은 무엇입니까??누가 좀 도와주세요..

내 주요활동:

public class MainActivity extends Activity {

ListView mListView;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);    

    // URL to the JSON data         
    String strUrl = "http://www.mulnivasisangh.com/aman/listweb.json";

    // Creating a new non-ui thread task to download json data 
    DownloadTask downloadTask = new DownloadTask();

    // Starting the download process
    downloadTask.execute(strUrl);

    // Getting a reference to ListView of activity_main
    mListView = (ListView) findViewById(R.id.lv_countries);

    }

/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    try{
            URL url = new URL(strUrl);

            // Creating an http connection to communicate with url 
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url 
            urlConnection.connect();

            // Reading data from url 
            iStream = urlConnection.getInputStream();

            BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

            StringBuffer sb  = new StringBuffer();

            String line = "";
            while( ( line = br.readLine())  != null){
                sb.append(line);
            }

            data = sb.toString();

            br.close();

    }catch(Exception e){
            Log.d("Exception while downloading url", e.toString());
    }finally{
            iStream.close();
    }

    return data;
}



/** AsyncTask to download json data */
private class DownloadTask extends AsyncTask<String, Integer, String>{
    String data = null;
            @Override
            protected String doInBackground(String... url) {
                    try{
                        data = downloadUrl(url[0]);

                    }catch(Exception e){
                        Log.d("Background Task",e.toString());
                    }
                    return data;
            }

            @Override
            protected void onPostExecute(String result) {

                    // The parsing of the xml data is done in a non-ui thread 
                    ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();

                    // Start parsing xml data
                    listViewLoaderTask.execute(result);                        

            }
}

/** AsyncTask to parse json data and load ListView */
private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

    JSONObject jObject;
    // Doing the parsing of xml data in a non-ui thread 
    @Override
    protected SimpleAdapter doInBackground(String... strJson) {
        try{
            jObject = new JSONObject(strJson[0]);
            CountryJSONParser countryJsonParser = new CountryJSONParser();
            countryJsonParser.parse(jObject);
        }catch(Exception e){
            Log.d("JSON Exception1",e.toString());
        }

        // Instantiating json parser class
        CountryJSONParser countryJsonParser = new CountryJSONParser();

        // A list object to store the parsed countries list
        List<HashMap<String, Object>> countries = null;

        try{
            // Getting the parsed data as a List construct
            countries = countryJsonParser.parse(jObject);
        }catch(Exception e){
            Log.d("Exception",e.toString());
        }          

        // Keys used in Hashmap 
        String[] from = { "country","flag","details", "URL"};

        // Ids of views in listview_layout
        int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details,R.id.tv_URL};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item         
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);  

        return adapter;
    }

    /** Invoked by the Android on "doInBackground" is executed */
    protected void onPostExecute(SimpleAdapter adapter) {

        // Setting adapter for the listview
        mListView.setAdapter(adapter);

        for(int i=0;i<adapter.getCount();i++){
            HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
            String imgUrl = (String) hm.get("flag_path");
            ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

            HashMap<String, Object> hmDownload = new HashMap<String, Object>();
            hm.put("flag_path",imgUrl);
            hm.put("position", i);

            // Starting ImageLoaderTask to download and populate image in the listview 
            imageLoaderTask.execute(hm);
        }

        mListView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                    long arg3) {
                // TODO Auto-generated method stub
                        String URL = ((TextView) view.findViewById(R.id.tv_URL)).getText().toString();//this will take the value of the invincible textView
                        Intent i = new Intent(MainActivity.this, WebViewActivity.class);
                        i.putExtra("URL", URL);
                        startActivity(i); 
                      } 
});
    }
    }

/** AsyncTask to download and load an image in ListView */
private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

    @Override
    protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {

        InputStream iStream=null;
        String imgUrl = (String) hm[0].get("flag_path");
        int position = (Integer) hm[0].get("position");

        URL url;
        try {
            url = new URL(imgUrl);

            // Creating an http connection to communicate with url
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

            // Connecting to url                
            urlConnection.connect();

            // Reading data from url 
            iStream = urlConnection.getInputStream();

            // Getting Caching directory 
            File cacheDirectory = getBaseContext().getCacheDir();

            // Temporary file to store the downloaded image 
            File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");               

            // The FileOutputStream to the temporary file
            FileOutputStream fOutStream = new FileOutputStream(tmpFile);

            // Creating a bitmap from the downloaded inputstream
            Bitmap b = BitmapFactory.decodeStream(iStream);             

            // Writing the bitmap to the temporary file as png file
            b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);              

            // Flush the FileOutputStream
            fOutStream.flush();

            //Close the FileOutputStream
            fOutStream.close();             

            // Create a hashmap object to store image path and its position in the listview
            HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

            // Storing the path to the temporary image file
            hmBitmap.put("flag",tmpFile.getPath());

            // Storing the position of the image in the listview
            hmBitmap.put("position",position);              

            // Returning the HashMap object containing the image path and position
            return hmBitmap;                


        }catch (Exception e) {              
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(HashMap<String, Object> result) {
        // Getting the path to the downloaded image
        String path = (String) result.get("flag");          

        // Getting the position of the downloaded image
        int position = (Integer) result.get("position");

        // Getting adapter of the listview
        SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();

        // Getting the hashmap object at the specified position of the listview
        HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);   

        // Overwriting the existing path in the adapter 
        hm.put("flag",path);

        // Noticing listview about the dataset changes
        adapter.notifyDataSetChanged(); 
    }
}

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

}

내 나라JSONParser:

public class CountryJSONParser {

// Receives a JSONObject and returns a list
public List<HashMap<String,Object>> parse(JSONObject jObject){      

    JSONArray jCountries = null;
    try {       
        // Retrieves all the elements in the 'countries' array 
        jCountries = jObject.getJSONArray("webs");
    } catch (JSONException e) {
        e.printStackTrace();
    }

     // Invoking getCountries with the array of json object
     // where each json object represent a country
    return getCountries(jCountries);
}


private List<HashMap<String, Object>> getCountries(JSONArray jCountries){
    int countryCount = jCountries.length();
    List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
    HashMap<String, Object> country = null; 

    // Taking each country, parses and adds to list object 
    for(int i=0; i<countryCount;i++){
        try {
            // Call getCountry with country JSON object to parse the country 
            country = getCountry((JSONObject)jCountries.get(i));
            countryList.add(country);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    return countryList;
}



// Parsing the Country JSON object 
private HashMap<String, Object> getCountry(JSONObject jCountry){

    HashMap<String, Object> country = new HashMap<String, Object>();
    String countryName = "";
    String flag="";
    String language = "";
    String capital = "";
    String web ="";


    try {
        countryName = jCountry.getString("Nom");
        flag = jCountry.getString("UrlImatge");
        language = jCountry.getString("Descripcio");
        capital = jCountry.getString("Id");
        web = jCountry.getString("UrlWeb");

        String details = "Descripcio : " + language + "\n" +
                "Id : " + capital + "\n" + "URL: " + web + "\n";

        country.put("country", countryName);
        country.put("UrlImatge", R.drawable.blank);
        country.put("flag_path", flag);
        country.put("details", details);
        country.put("URL", web);

    } catch (JSONException e) {         
        e.printStackTrace();
    }       
    return country;
}

}

미리 감사드립니다..

도움이 되었습니까?

해결책

데이터를 전달하고 싶을 때 이 트릭을 사용합니다. listview 다른 활동으로.

1- 나는 추가한다 textView 나에게 item-list.xml 이는 R.layout.lv_layout 귀하의 경우 가시성을 없애십시오. android:visibility="gone"

2- 여기에 URL 문자열을 추가합니다. textView, 가시성이 없기 때문에 목록 보기에 표시되지 않습니다.

String[] from = { "country","flag","details", "URL"};

// Ids of views in listview_layout
int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details, R.id.tv_country_URL};//the forth one is the textView you set it as gone.

3인치 OnItemClick 함수에 다음을 추가하면 됩니다:

String URL = ((TextView) view.findViewById(R.id.tv_country_URL)).getText().toString();//this will take the value of the invincible textView
Intent i = new Intent(MainActivity.this, WebView.class);
i.putExtra("URL", URL);
startActivity(i);

4- webView 활동에서 getIntent를 사용하여 URL을 가져와 로드합니다.

아직 모호하다면 알려주세요.당신이 아이디어를 얻었기를 바랍니다.

편집하다

당신은 필요하지 않습니다 getURL 더 이상 기능하지 않는 것 같았어요 getCountries 반환하지 않습니다 hashMap URL용.따라서 당신이 해야 할 일은 lv_layout 각 URL을 그 안에 넣으세요.

위의 4단계를 따르세요.

Post의 3단계:

protected void onPostExecute(SimpleAdapter adapter) {

    // Setting adapter for the listview
    mListView.setAdapter(adapter);

    for(int i=0;i<adapter.getCount();i++){
        HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
        String imgUrl = (String) hm.get("flag_path");
        ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

        HashMap<String, Object> hmDownload = new HashMap<String, Object>();
        hm.put("flag_path",imgUrl);
        hm.put("position", i);

        // Starting ImageLoaderTask to download and populate image in the listview 
        imageLoaderTask.execute(hm);
    }

    mListView.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View view, int arg2,
                long arg3) {
            // TODO Auto-generated method stub
                            String URL = ((TextView) view.findViewById(R.id.tv_URL)).getText().toString();//this will take the value of the invincible textView
                    Intent i = new Intent(MainActivity.this, WebView.class);
                    i.putExtra("URL", URL);
                    startActivity(i); 
                  }      

편집하다

webViewActivity의 경우 다음과 같이 이전 활동에서 추가 정보를 얻어야 합니다.

public class WebViewActivity extends Activity{
private WebView webView;

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

    webView = (WebView) findViewById(R.id.webview);
    webView.setWebViewClient(new MyWebViewClient());


    String url = getIntent().getExtras().getString("URL")

    if (null != url) {
        webView.getSettings().setJavaScriptEnabled(true);
        webView.loadUrl(url);
    }
}

private class MyWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

}

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top