Webview为空白或为不同的URL加载相同的页面

时间:2012-07-12 18:18:12

标签: java android

搜索API正在返回一些元数据,即网址“eventURL”和trackbackurl,即“trackBack”。我将数据放在listview中,每行包含一些数据和一个唯一的url和trackback url。当用户点击listview中的行时,会显示一个警告对话框,显示用户2的选项。单击选项1应该在webview中启动trackback url,而单击第二个opion应该在webview中启动eventURL。我已经为它创建了一个WebViewActivity,问题是我的webview始终是空白的。

主要活动

package my.stayactive.plan;


import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import my.stayactive.plan.ActiveHelper.ApiException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;


public class StayActiveActivity extends Activity implements OnItemClickListener {

    //private EditText m_search_text;
    protected EditText m_zip;
    private ListView m_search_results;
    private Button m_search_btn;
    private JSONArray m_results; 
    private LayoutInflater m_inflater;
    private InputMethodManager m_ctrl;
    private Spinner m_radius;
    private Spinner m_activity_selector;
    public static int radius = 0;
    public static String activities;
    public String url;
    public String trackBack;
    public static String assetId;


    static final private int EXIT_ID = Menu.FIRST;



    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);
       // m_search_text = (EditText) findViewById(R.id.search_text);
        m_zip = (EditText) findViewById(R.id.zip);
        m_search_btn = (Button) findViewById(R.id.search_button);
       // m_searchm_results = (ListView) findViewById(R.id.lview);
        m_search_btn .setOnClickListener(go_handler);

        m_ctrl = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        m_inflater = LayoutInflater.from(this);
        addListenerOnSpinnerItemSelection();
        addListenerOnSpinner1ItemSelection();

      m_search_results = (ListView)findViewById(R.id.lview);
      m_search_results.setOnItemClickListener(this);

    }

    public void addListenerOnSpinnerItemSelection() {
        m_radius = (Spinner) findViewById(R.id.spinner);
        m_radius.setOnItemSelectedListener(new CustomOnItemSelectedListener());
      }

    public void addListenerOnSpinner1ItemSelection(){
        m_activity_selector = (Spinner) findViewById(R.id.spinner1);
        m_activity_selector.setOnItemSelectedListener(new ActivitySelectedListener());
        }

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        super.onCreateOptionsMenu(menu);

        menu.add(0, EXIT_ID, 0, R.string.exit);
        return true;
        }
    @Override
    public boolean onOptionsItemSelected (MenuItem item){

        switch (item.getItemId()){
        case EXIT_ID:
            finish();
            return true;

        }

        return super.onOptionsItemSelected(item);

    }



    OnClickListener go_handler = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //m_ctrl.hideSoftInputFromWindow(m_search_text.getWindowToken(), 0);
            m_ctrl.hideSoftInputFromWindow(m_zip.getWindowToken(), 0);

            //String searchText = Uri.encode(m_search_text.getText().toString());
            String zip = Uri.encode(m_zip.getText().toString());

            new SearchTask().execute("?k=Fall+Classic" + "&m=meta:channel=" + activities + "&l="+ zip + "&r=" + radius);
            // Show a toast showing the search text
            Toast.makeText(getApplicationContext(),
                    getString(R.string.search_msg) + " " + 
                    activities, Toast.LENGTH_LONG).show();
        }
    };

    private class SearchTask extends AsyncTask<String, Integer, String>
    {

        ProgressDialog dialog;

            @Override
            protected void onPreExecute() {

                dialog = ProgressDialog.show(StayActiveActivity.this,"","Please Wait...");

                super.onPreExecute();
            }

            @Override
            protected String doInBackground(String... params) {
                try {
                    String result = ActiveHelper.download(params [0]);
                    return result;
                } catch (ApiException e) {
                    e.printStackTrace();
                    Log.e("alatta", "Problem making search request");
                }
                return "";
            }
            @Override
            protected void onPostExecute(String result) {
                dialog.hide();
                try {
                    JSONObject obj = new JSONObject(result);
                    m_results = obj.getJSONArray("_results");
                    if (m_results == null || m_results.length() == 0)
                    {
                        Toast.makeText(getApplicationContext(),
                                "No Results found for " + activities, 
                                Toast.LENGTH_LONG).show();

                    }
                    else
                        m_search_results.setAdapter(new JSONAdapter(getApplicationContext()));
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }

    private class JSONAdapter extends BaseAdapter
    {
        public JSONAdapter(Context c){

        }

        public int getCount() 
        {
        return  m_results.length();
            }

        public Object getItem(int arg0){
            return null;
        }

        public long getItemId(int pos){
            return pos;

        }

        public View getView(int pos, View convertView, ViewGroup parent) {
            View tv;
            TextView t;

            if (convertView == null)
                tv = m_inflater.inflate (R.layout.item, parent, false);
            else
                tv = convertView;
            try {
                /* For each entry in the ListView, we need to populate 
                 * its text and timestamp */
                t = (TextView) tv.findViewById(R.id.text);
                JSONObject obj = m_results.getJSONObject(pos);

                t.setText (obj.getString("title").replaceAll("</?(?i:<|>|...|&quot|&amp|;|)(.|\n)*?>", ""));
                        //("\\<.*?\\>", ""))

                t = (TextView) tv.findViewById(R.id.created_at);
                JSONObject meta = obj.getJSONObject("meta");
              //  url = meta.getString("eventURL");
                trackBack = obj.getString("url");
                assetId = meta.getString("assetTypeId");
                //String eventDate = meta.getString("startDate");
                Calendar currentDate = Calendar.getInstance();
                long dateNow = currentDate.getTimeInMillis();


               String eventDate = meta.getString("startDate");
               String endDate = meta.getString("endDate");
               SimpleDateFormat formatter  = new SimpleDateFormat("yyyy-MM-dd");
               Date date = null;
               Date date2 = null;
            try {
                date = formatter.parse(eventDate);
                date2 = formatter.parse(endDate);
            } catch (java.text.ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
               long modifiedDate= date.getTime();
               long modifiedEndDate = date2.getTime();



                if ( Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedDate)) > 0 || Long.valueOf(dateNow).compareTo(Long.valueOf(modifiedEndDate)) > 0)

                {

                    t.setText ("Was:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n" + meta.getString("eventURL") +"\n"+ obj.getString("url"));

                }
                    else {
                    t.setText ("When:" + "\t"+eventDate+"\n"+"Location:" +"\t" +meta.getString("location")+"\n"+ meta.getString("eventURL") +"\n"+ obj.getString("url"));
                }


            } catch (JSONException e) {

                Log.e("alatta", e.getMessage());
            }
            return tv;
        }
    }



    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        /*try {
        JSONObject obj = m_results.getJSONObject(position);
        JSONObject meta = obj.getJSONObject("meta");
        url = meta.getString("eventURL"); 


        //Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
        //StayActiveActivity.this.startActivity(intent);

        } catch (JSONException e) {

            Log.e("alatta",e.getMessage());
        }*/



        // TODO Auto-generated method stub
        final CharSequence[] items = {"Register", "Additional Information"};
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Please Select an Option");
        builder.setItems(items, new DialogInterface.OnClickListener() {


            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub

                if (which == 0){

                    Intent intent1 = new Intent (StayActiveActivity.this, ReviewActivity.class);
                    StayActiveActivity.this.startActivity(intent1);

                }

                else if ( which == 1){
                Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
                StayActiveActivity.this.startActivity(intent);

                }

            }
        });
    AlertDialog alert = builder.create();
    alert.show();

    }}

