2017-08-06 17 views
0

openFileOutput()に関連付けられた「解決できないメソッド」で苦労しています。私は自分の問題が文脈に関係していると思うが、それを解決する方法は知らない。 Webサイトからデータを読み込む非同期タスク(AirLineListRetriever.java)から呼び出されるファイル処理クラス(FileHelper.java)があります。 AsynchTaskActivityから呼び出されます。Androidからの読み込み/書き込み

非同期クラスを呼び出し

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

抽出

   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()); 

非同期クラス

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); 
    } 


} 
完全に活性エキス contextを使用0
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(); 
+0

これはどのクラスですか? openFileOutputはContextのメンバーです。あなたのクラスがContextの子でない場合、それは動作しません。あなた自身ではなく、コンテキスト上で呼び出さなければなりません。 –

答えて

2

を非同期タスクへのコンテキストを渡すことも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); 
    } 


} 

コンストラクタの2番目のパラメータとしてactivtyパスコンテキストでタスクを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(); 

変更SaveToFileメソッドシグネチャ、

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

は、ファイルを開くためにそのコンテキストを使用ストリーム、

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

ありがとうJTeam。私はこの行に沿って作業を始めましたが、saveToFileは非同期タスク内から呼び出されるため、非同期タスクにコンテキストを渡す必要があるように見えます。 – jcbird

+0

@jcbird編集した回答を確認してください。 – JTeam

+0

こんにちはJTeam私はまだアクティビティから非同期タスクを介してsaveToFileにコンテキストを渡す方法が失われていますか、またはアクティビティからsaveToFileを呼び出す方法を見つけるためにリストラを見なければなりませんか? – jcbird

1

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

関連する問題