2015-02-17 5 views
0

Я создаю виджет, который должен получать информацию о погоде с веб-сайта, который предоставляет услугу JSON и показывает ее. Вот кодВиджет не показывает результат JSON

Widget:

public class MainActivity extends AppWidgetProvider { 



public static void onUpdate(Context context, AppWidgetManager appWidgetManager,int appWidgetIds) { 
    String resultadoObtido = ""; 

    SharedPreferences c = PreferenceManager.getDefaultSharedPreferences(context); 
    String cidade = c.getString("cidade", "Coimbra"); 

    try { 
     Dados d = new Dados(cidade); 
     resultadoObtido = d.execute().get(); 

    }catch (InterruptedException e){ 
     e.printStackTrace();      
    }    
    catch (ExecutionException e) { 
     // TODO: handle exception 
     e.printStackTrace(); 
    } 
    String string = resultadoObtido; 

    String[] parts = string.split("/"); 
    String part1 = parts[0]; 
    String part2 = parts[1]; 
    String part3 = parts[2]; 
    String part4 = parts[3]; 
    String part5 = parts[4]; 

    float atual =Float.parseFloat(part1); 
    float minima =Float.parseFloat(part2); 
    float maxima = Float.parseFloat(part3); 

    float atualC = (float) (atual-273.15); 
    float minimaC = (float) (minima-273.15); 
    float maximaC = (float) (maxima-273.15); 

    String result1 =String.format("%.1f", atualC); 
    String result2 =String.format("%.1f", minimaC); 
    String result3 =String.format("%.1f", maximaC); 

    RemoteViews view =new RemoteViews(context.getPackageName(),R.layout.activity_main); 

    view.setTextViewText(R.id.cidade,""+part4); 
    view.setTextViewText(R.id.temp,""+result1+"ºC"); 
    view.setTextViewText(R.id.temp_max,""+result2+"ºC"); 
    view.setTextViewText(R.id.temp_min,""+result3+"ºC"); 




} 

}

класса Dados, который получает услугу: общественного класса Dados расширяет AsyncTask {

String Resultado = ""; 
public String s,city; 
public Dados(String cidade){ 
    city=cidade;   
} 

@Override 
protected String doInBackground(String... params) { 
    // TODO Auto-generated method stub 
    try { 
     s = getJson("http://api.openweathermap.org/data/2.5/weather?q="+city+",pt"); 
     JSONObject jobj = new JSONObject(s); 
     JSONObject detalhe= jobj.getJSONObject("main"); 
     JSONArray weather = jobj.getJSONArray("weather"); 
     Resultado = detalhe.getString("temp")+"/"+detalhe.getString("temp_min")+"/" 
     +detalhe.getString("temp_max")+"/"+jobj.getString("name") 
     +"/"+weather.getJSONObject(0).getString("main"); 
    } catch (Exception e) { 
     // TODO: handle exception 
     e.printStackTrace(); 
    } 


    return Resultado; 
} 

public String getJson (String url) throws ClientProtocolException, IOException{ 

    StringBuilder build = new StringBuilder(); 
    HttpClient client = new DefaultHttpClient(); 
    HttpGet httpGet = new HttpGet(url); 
    HttpResponse response = client.execute(httpGet); 
    HttpEntity entity = response.getEntity(); 
    InputStream content = entity.getContent(); 
    BufferedReader reader = new BufferedReader(new InputStreamReader(content)); 
    String con; 
    while ((con=reader.readLine())!= null){ 
     build.append(con); 
    } 
    return build.toString(); 

} 

}

Config:

public class Config extends Activity{ 

private int myWidgetId; 
Context context; 

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setResult(RESULT_CANCELED); 
    setContentView(R.layout.config); 

    final EditText cidade = (EditText) findViewById(R.id.editText1); 
    context=Config.this; 
    Intent intent = getIntent(); 
    Bundle extras = intent.getExtras(); 
    if (extras!=null) { 
     myWidgetId = extras.getInt(AppWidgetManager.EXTRA_APPWIDGET_ID, 
       AppWidgetManager.INVALID_APPWIDGET_ID); 
    } 
    if(myWidgetId == AppWidgetManager.INVALID_APPWIDGET_ID){ 
     finish(); 
    } 
    Button bt1 = (Button) findViewById(R.id.button1); 
    bt1.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      String city = cidade.getText().toString(); 
      SharedPreferences.Editor editor = getPreferences(MODE_PRIVATE).edit(); 
      editor.putString("Cidade", city); 
      editor.commit(); 

      AppWidgetManager appWMan= AppWidgetManager.getInstance(context); 
      MainActivity.onUpdate(context, appWMan,myWidgetId); 
      Intent resultvalue = getIntent(); 
      resultvalue.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID,myWidgetId); 
      setResult(RESULT_OK,resultvalue); 
      finish(); 


     } 
    }); 

} 

}

Я не получаю никаких ошибок, но виджет показывает только TextViews с текстом по умолчанию. Может ли кто-нибудь понять, что это происходит?

ответ

0

Вам просто нужно добавить метод onPostExecute в asynctask для установки данных в TextView и записать класс asynctask внутри класса MainActivity.

Так ваш класс MainActivity будет выглядеть следующим образом

public class MainActivity extends AppWidgetProvider { 
     Context context; 


     public static void onUpdate(Context context, AppWidgetManager appWidgetManager,int appWidgetIds) { 
     this.context=context; 

     SharedPreferences c = PreferenceManager.getDefaultSharedPreferences(context); 
     String cidade = c.getString("cidade", "Coimbra"); 

     try { 
      new Dados(cidade).execute(); 
     } catch (InterruptedException e){ 
      e.printStackTrace();      
     } catch (ExecutionException e) {   
      e.printStackTrace(); 
     } 
     } 

     public class Dados extends AsyncTask<Void,Void,String>{ 
     public String s,city; 
     public Dados(String cidade){ 
      city=cidade;   
     } 

     @Override 
     protected String doInBackground(Void... params) {   
      String Resultado = ""; 

      try { 
       s = getJson("http://api.openweathermap.org/data/2.5/weather?q="+city+",pt"); 
       JSONObject jobj = new JSONObject(s); 
       JSONObject detalhe= jobj.getJSONObject("main"); 
       JSONArray weather = jobj.getJSONArray("weather"); 
       Resultado = detalhe.getString("temp")+"/"+detalhe.getString("temp_min")+"/" 
      +detalhe.getString("temp_max")+"/"+jobj.getString("name") 
      +"/"+weather.getJSONObject(0).getString("main"); 
      } catch (Exception e) { 
       e.printStackTrace(); 
      } 

      return Resultado; 
    } 

    @Override 
    protected void onPostExecute(String result) { 
     super.onPostExecute(result);   

     if(result!=null && !result.trim().isEmpty()){ 

      String[] parts = result.split("/"); 
      String part1 = parts[0]; 
      String part2 = parts[1]; 
      String part3 = parts[2]; 
      String part4 = parts[3]; 
      String part5 = parts[4]; 

      float atual =Float.parseFloat(part1); 
      float minima =Float.parseFloat(part2); 
      float maxima = Float.parseFloat(part3); 

      float atualC = (float) (atual-273.15); 
      float minimaC = (float) (minima-273.15); 
      float maximaC = (float) (maxima-273.15); 

      String result1 =String.format("%.1f", atualC); 
      String result2 =String.format("%.1f", minimaC); 
      String result3 =String.format("%.1f", maximaC); 

      RemoteViews view =new RemoteViews(context.getPackageName(),R.layout.activity_main); 

      view.setTextViewText(R.id.cidade,""+part4); 
      view.setTextViewText(R.id.temp,""+result1+"ºC"); 
      view.setTextViewText(R.id.temp_max,""+result2+"ºC"); 
      view.setTextViewText(R.id.temp_min,""+result3+"ºC"); 
     } 
    } 

    public String getJson (String url) throws ClientProtocolException, IOException{ 

     StringBuilder build = new StringBuilder(); 
     HttpClient client = new DefaultHttpClient(); 
     HttpGet httpGet = new HttpGet(url); 
     HttpResponse response = client.execute(httpGet); 
     HttpEntity entity = response.getEntity(); 
     InputStream content = entity.getContent(); 
     BufferedReader reader = new BufferedReader(new InputStreamReader(content)); 
     String con; 
     while ((con=reader.readLine())!= null){ 
      build.append(con); 
     } 
     return build.toString(); 

    } 
} 

}

+0

asynktask не в основной деятельности ... так что я не могу сделать это onpostexecute .... – Rasmnev

+0

Это что я сказал вам. напишите свою задачу async внутри класса MainActivity. –

0

мне удалось решить эту проблему, переместив эту часть кода

try { 
    Dados d = new Dados(cidade); 
    resultadoObtido = d.execute().get(); 

}catch (InterruptedException e){ 
    e.printStackTrace();      
}    
catch (ExecutionException e) { 
    // TODO: handle exception 
    e.printStackTrace(); 
} 
String string = resultadoObtido; 

String[] parts = string.split("/"); 
String part1 = parts[0]; 
String part2 = parts[1]; 
String part3 = parts[2]; 
String part4 = parts[3]; 
String part5 = parts[4]; 

float atual =Float.parseFloat(part1); 
float minima =Float.parseFloat(part2); 
float maxima = Float.parseFloat(part3); 

float atualC = (float) (atual-273.15); 
float minimaC = (float) (minima-273.15); 
float maximaC = (float) (maxima-273.15); 

String result1 =String.format("%.1f", atualC); 
String result2 =String.format("%.1f", minimaC); 
String result3 =String.format("%.1f", maximaC); 

к классу, который проходит службу а затем вызов службы в виджет.

теперь у меня другая проблема, если кто-нибудь может помочь вопрос здесь: https://stackoverflow.com/questions/28563880/weather-widget-not-changing-icon

Смежные вопросы