Android TextView 未设置

标签 android android-asynctask textview

我现在正在学习Android开发,我想尝试一下我在iOS开发中做过的任何基本程序。问题是获取某个地方的天气状况并在 TextView 中设置该条件。

代码

package com.bh.weather;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

class WeatherTask extends AsyncTask<String, Void, String> {

    protected void onPostExecute(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            String value = jsonObject.getJSONObject("data")
                    .getJSONArray("current_condition").getJSONObject(0)
                    .getJSONArray("weatherDesc").getJSONObject(0)
                    .getString("value");
            Log.d("bh", value);
            MainActivity m = new MainActivity();
            m.setTextView(value);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected String doInBackground(String... urlTojson) {
        String json = new String();
        try {
            DefaultHttpClient defaultClient = new DefaultHttpClient();
            HttpGet httpGetRequest = new HttpGet(urlTojson[0]);
            HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
            json = reader.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }
}

public class MainActivity extends Activity implements OnClickListener {

    private TextView tv = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = (Button) findViewById(R.id.button1);
        button.setOnClickListener(this);

    }

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

    @Override
    public void onClick(View v) {
    //changed the API key here to xxxxxxxxxxxxxxxx
        new WeatherTask().execute("http://free.worldweatheronline.com/feed/weather.ashx?q=Bangalore,India&format=json&num_of_days=1&key=xxxxxxxxxxxxxxxxx");
    }

    public void setTextView(String v) {
        Log.d("bh","Inside setTextView:"+v);
        if(v.equals("")) {
            Log.d("bh","Value not received");
        }
        else {
            tv = (TextView) findViewById(R.id.textView3);
            tv.setText(v);
        }
    }
}

生成的 JSON 如下所示(可以使用 jsonviewer.stack.hu 查看):

{
  "data": {
    "current_condition": [
      {
        "cloudcover": "0",
        "humidity": "30",
        "observation_time": "01:29 PM",
        "precipMM": "0.0",
        "pressure": "1017",
        "temp_C": "25",
        "temp_F": "77",
        "visibility": "10",
        "weatherCode": "113",
        "weatherDesc": [
          {
            "value": "Clear"
          }
        ],
        "weatherIconUrl": [
          {
            "value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0008_clear_sky_night.png"
          }
        ],
        "winddir16Point": "E",
        "winddirDegree": "90",
        "windspeedKmph": "13",
        "windspeedMiles": "8"
      }
    ],
    "request": [
      {
        "query": "Bangalore, India",
        "type": "City"
      }
    ],
    "weather": [
      {
        "date": "2013-01-25",
        "precipMM": "0.0",
        "tempMaxC": "29",
        "tempMaxF": "84",
        "tempMinC": "15",
        "tempMinF": "59",
        "weatherCode": "113",
        "weatherDesc": [
          {
            "value": "Sunny"
          }
        ],
        "weatherIconUrl": [
          {
            "value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png"
          }
        ],
        "winddir16Point": "E",
        "winddirDegree": "97",
        "winddirection": "E",
        "windspeedKmph": "17",
        "windspeedMiles": "11"
      }
    ]
  }
}

activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="22dp"
        android:text="@string/title" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@+id/textView1"
        android:layout_marginLeft="32dp"
        android:layout_marginTop="30dp"
        android:text="@string/place_name"
        android:textAppearance="?android:attr/textAppearanceLarge" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textView2"
        android:layout_below="@+id/textView2"
        android:layout_marginTop="36dp"
        android:layout_marginLeft="0dp"
        android:text="@string/weather_condition" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_centerVertical="true"
        android:layout_marginTop="140dp"
        android:layout_marginLeft="120dp"
        android:text="@string/show_weather" />

</RelativeLayout>

从代码中可以看到,解析后我得到了值“Clear”(使用 Internet 权限集)。但由于某种原因,这没有在 TextView 中设置。我不知道我在这里犯了什么错误。 Logcat 正确显示记录的值。请帮忙。

干杯。

最佳答案

您将需要使用构造函数 AsyncTask 来传递 Activity 上下文,而不是在 AsyncTask 中创建它。将您的代码更改为:

class WeatherTask extends AsyncTask<String, Void, String> {
public Context context;
  public WeatherTask(Context context){

     this.context=context;
  }
    protected void onPostExecute(String json) {
        try {
            JSONObject jsonObject = new JSONObject(json);
            String value = jsonObject.getJSONObject("data")
                    .getJSONArray("current_condition").getJSONObject(0)
                    .getJSONArray("weatherDesc").getJSONObject(0)
                    .getString("value");
            Log.d("bh", value);

            context.setTextView(value); 

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 //your code here....

并从 MainActivity 传递 Activity 上下文:

    WeatherTask weatherobj=new WeatherTask(MainActivity.this);
        weatherobj.execute("http://free.worldweatheronline.com/feed/
weather.ashx?q=Bangalore,India&format=json&num_of_days=1&key=xxxxxxxxxxxxxxxxx");

关于Android TextView 未设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14522896/

相关文章:

android - 在 Android 模拟器上运行自定义 ROM

java - 如何在一个类中执行多个AsyncTask

java - 如何链接 TextView 中的文本以打开网址

java - android 上的动画 Logo /文本通常是用什么创建的?

android - 使用 InputType.TYPE_CLASS_PHONE 进行数字输入的注意事项

java - SQlite 数据库文件未加载

Android asynctask自定义适配器在错误位置加载图像

java - 我需要以 2 分钟的间隔执行 AsynckTask 对象 5 次

ios - 使 GridLayout 中的 NativeScript ScrollView 和 TextView 一起工作(仅限 iOS)

ios - 键盘打开时如何滚动屏幕?