简体   繁体   English

Android从类中读取/写入

[英]Android Read/Write from class

I am struggling with a "Cannot Resolve method" associated with a openFileOutput() . 我正在为与openFileOutput()关联的“无法解析方法”而苦苦挣扎。 I suspect my problem relates to context but don't know how to resolve it. 我怀疑我的问题与上下文有关,但不知道如何解决。 I have a file handling class ( FileHelper.java ) that is called from an asynchronous task ( AirLineListRetriever.java ) that reads data from a website. 我有一个文件处理类( FileHelper.java ),该类从异步任务( AirLineListRetriever.java )中调用,该异步任务从网站读取数据。 The AsynchTask is called from an Activity . Activity调用AsynchTask

FileHelper.java extract FileHelper.java提取

    public static boolean saveToFile(String data){
    try {

        FileOutputStream fileOutputStream = openFileOutput("airlinedata.txt", MODE_PRIVATE);
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
        outputStreamWriter.write(data);
        outputStreamWriter.close();



        Log.d (TAG, "Airline List written to file");

        return true;
    }  catch(FileNotFoundException ex) {
        Log.d(TAG, ex.getMessage());
    }  catch(IOException ex) {
        Log.d(TAG, ex.getMessage());
    }
    return  false;


}

doInBackground extract doInBackground提取

                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                bufferedReader.close();



                FileHelper.saveToFile(stringBuilder.toString());

Async class in full 完整的异步类

    class AirLineListRetriever extends AsyncTask<Void, Void, List<Airline>> {

    private String FSAPIid = "appId=xxxxx";



    public interface AirLineListResponse{
        void processFinish(List<Airline> airlines);
    }

    AirLineListResponse delegate;

    public AirLineListRetriever(AirLineListResponse delegate){
        this.delegate = delegate;
    }


    @Override
    protected List<Airline> doInBackground(Void... params) {

        JSONObject JSONAirlines;
        JSONObject JSONAirline;
        JSONArray JSONAirlinesList;
        Airline airline;
        List<Airline> airlineList;

        try {

            Log.d("ALPrint", "In Retrieve Airline List");

            URL url = new URL("https://api.flightstats.com/flex/airlines/rest/v1/json/active?" + FSAPIid);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                bufferedReader.close();



                FileHelper.saveToFile(stringBuilder.toString());

                JSONAirlines = new JSONObject(stringBuilder.toString());
                JSONAirlinesList = JSONAirlines.getJSONArray("airlines");
                airlineList = new ArrayList<Airline>();

                for (int i = 0; i < JSONAirlinesList.length(); i++) {
                    JSONAirline = JSONAirlinesList.getJSONObject(i);
                    String airlineName = JSONAirline.has("name") ? JSONAirline.getString("name") : null;
                    String fsCode = JSONAirline.has("fs") ? JSONAirline.getString("fs") : null;
                    String iataCode = JSONAirline.has("iata") ? JSONAirline.getString("iata") : null;
                    String icaoCode = JSONAirline.has("icao") ? JSONAirline.getString("icao") : null;

                    airline = new Airline(
                            airlineName,
                            fsCode,
                            iataCode,
                            icaoCode
                    );
                    airlineList.add(airline);

                }

                return airlineList;
            } finally {
                urlConnection.disconnect();
            }
        } catch (Exception e) {
            Log.e("ERROR", e.getMessage(), e);
            return null;
        }
    }

    protected void onPostExecute(List<Airline> airlineList){
        this.delegate.processFinish(airlineList);
    }


}

activity extract that calls the async class 调用异步类的活动摘录

new AirLineListRetriever(
            new AirLineListRetriever.AirLineListResponse() {
                @Override
                public void processFinish(List<Airline> airlines) {

                    String selectedAirLine = null;
                    airlineList = airlines;

                    Log.d("EndRetrieve", "Completed the retrieve");

                    // sort the airline list
                    Collections.sort(airlineList, new Comparator<Airline>() {
                        @Override
                        public int compare(Airline airline, Airline t1)
                        {
                            Airline airline1 = (Airline) airline;
                            Airline airline2 = (Airline) t1;
                            return airline1.airlineName.compareToIgnoreCase(airline2.airlineName);

                        }

                    });

                    final ArrayList airlineArrayList = new ArrayList();

                    //copy the airline list to an array to populate the autoCompleteTextView
                    for (int i=0; i < airlineList.size(); i++){
                        airlineArrayList.add(airlineList.get(i).airlineName);
                    }

                    progressDialog.dismiss();

                    acAirlines = (AutoCompleteTextView) findViewById(R.id.autoCompleteAirLines);
                    acAirlines.setVisibility(View.VISIBLE);
                    //acAirlines.setThreshold(4);

                    final ArrayAdapter<String> adapter = new ArrayAdapter<String> (AddFlightActivity.this, android.R.layout.simple_list_item_1, airlineArrayList);
                    acAirlines.setThreshold(2);
                    acAirlines.setAdapter(adapter);

                    acAirlines.setOnItemClickListener(new AdapterView.OnItemClickListener() {


                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) {

                            String selectedAirLine = adapter.getItem(index);
                            int position = airlineArrayList.indexOf(selectedAirLine);
                            String alIataCode = airlineList.get(position).iataCode;
                            Log.d("ALCodePrint", selectedAirLine + " " + alIataCode);
                            alCode.setText(alIataCode);
                            alCode_Set = true;
                            extFunctions.hideKeyboard(AddFlightActivity.this);
                        }

                    });

                }
            }
    ).execute();

