【问题标题】:Widget not showing JSON result小部件未显示 JSON 结果
【发布时间】:2020-01-26 22:18:11
【问题描述】:

我正在创建一个小部件,它应该从提供 JSON 服务的网站获取天气信息并显示它。这是代码

小部件:

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

}

}

配置:

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


        }
    });

}

}

我没有收到任何错误,但小部件仅显示带有默认文本的 textView。 谁能弄清楚这正在发生?

【问题讨论】:

    标签: android json android-widget


    【解决方案1】:

    您只需在 asynctask 中添加 onPostExecute 方法即可将数据设置为 TextView 并在 MainActivity 类中编写您的 asynctask 类。

    所以你的 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();
    
        }
    }
    

    }

    【讨论】:

    • 这就是我告诉你的。在 MainActivity 类中编写你的异步任务。
    【解决方案2】:

    我设法通过移动这部分代码来解决问题

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

    到扩展服务的类,然后在小部件上调用服务。

    【讨论】:

      猜你喜欢
      • 2016-04-08
      • 2019-09-16
      • 2013-12-22
      • 1970-01-01
      • 1970-01-01
      • 2013-03-31
      • 2013-10-22
      • 2011-01-01
      • 1970-01-01
      相关资源
      最近更新 更多