WebViewActivity

package my.stayactive.plan;


import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

    public class WebViewActivity extends StayActiveActivity {

            private WebView webView;

            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.webview);

                webView = (WebView) findViewById(R.id.webView);
                WebSettings setting = webView.getSettings();
                setting.setJavaScriptEnabled(true);
                if (url != null && url.length()>0) {
                webView.loadUrl(url);

            }
              } 


            }

2 个答案:

答案 0 :(得分:3)

您没有将网址传递给WebViewActivity。要做到这一点:

  • 在致电startActivity()之前,请使用setData()将您的网址附加到意图。
  • onCreate()的{​​{1}}中,使用getData()检索网址,然后加载。

或搜索WebViewActivity。您可以使用Intent传输大量数据。

- 已编辑 -

示例:

设置数据:

putExtra(...)

要检索数据:

import android.net.Uri;

//...
Intent intent = new Intent (StayActiveActivity.this, WebViewActivity.class);
intent.setData(Uri.parse("your-url"));
StayActiveActivity.this.startActivity(intent);

答案 1 :(得分:0)

我的猜测是您的网址正在重定向,并且您没有处理重定向,因此没有显示任何内容。

尝试将此添加到您的网络视图活动中:

mWebView.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url)
        {
            view.loadUrl(url);
            return false;
        }
});

此外,这也是一个好主意,因为您在WebView活动中有一个if语句来记录URL,以便您可以确定它实际上正确地将其放入活动中。如果不是,Web视图将永远不会加载任何内容。

编辑:实际上仔细看看你似乎没有在任何地方设置'url'变量,因此它会为null,因此不会因为if语句而调用你的loadUrl方法。