2013-01-25 8 views
1

지금 Android 개발을 배우고 있으며 iOS 개발에서 수행 한 기본 프로그램을 시험해보고 싶었습니다. 문제는 장소의 날씨 상태를 파악하고 TextView에서 조건을 설정하는 것입니다.Android 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> 

코드에서 볼 수 있습니다, 구문 분석 후 값을 "지우기"(USES 인터넷 사용 권한 집합) 얻을. 그러나 어떤 이유로 텍스트 뷰에 설정되지 않습니다. 나는 여기서 무슨 실수를했는지 모른다. Logcat은 로그 된 값을 올바르게 보여줍니다. 도와주세요.

건배.

+0

시도 setTextView()'를 호출하고 기존 인스턴스를 처리하지 않습니다. –

+0

오, 그렇다면 어떻게 MainActivity의 기존 인스턴스에서 텍스트를 설정해야합니까? – thandasoru

답변

1

당신은 MainActivity의 ** 새로운 ** 인스턴스를 생성하고`의를 호출

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); 
     } 
    } 
} 
+0

그것은 일했습니다 .. 도움 주셔서 감사합니다 :-) – thandasoru

2

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.... 

및 MainActivity에서 같이 활동 컨텍스트를 전달합니다

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"); 
+0

그것은 일했다 .. 도움을 주셔서 감사합니다 :-) – thandasoru

관련 문제