【问题标题】:android studio how to fill textviews with dataandroid studio如何用数据填充textviews
【发布时间】:2023-04-09 06:40:01
【问题描述】:

我很绝望,我不知道如何解决我的问题。当我按下刷新按钮时,我想更改我的 textview 元素上的文本。我正在解析 json 文件(连接和值都可以),我希望 textview 值相应地更改为我的 json。

片段.java:

public class Fragment extends Fragment {

    String v1, v2, v3, v4, v5, v6, v7, v8, v9, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24, v25, v26, v27, v28, v29, v30, v31, v32, v33, v34, v35, v36;

    final String LOG_TAG = Fragment.class.getSimpleName();

    public Fragment() {
    }
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.fragment, menu);
    }
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_fresh) {
            FetchWeatherTask weatherTask = new FetchWeatherTask();
            weatherTask.execute("94043");
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment, container, false);

        TextView t = (TextView)v.findViewById(R.id.reiksme1);
        t.setText(v3);



        Log.e(LOG_TAG, "reiksme ONCREATEVIEW:" + v3);
        return v;
    }
    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

    public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
        public String[] resultStrs = new String[23];
        private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();

        private String[] getWeatherDataFromJson(String forecastJsonStr, int numDays)
                throws JSONException {

            // These are the names of the JSON objects that need to be extracted.
            final String OWM_LIST = "list";
            final String OWM_WEATHER = "weather";

            final String OWM_timestamp = "timestamp";
            final String OWM_zeno_BP1_5s_Mb = "zeno_BP1_5s_Mb";
            final String OWM_zeno_Spd_5s_Kt = "zeno_Spd_5s_Kt";
            final String OWM_zeno_PP_30s_Mm = "zeno_PP_30s_Mm";
            final String OWM_zeno_PP_24h_Mm = "zeno_PP_24h_Mm";
            final String OWM_zeno_AT_5s_C = "zeno_AT_5s_C";
            final String OWM_zeno_BIT = "zeno_BIT";
            final String OWM_zeno_gust = "zeno_gust";
            final String OWM_zeno_RH_5s = "zeno_RH_5s";
            final String OWM_zeno_V_DC = "zeno_V_DC";
            final String OWM_zeno_BP2_5s_Mb = "zeno_BP2_5s_Mb";
            final String OWM_zeno_Dir_5s = "zeno_Dir_5s";
            final String OWM_zeno_WSonicBIT = "zeno_WSonicBIT";
            final String OWM_zeno_ID = "zeno_ID";
            final String OWM_cl31_high_sig = "cl31_high_sig";
            final String OWM_cl31_ClH2_30s_Ft = "cl31_ClH2_30s_Ft";
            final String OWM_cl31_ClH1_30s_Ft = "cl31_ClH1_30s_Ft";
            final String OWM_cl31_Range_Ft = "cl31_Range_Ft";
            final String OWM_cl31_Detect = "cl31_Detect";
            final String OWM_cl31_raw = "cl31_raw";
            final String OWM_cl31_ClH3_30s_Ft = "cl31_ClH3_30s_Ft";
            final String OWM_sws200_PP_Mm = "sws200_PP_Mm";
            final String OWM_sws200_synop_code = "sws200_synop_code";
            final String OWM_sws200_Vis_1m_KM = "sws200_Vis_1m_KM";


            JSONObject forecastJson = new JSONObject(forecastJsonStr);
            JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);


                // Get the JSON object representing the day
                JSONObject dayForecast = weatherArray.getJSONObject(0);

                // description is in a child array called "weather", which is 1 element long.

                JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v1 = weatherObject.getString(OWM_timestamp);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v2 = weatherObject.getString(OWM_zeno_BP1_5s_Mb);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v3 = weatherObject.getString (OWM_zeno_Spd_5s_Kt);
            Log.e(LOG_TAG, "reiksme inicializacija:" + v3);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v4 = weatherObject.getString(OWM_zeno_PP_30s_Mm);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v5 = weatherObject.getString (OWM_zeno_PP_24h_Mm);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v6 = weatherObject.getString(OWM_zeno_AT_5s_C);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v7 = weatherObject.getString (OWM_zeno_BIT);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v8 = weatherObject.getString(OWM_zeno_gust);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v9 = weatherObject.getString (OWM_zeno_RH_5s);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v10 = weatherObject.getString(OWM_zeno_V_DC);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v11 = weatherObject.getString (OWM_zeno_BP2_5s_Mb);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v12 = weatherObject.getString(OWM_zeno_Dir_5s);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v13 = weatherObject.getString (OWM_zeno_WSonicBIT);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v14 = weatherObject.getString(OWM_zeno_ID);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v21 = weatherObject.getString(OWM_cl31_high_sig);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v24 = weatherObject.getString (OWM_cl31_ClH2_30s_Ft);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v25 = weatherObject.getString(OWM_cl31_ClH1_30s_Ft);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v26 = weatherObject.getString (OWM_cl31_Range_Ft);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v27 = weatherObject.getString(OWM_cl31_Detect);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v29 = weatherObject.getString(OWM_cl31_ClH3_30s_Ft);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v31 = weatherObject.getString (OWM_sws200_PP_Mm);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v33 = weatherObject.getString (OWM_sws200_synop_code);
                weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
                v34 = weatherObject.getString(OWM_sws200_Vis_1m_KM);


                resultStrs[0] = v1;
                resultStrs[1] = v2;
                resultStrs[2] = "Vėjo greitis: " + v3;
                resultStrs[3] = "Kritulių kiekis per 30s: " + v4;
                resultStrs[4] = "Krituliu kiekio suma per einamą parą: " + v5;
                resultStrs[5] = "Momentinė temperatūra: " + v6;
                resultStrs[6] = v7;
                resultStrs[7] = "Vėjo gūsio stiprumas: " + v8;
                resultStrs[8] = "Santykinis oro drėgnis: " + v9;
                resultStrs[9] = v10;
                resultStrs[10] = "Atmosferos slėgis stoties lygyje: " + v11;
                resultStrs[11] = v12;
                resultStrs[12] = "Vėjo kryptis: " + v13;
                resultStrs[13] = v14;
                resultStrs[14] = v21;
                resultStrs[15] = "Vidurinio aukšto debesų pado aukštis: " + v24;
                resultStrs[16] = "Žemutinio aukšto debesų pado aukštis: " + v25;
                resultStrs[17] = v26;
                resultStrs[18] = v27;
                resultStrs[19] = v29;
                resultStrs[20] = v31;
                resultStrs[21] = "Esamų oro sąlygų kodas: " +v33;
                resultStrs[22] = "Horizontalus matomumas per 1 minutę: " + v34;


            for (String s : resultStrs) {
                Log.v(LOG_TAG, "Forecast entry: " + s);
            }
            Log.e(LOG_TAG, "reiksme paskui:" + v3);
            return resultStrs;

        }


        @Override
        protected String[] doInBackground(String... params) {

            // If there's no zip code, there's nothing to look up.  Verify size of params.
            if (params.length == 0) {
                return null;
            }

            // These two need to be declared outside the try/catch
            // so that they can be closed in the finally block.
            HttpURLConnection urlConnection = null;
            BufferedReader reader = null;

            // Will contain the raw JSON response as a string.
            String forecastJsonStr = null;

            int numDays = 23;

            try {
                // Construct the URL for the OpenWeatherMap query
                // Possible parameters are avaiable at OWM's forecast API page, at
                // http://openweathermap.org/API#forecast


                Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
                        .build();

                URL url = new URL(builtUri.toString());

                Log.v(LOG_TAG, "Built URI " + builtUri.toString());

                // Create the request to OpenWeatherMap, and open the connection
                urlConnection = (HttpURLConnection) url.openConnection();
                urlConnection.setRequestMethod("GET");
                urlConnection.connect();

                // Read the input stream into a String
                InputStream inputStream = urlConnection.getInputStream();
                StringBuffer buffer = new StringBuffer();
                if (inputStream == null) {
                    // Nothing to do.
                    return null;
                }
                reader = new BufferedReader(new InputStreamReader(inputStream));

                String line;
                while ((line = reader.readLine()) != null) {
                    // Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
                    // But it does make debugging a *lot* easier if you print out the completed
                    // buffer for debugging.
                    buffer.append(line + "\n");
                }

                if (buffer.length() == 0) {
                    // Stream was empty.  No point in parsing.
                    return null;
                }
                forecastJsonStr = buffer.toString();

                Log.v(LOG_TAG, "Forecast string: " + forecastJsonStr);
            } catch (IOException e) {
                Log.e(LOG_TAG, "Error ", e);
                // If the code didn't successfully get the weather data, there's no point in attemping
                // to parse it.
                return null;
            } finally {
                if (urlConnection != null) {
                    urlConnection.disconnect();
                }
                if (reader != null) {
                    try {
                        reader.close();
                    } catch (final IOException e) {
                        Log.e(LOG_TAG, "Error closing stream", e);
                    }
                }
            }

            try {
                return getWeatherDataFromJson(forecastJsonStr, numDays);
            } catch (JSONException e) {
                Log.e(LOG_TAG, e.getMessage(), e);
                e.printStackTrace();
            }

            // This will only happen if there was an error getting or parsing the forecast.
            return null;
        }



    }

}

