Android文本视图未设置

Android文本视图未设置,android,android-asynctask,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; i

我现在正在学习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);
        }
    }
}
活动\u 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
传递活动上下文,而不是在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....
试一试

class WeatherTask扩展了AsyncTask{
主要活动能力;
公共天气任务(主要活动){
这个.mActivity=mActivity;
}
受保护的void onPostExecute(字符串json){
试一试{
JSONObject JSONObject=新的JSONObject(json);
字符串值=jsonObject.getJSONObject(“数据”)
.getJSONArray(“当前条件”).getJSONObject(0)
.getJSONArray(“weatherDesc”).getJSONObject(0)
.getString(“值”);
Log.d(“bh”,值);
mActivity.setTextView(值);
}捕获(例外e){
e、 printStackTrace();
}
}
@凌驾
受保护的字符串doInBackground(字符串…urlTojson){
String json=新字符串();
试一试{
DefaultHttpClient defaultClient=新的DefaultHttpClient();
HttpGet httpGetRequest=新的HttpGet(urlTojson[0]);
HttpResponse HttpResponse=defaultClient.execute(httpGetRequest);
BufferedReader=新的BufferedReader(新的InputStreamReader(httpResponse.getEntity().getContent(),“UTF-8”);
json=reader.readLine();
}捕获(例外e){
e、 printStackTrace();
}
返回json;
}
}
公共类MainActivity扩展活动实现OnClickListener{
私有文本视图tv=null;
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
按钮按钮=(按钮)findViewById(R.id.button1);
setOnClickListener(此);
}
@凌驾
公共布尔onCreateOptions菜单(菜单){
getMenuInflater().充气(R.menu.activity\u主菜单);
返回true;
}
@凌驾
公共void onClick(视图v){
//将此处的API密钥更改为XXXXXXXXXXXXXX
新建WeatherTask(此)。执行(“http://free.worldweatheronline.com/feed/weather.ashx?q=Bangalore,印度&format=json&num_of_days=1&key=XXXXXXXXXXXXXXXXXX”);
}
公共void setTextView(字符串v){
Log.d(“bh”,“内部setTextView:+v”);
如果(v等于(“”){
日志d(“bh”,“未收到的价值”);
}
否则{
tv=(TextView)findViewById(R.id.textView3);
tv.setText(v);
}
}
}

您正在创建MainActivity的新实例并调用其
setTextView()
,而不是处理现有实例。哦,那么如何让MainActivity的现有实例设置文本呢?
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....
    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");
 class WeatherTask extends AsyncTask<String, Void, String> {
    MainActivity mActivity;
     public WeatherTask(MainActivity mActivity){

          this.mActivity=mActivity;
                  }

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);

        mActivity.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(this).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);
        }
    }
}