Android App卡在了加载屏幕中-Android Studio

时间:2018-07-15 05:07:23

标签: android android-studio

这是我在Android Studio中的应用遇到的特定问题。我正在制作一个天气应用程序,需要调用Yahoo weather API。我在用户等待应用程序连接到互联网时添加了一个加载屏幕,但该屏幕仅停留在该加载过程中。雅虎气象服务不再起作用了吗?

这是我的主要活动

public class MainActivity extends AppCompatActivity implements YahooServiceCallback {

private ImageView weatherIcon;
private TextView temperature;
private TextView condition;
private TextView location;

private YahooWeatherService service;
private ProgressDialog dialog;
private int resourceId;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    weatherIcon = findViewById(R.id.weatherIcon);
    temperature = findViewById(R.id.temperature);
    condition = findViewById(R.id.condition);
    location = findViewById(R.id.location);

    service = new YahooWeatherService(this);
    dialog = new ProgressDialog(this);
    dialog.setMessage("Loading...");
    dialog.show();

    service.refreshWeather("Manalapan, NJ", resourceId);

}

@Override
public void serviceSuccess(Channel channel, int resourceId) {
    dialog.hide();

    item item = channel.getItem();
    int resource = getResources().getIdentifier("drawable/icon_"+ item.getCondition().getCode(), null, getPackageName());

    @SuppressLint({"NewApi", "LocalSuppress"})
    Drawable weatherIconDrawable = getResources().getDrawable(resourceId, null);

    weatherIcon.setImageDrawable(weatherIconDrawable);

    temperature.setText(item.getCondition().getTemperature()+"\u00B0"+channel.getUnits().getTemperature());
    condition.setText(item.getCondition().getDescription());
    location.setText(service.getLocation());
}

@Override
public void serviceFailure(Exception exception) {
    Toast.makeText(this, exception.getMessage(), Toast.LENGTH_LONG).show();
}
}

和我的 YahooWeatherService.java

public class YahooWeatherService {
private YahooServiceCallback callback;
private String location;
private Exception error;

public YahooWeatherService(YahooServiceCallback callback) {
    this.callback = callback;
}

public String getLocation() {
    return location;
}

@SuppressLint("StaticFieldLeak")
public void refreshWeather(final String location, final int resourceId) {
    this.location = location;
    new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... strings) {

            String YQL = String.format("select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\"%s\")", strings[0]);

            String endpoint = String.format("https://query.yahooapis.com/v1/public/yql?q=%s&format=json", Uri.encode(YQL));

            try {
                URL url = new URL(endpoint);

                URLConnection connection = url.openConnection();
                InputStream inputStream = connection.getInputStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                return result.toString();

            } catch (Exception e) {
                error = e;
                return null;
            }
        }
    };
}
}

2 个答案:

答案 0 :(得分:0)

我发现了错误,这是您使用dialog.show()以来的逻辑错误。方法,但是当您从Yahoo weather api接收值时,需要调用dialog.dismiss();。取消进度对话框的方法,以便可以取消加载并向用户显示结果

答案 1 :(得分:0)

如我所见,您没有在AsyncTask上调用execute。您甚至还没有达到加载数据的目的。添加:

.yourAsyncTask.execute(location)

示例:

@SuppressLint("StaticFieldLeak")
public void refreshWeather(final String location) {
    this.location = location;
    new AsyncTask<String, Void, String>() {
        @Override
        protected String doInBackground(String... strings) {

            String YQL = String.format("select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\"%s\")", strings[0]);

            String endpoint = String.format("https://query.yahooapis.com/v1/public/yql?q=%s&format=json", Uri.encode(YQL));

            try {
                URL url = new URL(endpoint);

                URLConnection connection = url.openConnection();
                InputStream inputStream = connection.getInputStream();

                BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder result = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    result.append(line);
                }

                return result.toString();

            } catch (Exception e) {
                error = e;
                return null;
            }
        }

        @Override
        protected void onPostExecute(String s) {
            //param1 and param2 are the ones from the callback.
            callback.serviceSuccess(param1, param2);
        }
    }.execute(location);
}

它应该返回您想要的String数据。

修改
完整解决方案

public class MainActivity extends AppCompatActivity implements YahooWeatherCallback {

    private static final String TAG = MainActivity.class.getSimpleName();
    private TextView temperature;
    private TextView condition;
    private TextView location;

    private ProgressDialog dialog;

    private YahooWeatherService service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // weatherIcon = findViewById(R.id.weatherIcon);
        temperature = findViewById(R.id.tv_condition_show);
        condition = findViewById(R.id.tv_condition_show);
        location = findViewById(R.id.tv_location_show);

        service = new YahooWeatherService(this);
        dialog = new ProgressDialog(this);
        dialog.setMessage("Loading...");
        dialog.show();

        service.refreshWeather("Manalapan, NJ");

    }


    @Override
    public void serviceFailure(Exception exception) {

    }


    @Override
    public void serviceSuccess(Channel channel) {
        Log.d(TAG, "result:" + channel.getTitle());
        dialog.hide();
    }
}

//callback
 public interface YahooWeatherCallback {
    void serviceSuccess(Channel channel);

    void serviceFailure(Exception exception);
 }


 //service
  public class YahooWeatherService {


    private YahooWeatherCallback callback;
    private String location;
    private Exception error;

     public String getLocation() {
        return location;
     }

     public YahooWeatherService(YahooWeatherCallback callback) {
        this.callback = callback;
     }

     @SuppressLint("StaticFieldLeak")
     public void refreshWeather(final String location) {
         this.location = location;
         new AsyncTask<String, Void, String>() {
             @Override
             protected String doInBackground(String... strings) {

                 String YQL = String.format("select * from weather.forecast where woeid in (select woeid from geo.places(1) where text=\"%s\")", strings[0]);

                 String endpoint = String.format("https://query.yahooapis.com/v1/public/yql?q=%s&format=json", Uri.encode(YQL));

                 try {
                     URL url = new URL(endpoint);

                     URLConnection connection = url.openConnection();
                     InputStream inputStream = connection.getInputStream();

                      BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
                      StringBuilder result = new StringBuilder();
                      String line;
                      while ((line = reader.readLine()) != null) {
                         result.append(line);
                      }

                      return result.toString();

                  } catch (Exception e) {
                      error = e;
                      return null;
                  }
              }

              @Override
              protected void onPostExecute(String s) {
                  callback.serviceSuccess(new Channel());
              }
          }.execute(location);
      }
  }

    //Channel
    public class Channel {
       //here you can add more data.
    }

如您所见,我剥离了一些数据只是为了让您起步。