The method findViewById(int) is undefined

前端 未结 4 845
被撕碎了的回忆
被撕碎了的回忆 2021-01-03 02:08

I\'m new to Android development and I\'m trying to code a little app which allows me to grab an external JSON file and parse it. I got this to work, however it wont work if

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-03 03:05

    Here is what you should do to make it work as you want. Use onPostExecude()

    public class Main extends Activity {
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
            new LongOperation(this).execute();
        }
    }
    
    
    class LongOperation extends AsyncTask {
        private Main longOperationContext = null;
    
        public LongOperation(Main context) {
            longOperationContext = context;
            Log.v("LongOper", "Konstuktor");
        }
    
        @Override
        protected String doInBackground(String... params) {
            Log.v("doInBackground", "inside");
            StringBuilder sb = new StringBuilder();
    
            try {
                URL json = new URL("http://www.corps-marchia.de/jsontest.php");
                URLConnection tc = json.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
    
                String line;
                while ((line = in.readLine()) != null) {
                        JSONArray ja = new JSONArray(line);
                        JSONObject jo = (JSONObject) ja.get(0);
                        Log.v("line = ", "jo.getString() ="+jo.getString("text"));
                        sb.append(jo.getString("text") + " - " + jo.getString("secondtest")).append("\n");
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
                Log.v("Error", "URL exc");
            } catch (IOException e) {
                e.printStackTrace();
                Log.v("ERROR", "IOEXECPTOIn");
            } catch (JSONException e) {
                e.printStackTrace();
                Log.v("Error", "JsonException");
            }
            String result = sb.toString();
            return result;
        }
    
        @Override
        protected void onPostExecute(String result) {
            Log.v("onPostExe", "result = "+result);
          TextView txtView1 = (TextView)longOperationContext.findViewById(R.id.textView01);
          txtView1.setText(result);
    
    
        }
        protected void onPreExecute() {
        }
    
        @Override
        protected void onProgressUpdate(Void... values) {
            ProgressDialog pd = new ProgressDialog(longOperationContext);
            pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pd.setMessage("Working...");
            pd.setIndeterminate(true);
            pd.setCancelable(false);
        }    
    
    }
    

提交回复
热议问题