无法将数据传递给android中的detailActivity

时间:2018-03-22 21:28:39

标签: android json android-intent weather-api

我正在使用天气地下api构建天气应用程序。我有listView预测10天,我想创建详细活动,以便按下每个列表项后每天更详细的预测。而且我不知道如何将数据传递给详细活动。我使用listView与适配器,我有列表上的图像网址与maxtemp和最小临时和详细活动我希望相同的图像网址更详细我同样的ID为两个图像视图(详细和列表视图)但它只工作正常在列表上。我是否只在详细活动中实例化我的视图并使用id将其附加到适配器?我尝试了一些额外的意图,但它不适用于数据 来自web api。

我确实喜欢你说但是在我的适配器中我只夸大了列表项目视图,当我尝试启动应用程序时我得到这样的错误:

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference

我的适配器类看起来像这样:

public class WeatherAdapter extends ArrayAdapter<Weather> {


    public WeatherAdapter(Context context, ArrayList<Weather> weather) {
        super(context, 0, weather);

    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View listItemView = convertView;
        if (listItemView == null) {
            listItemView = LayoutInflater.from(getContext()).inflate(
                    R.layout.list_item, parent, false);
        }

        Weather currentWeather = getItem(position);

        TextView date = (TextView) listItemView.findViewById(R.id.month);
        date.setText(currentWeather.getDate());

        TextView minTemp = (TextView) listItemView.findViewById(R.id.low_temperature);
        minTemp.setText(String.valueOf(currentWeather.getMinTemp()) + " \u2103");

        TextView maxTemp = (TextView) listItemView.findViewById(R.id.high_temperature);
        maxTemp.setText(String.valueOf(currentWeather.getMaxTemp()) + " \u2103");

        ImageView image = (ImageView) listItemView.findViewById(R.id.weather_icon);
        Picasso.with(getContext()).load(currentWeather.getUrl()).into(image);

        TextView day = (TextView) listItemView.findViewById(R.id.day);
        day.setText(String.valueOf(currentWeather.getDay()));

        TextView weekday = (TextView) listItemView.findViewById(R.id.weekday);
        weekday.setText(String.valueOf(currentWeather.getWeekday()));

        TextView conditions = (TextView) listItemView.findViewById(R.id.conditions);
        conditions.setText(currentWeather.getConditions());

        TextView humidity = (TextView) listItemView.findViewById(R.id.humidity);
        humidity.setText(String.valueOf(currentWeather.getHumidity()));

        return listItemView;
    }

}

并且我的适配器无法识别activity_detail.xml,其中放置了我的湿度textView,并且我不知道如何在我的适配器中对此布局进行充气

这是我的工具类

public class WeatherUtils {


    private static final String LOG_TAG = WeatherUtils.class.getSimpleName();


    public WeatherUtils() {

    }

    public static List<Weather> fetchNewsData(String requestUrl) throws JSONException {
        URL url = createUrl(requestUrl);
        String jsonResponse = null;
        try {
            jsonResponse = makeHttpsRequest(url);
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem making the HTTP request.", e);
        }
        List<Weather> weather = extractFromJSONResponse(jsonResponse);

        return weather;
    }

    private static URL createUrl(String stringUrl) {

        URL url = null;
        try {
            url = new URL(stringUrl);
        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "Error with creating URL", e);
        }

        return url;
    }

    private static String makeHttpsRequest(URL url) throws IOException {
        String jsonResponse = "";
        if (url == null) {

            return jsonResponse;
        }

        HttpURLConnection urlConnection = null;
        InputStream inputStream = null;
        try {
            urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.setReadTimeout(10000 /*milliseconds*/);
            urlConnection.setConnectTimeout(15000 /*milliseconds*/);
            urlConnection.setRequestMethod("GET");
            urlConnection.connect();

            if (urlConnection.getResponseCode() == 200) {
                inputStream = urlConnection.getInputStream();
                jsonResponse = readFromStream(inputStream);

            } else {
                Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
            }
        } catch (IOException e) {
            Log.e(LOG_TAG, "Problem retrieving Book JSON results.", e);

        } finally {
            if (urlConnection != null) {
                urlConnection.disconnect();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }

        return jsonResponse;
    }

    private static String readFromStream(InputStream inputStream) throws IOException {

        StringBuilder output = new StringBuilder();
        if (inputStream != null) {
            InputStreamReader inputStreamReader;
            inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
            BufferedReader reader = new BufferedReader(inputStreamReader);
            String line = reader.readLine();
            while (line != null) {
                output.append(line);
                line = reader.readLine();
            }
        }

        return output.toString();
    }

    private static List<Weather> extractFromJSONResponse(String JSONResponse) throws JSONException {
        if (TextUtils.isEmpty(JSONResponse)) {
            return null;
        }

        List<Weather> weather = new ArrayList<>();


        try {

            JSONObject jsonResponse = new JSONObject(JSONResponse);
            JSONObject forecast = jsonResponse.getJSONObject("forecast");
            JSONObject simpleForecast = forecast.getJSONObject("simpleforecast");
            JSONArray listArray = simpleForecast.getJSONArray("forecastday");
            for (int i = 0; i < listArray.length(); i++) {

                JSONObject currentWeather = listArray.getJSONObject(i);

                String iconUrl = currentWeather.getString("icon_url");

                double humidity = currentWeather.getDouble("avehumidity");

                JSONObject highTempObject = currentWeather.getJSONObject("high");
                String maxTemp = highTempObject.getString("celsius");

                JSONObject lowTempObject = currentWeather.getJSONObject("low");
                String minTemp = lowTempObject.getString("celsius");


                JSONObject dateObject = currentWeather.getJSONObject("date");
                String date = dateObject.getString("monthname");
                String weekday = dateObject.getString("weekday");
                int day = dateObject.getInt("day");
                int year = dateObject.getInt("year");


                Weather data = new Weather(maxTemp, minTemp, humidity, date, iconUrl, year, day, weekday);
                weather.add(data);

            }


        } catch(JSONException e){
            Log.e("QueryUtils", "Problem parsing the earthquake JSON results", e);
        }

        return weather;

    }
}

这是我的天气课程

public class Weather {

    private String maxTemp;
    private String minTemp;
    private double humidity;
    private String date;
    private int year;
    private int day;
    private String weekday;
    private String url;


    public Weather(String maxTemp, String minTemp, double humidity, String date, String url, int year, int day, String weekday) {
        this.maxTemp = maxTemp;
        this.minTemp = minTemp;
        this.humidity = humidity;
        this.date = date;
        this.day = day;
        this.year = year;
        this.weekday = weekday;
        this.url = url;
    }

    public String getMaxTemp() {
        return maxTemp;
    }

    public String getMinTemp() {
        return minTemp;
    }

    public double getHumidity() {
        return humidity;
    }

    public int getYear() {
        return year;
    }

    public int getDay() {
        return day;
    }

    public String getDate() {
        return date;
    }

    public String getUrl() {
        return url;
    }

    public String getWeekday() {
        return weekday;
    }
}

1 个答案:

答案 0 :(得分:0)

您可以通过意图传递详细信息数据。但是你需要使Weather实现Serializable或实现Parcelable。简单的方法是将天气序列化为:

public class Weather implements Serializable {
  ...
}

然后你可以像往常一样传递对象:

Intent intent = new Intent(ActivityCaller.this, DetailActivity.class);
intent.putExtra("weatherkey", weather);
startActivity(intent);

了解详情,请阅读Start Another Activity

要使用以下自定义适配器处理项目:

public class WeathersAdapter extends ArrayAdapter<Weather> {
    private static class ViewHolder {
        TextView tvMaxTemp;
        TextView tvMinTemp;
        // ...
    }

    public Weathers(Context context, ArrayList<Weather> weathers) {
       super(context, R.layout.item_weather, weathers);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
       Weather weather = getItem(position);    

       ViewHolder viewHolder;
       if (convertView == null) {
          viewHolder = new ViewHolder();
          LayoutInflater inflater = LayoutInflater.from(getContext());
          convertView = inflater.inflate(R.layout.item_weather, parent, false);
          viewHolder.name = (TextView) convertView.findViewById(R.id.tvMaxTemp);
          viewHolder.home = (TextView) convertView.findViewById(R.id.tvMinTemp);
          convertView.setTag(viewHolder);
       } else {
           viewHolder = (ViewHolder) convertView.getTag();
       }

       viewHolder.tvMaxTemp.setText(weather.getMaxTemp());
       viewHolder.tvMinTemp.setText(user.getMinTemp());
       // ...
       return convertView;
   }
}

您可以使用:

// assume that your Weather is inside a list
List<Weather> weathers = getWeathers();

listView.setOnItemClickListener(new OnItemClickListener() {
   @Override
   public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
     // ActivityCaller is the activity where your ListView reside.
     Intent intent = new Intent(ActivityCaller.this, DetailActivity.class);
     intent.putExtra("weatherkey", weathers.get(position));
     startActivity(intent);
   }
});