To Pass context to async task changes its constructor to receive context like below, also pass that to saveToFile method. 要将上下文传递给异步任务,请更改其构造函数以接收如下所示的上下文,并将其也传递给saveToFile方法。

    class AirLineListRetriever extends AsyncTask<Void, Void, List<Airline>> {

    private String FSAPIid = "appId=xxxxx";

    private Context mContext;

    public interface AirLineListResponse{
        void processFinish(List<Airline> airlines);
    }

    AirLineListResponse delegate;

    public AirLineListRetriever(AirLineListResponse delegate, Context context){
        this.delegate = delegate;
        this.mContext = context;
    }


    @Override
    protected List<Airline> doInBackground(Void... params) {

        JSONObject JSONAirlines;
        JSONObject JSONAirline;
        JSONArray JSONAirlinesList;
        Airline airline;
        List<Airline> airlineList;

        try {

            Log.d("ALPrint", "In Retrieve Airline List");

            URL url = new URL("https://api.flightstats.com/flex/airlines/rest/v1/json/active?" + FSAPIid);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            try {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                StringBuilder stringBuilder = new StringBuilder();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line).append("\n");
                }
                bufferedReader.close();



                FileHelper.saveToFile(stringBuilder.toString(), mContext);

                JSONAirlines = new JSONObject(stringBuilder.toString());
                JSONAirlinesList = JSONAirlines.getJSONArray("airlines");
                airlineList = new ArrayList<Airline>();

                for (int i = 0; i < JSONAirlinesList.length(); i++) {
                    JSONAirline = JSONAirlinesList.getJSONObject(i);
                    String airlineName = JSONAirline.has("name") ? JSONAirline.getString("name") : null;
                    String fsCode = JSONAirline.has("fs") ? JSONAirline.getString("fs") : null;
                    String iataCode = JSONAirline.has("iata") ? JSONAirline.getString("iata") : null;
                    String icaoCode = JSONAirline.has("icao") ? JSONAirline.getString("icao") : null;

                    airline = new Airline(
                            airlineName,
                            fsCode,
                            iataCode,
                            icaoCode
                    );
                    airlineList.add(airline);

                }

                return airlineList;
            } finally {
                urlConnection.disconnect();
            }
        } catch (Exception e) {
            Log.e("ERROR", e.getMessage(), e);
            return null;
        }
    }

    protected void onPostExecute(List<Airline> airlineList){
        this.delegate.processFinish(airlineList);
    }


}

While creating asyn task in activty pass context as second parameter to its constructor, 在活动中创建asyn任务时,将上下文作为第二个参数传递给其构造函数,

new AirLineListRetriever(
            new AirLineListRetriever.AirLineListResponse() {
                @Override
                public void processFinish(List<Airline> airlines) {

                    String selectedAirLine = null;
                    airlineList = airlines;

                    Log.d("EndRetrieve", "Completed the retrieve");

                    // sort the airline list
                    Collections.sort(airlineList, new Comparator<Airline>() {
                        @Override
                        public int compare(Airline airline, Airline t1)
                        {
                            Airline airline1 = (Airline) airline;
                            Airline airline2 = (Airline) t1;
                            return airline1.airlineName.compareToIgnoreCase(airline2.airlineName);

                        }

                    });

                    final ArrayList airlineArrayList = new ArrayList();

                    //copy the airline list to an array to populate the autoCompleteTextView
                    for (int i=0; i < airlineList.size(); i++){
                        airlineArrayList.add(airlineList.get(i).airlineName);
                    }

                    progressDialog.dismiss();

                    acAirlines = (AutoCompleteTextView) findViewById(R.id.autoCompleteAirLines);
                    acAirlines.setVisibility(View.VISIBLE);
                    //acAirlines.setThreshold(4);

                    final ArrayAdapter<String> adapter = new ArrayAdapter<String> (AddFlightActivity.this, android.R.layout.simple_list_item_1, airlineArrayList);
                    acAirlines.setThreshold(2);
                    acAirlines.setAdapter(adapter);

                    acAirlines.setOnItemClickListener(new AdapterView.OnItemClickListener() {


                        @Override
                        public void onItemClick(AdapterView<?> adapterView, View view, int index, long id) {

                            String selectedAirLine = adapter.getItem(index);
                            int position = airlineArrayList.indexOf(selectedAirLine);
                            String alIataCode = airlineList.get(position).iataCode;
                            Log.d("ALCodePrint", selectedAirLine + " " + alIataCode);
                            alCode.setText(alIataCode);
                            alCode_Set = true;
                            extFunctions.hideKeyboard(AddFlightActivity.this);
                        }

                    });

                }
            }, this.getApplicationContext()
    ).execute();

Change saveToFile signature to receive context, 更改saveToFile签名以接收上下文,

public static boolean saveToFile(String data, Context ctxt){..

Then use that context to open file stream, 然后使用该上下文打开文件流,

FileOutputStream fileOutputStream = ctxt.openFileOutput("airlinedata.txt", MODE_PRIVATE);

使用context

FileOutputStream fileOutputStream = context.openFileOutput("airlinedata.txt", context.MODE_PRIVATE);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM