【问题标题】:EditText value in a Service服务中的 EditText 值
【发布时间】:2014-08-05 08:40:20
【问题描述】:

我正在构建一个应用程序,在该应用程序中我使用服务来创建后台进程。但我有一个问题。 我在用户输入 URL 的地方使用 EditText,然后我将在服务中使用该 url 每 X 分钟检查一次与网站的连接。但是如果用户关闭应用程序,后台进程会因为EditText的值变成Null而崩溃,并且logcat给我空指针异常。我将值从活动传递给服务,其意图如下 MainActivity 代码:

public void onClickReadWebPage(View v)
    {


        if(address.getText().toString().trim().length() == 0)
        {
            Toast.makeText(getApplicationContext(), "URL String empty.", Toast.LENGTH_LONG).show();
        }
        else
        {
            time = String.valueOf(address.getText());
            i=new Intent(MainActivity.this,MyService.class);
            p=PendingIntent.getService(MainActivity.this, 0, i, 0);
            i.putExtra("Address", time);                
            //start the service from here //MyService is your service class name
            startService(i);
        }

这是服务代码:

    @Override
    public void onStart(Intent intent, int startId) 
    {   
        Address = intent.getStringExtra("Address");
        DownloadWebPageTask task = new DownloadWebPageTask();
        task.execute(Address);

        if(report == "false")
        {
            //do my stuff
        }
        else
        {
            //do my stuff
        }
    }

有什么建议吗?

【问题讨论】:

  • 不是你的问题(目前)-但看起来确实不对:if(report == "false")

标签: java android android-intent service


【解决方案1】:

只需将ediText 的值保存在SharedPreferences 中,然后在您的service 中检索它们

【讨论】:

  • 谢谢,SharedPreferences 可能是存储 URL 的正确方法。
  • 我知道,但我想先尝试一下。那我就做吧。
  • :) ...这很好,问候
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-09-26
  • 2012-05-11
  • 1970-01-01
  • 1970-01-01
  • 2014-02-01
  • 1970-01-01
相关资源
最近更新 更多