在onClick中访问修改后的变量

时间:2014-07-30 12:16:46

标签: android variables

在下面的代码中,我如何访问onClick方法中的变量?我正在尝试获取单击保存按钮时保存的URL。但是,由于它没有在onCreate之前声明,当我尝试使用它时,有一条红线。我如何使变量全局化,以便我可以从另一个方法中获取它?

我试图访问[urlStr]的变量:

   package sp.com;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.widget.Button;
import android.widget.TextView;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RadioGroup;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import android.app.TabActivity;
import android.widget.TabHost;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.content.Context;
import android.database.Cursor;
import android.support.v4.widget.CursorAdapter;
import android.media.MediaPlayer;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.KeyEvent;

public class DetailForm extends Activity {
    private EditText name = null;
    private EditText author = null;
    private EditText url = null;
    private EditText duedate = null;
    private RadioGroup category = null;
    private BookHelper helper = null;
    private Button save = null;
    private Button delete = null;
    String urlStr;

    private String bookId = null;


    CheckBox chkbox;

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

        helper = new BookHelper(this);
        name = (EditText) findViewById(R.id.name);
        author = (EditText) findViewById(R.id.author1);
        duedate = (EditText) findViewById(R.id.duedate);
        url = (EditText) findViewById(R.id.url);
        category = (RadioGroup) findViewById(R.id.category1);

        save = (Button) findViewById(R.id.save);
        save.setOnClickListener(onSave);

        delete = (Button) findViewById(R.id.delete);
        delete.setOnClickListener(onDelete);

        bookId = getIntent().getStringExtra("ID");
        if (bookId != null) {
            load();
        }


    }

    private void load() {
        Cursor c = helper.getById(bookId);
        c.moveToFirst();
        name.setText(helper.getName(c));
        author.setText(helper.getAuthor(c));
        duedate.setText(helper.getDue(c));
        url.setText(helper.getUrl(c));

        if (helper.getcat(c).equals("Action")) {
            category.check(R.id.action);
        } else if (helper.getcat(c).equals("Mystery")) {
            category.check(R.id.mystery);
        } else if (helper.getcat(c).equals("Thriller")) {
            category.check(R.id.thriller);
        } else if (helper.getcat(c).equals("Romance")) {
            category.check(R.id.romance);
        } else if (helper.getcat(c).equals("Horror")) {
            category.check(R.id.horror);
        } else {
            category.check(R.id.others);
        }
        c.close();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        helper.close();
    }

    private View.OnClickListener onDelete = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (bookId == null){
                return;
            }

            else {
                helper.delete(bookId);
                bookId=null;
            }

            finish();
        }
    };

    private View.OnClickListener onSave = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            String nameStr = name.getText().toString();
            String authStr = author.getText().toString();
            urlStr = url.getText().toString();
            String dueStr = duedate.getText().toString();
            String catStr = "";

            switch (category.getCheckedRadioButtonId()) {
            case R.id.action:
                catStr = "Action";
                break;
            case R.id.mystery:
                catStr = "Mystery";
                break;
            case R.id.thriller:
                catStr = "Thriller";
                break;
            case R.id.romance:
                catStr = "Romance";
                break;
            case R.id.horror:
                catStr = "Horror";
                break;
            case R.id.others:
                catStr = "Others";
                break;
            }

            if (bookId == null) {
                helper.insert(nameStr, authStr, dueStr, urlStr, catStr);
            } else {
                helper.update(bookId, nameStr, authStr, dueStr, urlStr, catStr);
            }
            finish();
        }
    };

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

    }



    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId()==R.id.gotourl){
            Intent i = new Intent(DetailForm.this,webactivity.class);
            i.putExtra("url",urlStr);
            startActivity(i);
        }
        return super.onOptionsItemSelected(item);
    }

}

网络活动

package sp.com;

import android.app.Activity;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.KeyEvent;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class webactivity extends Activity {
    private WebView webview;
    private String url = null;

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

        url = getIntent().getStringExtra("url");
        webview = (WebView) findViewById(R.id.webView1);
        webview.setWebViewClient(new myWebClient());
        webview.getSettings().setJavaScriptEnabled(true);
        webview.loadUrl("http://" + url);
    }

    public class myWebClient extends WebViewClient
    {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            // TODO Auto-generated method stub
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // TODO Auto-generated method stub

            view.loadUrl(url);
            return true;

        }
    }
    // To handle "Back" key press event for WebView to go back to previous screen.
   @Override
   public boolean onKeyDown(int keyCode, KeyEvent event)
  {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && webview.canGoBack()) {
        webview.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
   }
}

提前致谢, 史蒂夫

2 个答案:

答案 0 :(得分:1)

在类扩展活动

内的行下方声明String urlStrEditText url
public class YourActivity extends Activity {   
   String urlStr ;   //here
   EditText url;    

答案 1 :(得分:-1)

正如MysticMagic所说,让它成为全球性的。但我认为应该用一个例子来解释一下。在你的课堂上这样做:

     public class MainActivity extends Activity {

   //make it global here
  private String urlStr=null;

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

    private View.OnClickListener onSave = new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        //initialize the string here

          urlStr = url.getText().toString();
        }
    });
}

然后在你的onOptionsItemSelected中,在使用之前检查字符串是否有效:

       public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()==R.id.gotourl){
        //check if urlString is not null)
       if(urlStr!=null){
        Intent i = new Intent(DetailForm.this,webactivity.class);
        i.putExtra("url",urlStr);
        startActivity(i);
      }
    }
    return super.onOptionsItemSelected(item);
  }

在第二项活动中,获取如下值:

   //like above, make it global:
    String url =null;


       //and get the value from intent
       Bundle extras = getIntent().getExtras();
          if(extras !=null) {
         url = extras.getString("url");
        }