我正在创建一个小部件,该小部件应该从提供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");
}
}
获得服务的class 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();
}
});
}
}
我没有收到任何错误,但小部件只显示带有默认文本的textViews。 任何人都可以发现这种情况正在发生吗?
答案 0 :(得分:0)
您只需要在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();
}
}
}
答案 1 :(得分: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