活动:

public class Activity extends ActionBarActivity {



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity);
        if (savedInstanceState == null) {
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.container, new Fragment())
                    .commit();
        }

    }


}

在 onCreateView 的 Fragment 中,我试图通过以下方式更改文本:

View v = inflater.inflate(R.layout.fragment, container, false);

TextView t = (TextView)v.findViewById(R.id.reiksme1);
t.setText(v3);

但是logcat说是null

我意识到一开始我的 oncreateview 方法 ir 正在运行,然后才是我应该从中获得价值的方法。从我的 json 文件中获取值后,我有什么方法可以更改 textview 的值?

【问题讨论】:

    标签: android view null textview populate


    【解决方案1】:

    您可以覆盖 onPostExecute() 函数来执行此操作。 将此函数添加到您的 AsyncTask 类中

     protected void onPostExecute(String[] result) {
         t.setText(v3);
     }
    

    但在这种情况下,TextView t 必须是您的 Fragment 类的成员

    【讨论】:

    • 感谢您的回答。我真心的。你能告诉我什么时候应该调用 onPostExecute 方法吗?
    • 你不要直接调用 onPostExecute() 。它会在您的后台任务“doInBackground(String...params)”完成后自动调用
    • 我想也应该使用@Override?你的 cide 给出错误:cannot find symbol variable t 我写过://@Override protected void onPostExecute(String[] result) { View v = inflater.inflate(R.layout.fragment_vudata,container,false); TextView t = (TextView)v.findViewById(R.id.reiksme1); t.setText(v3); } 这给了我错误:找不到变量容器。如果我删除容器,我得到:找不到符号变量 inflater
    • 这当然行不通。 t = (TextView)v.findViewById(R.id.reiksme1);应该保留在 onCreateView 中。您必须将 TextView t 声明为类成员
    猜你喜欢
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    相关资源
    最近更新 更多