2013-04-15 19 views
0

好吧,我讀了很多,並認爲我有這個工作,但顯然不是。我想要做的是檢查一個文件是否存在(在這種情況下heapFile.csv),如果它不創建它,然後寫一個字符串。如果文件確實存在,那麼我想將該字符串追加到文件中。當我運行這個時,我沒有得到任何錯誤,雖然我確實收到一個警告,說它不能創建文件,儘管它實際上是這樣做的。但是,無論在哪種情況下,都不會將字符串寫入文件。我可能只是沒有使用正確的語法或什麼東西,但在盯着這幾個星期,我看不到樹林和發現問題。除了這一個問題,我的程序工作正常,如果我能夠得到這個工作,我可以最終完成這個。任何幫助都令人難以置信的讚賞。如果文件不存在,創建它並將字符串寫入它。如果它確實附加了字符串。工作不正確

這是java文件。我認爲這很清楚文件創建/寫入位在哪裏。

package com.loch.meaptracker; 

import java.io.BufferedWriter; 
import java.io.File; 
import java.io.FileWriter; 
import java.io.IOException; 

import com.google.ads.*; 


import android.os.Bundle; 
import android.os.Environment; 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.util.Log; 
import android.view.Menu; 
import android.view.View; 
import android.widget.Button; 
import android.widget.DatePicker; 
import android.widget.EditText; 
import android.widget.RelativeLayout; 
import android.widget.SeekBar; 
import android.widget.SeekBar.OnSeekBarChangeListener; 
import android.widget.TimePicker; 

public class MainActivity extends Activity implements OnSeekBarChangeListener { 

private SeekBar happyBar, energyBar, anxietyBar, painBar; 
private EditText noteField; 
private DatePicker dPick; 
private TimePicker tPick; 
@SuppressWarnings("unused") 
private Button enterButton; 
private int happyValue = 4, energyValue = 4, anxietyValue = 4, 
     painValue = 4; 
private static final String TAG = "heapApp"; 
private String Mood = "Blah"; 
private AdView adView; 
final Context context = this; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    try { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     // Create the adView 
     adView = new AdView (this, AdSize.BANNER, "a15138b1a7adad2"); 

     // Lookup your RelativeLayout assuming it's been given the attribute android:id="@+id/AdRelativeLayout 
     RelativeLayout layout = (RelativeLayout)findViewById(R.id.AdRelativeLayout); 

     // Add the AdView to it 
     layout.addView(adView); 

     // Initiate a generic request to load it with an ad 
     adView.loadAd(new AdRequest()); 

     // bars 
     happyBar = (SeekBar) findViewById(R.id.happinessBarID); 
     happyBar.setOnSeekBarChangeListener(this); 
     energyBar = (SeekBar) findViewById(R.id.energyBarID); 
     energyBar.setOnSeekBarChangeListener(this); 
     anxietyBar = (SeekBar) findViewById(R.id.anxietyBarID); 
     anxietyBar.setOnSeekBarChangeListener(this); 
     painBar = (SeekBar) findViewById(R.id.painBarID); 
     painBar.setOnSeekBarChangeListener(this); 
     // end bars 
     dPick = (DatePicker) findViewById(R.id.datePicker1); 
     tPick = (TimePicker) findViewById(R.id.timePicker1); 
     noteField = (EditText) findViewById(R.id.noteTextFieldID); 
     enterButton = (Button) findViewById(R.id.enterButtonID); 
    } catch (Exception onCreateException) { 
     Log.e(TAG, "Exception received", onCreateException); 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
} 

// Bar listener methods 
@Override 
public void onProgressChanged(SeekBar arg0, int barValue, boolean hFromUser) { 
    try { 

     switch (arg0.getId()) { 
     case R.id.happinessBarID: 
      happyValue = barValue + 1; 
      break; 
     case R.id.energyBarID: 
      energyValue = barValue + 1; 
      break; 
     case R.id.anxietyBarID: 
      anxietyValue = barValue + 1; 
      break; 
     case R.id.painBarID: 
      painValue = barValue + 1; 
      break; 
     } 
     String debugBarValue = "Happy is " + happyValue + ", Energy is " 
       + energyValue + ", Anxiety is " + anxietyValue 
       + ", Pain is " + painValue + "."; 
     System.out.println(debugBarValue); 

    } catch (Exception BarValueException) { 
     Log.e(TAG, "Exception received", BarValueException); 
    } 

} 

@Override 
public void onStartTrackingTouch(SeekBar happyBar) { 
    // TODO Auto-generated method stub 

} 

@Override 
public void onStopTrackingTouch(SeekBar happyBar) { 
    // TODO Auto-generated method stub 

} 

// end Bar listener methods 

// Enter Button listener Method 

public void dialogPop(View v) { 
    try { 
     AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
       context); 

     // set Title 
     alertDialogBuilder.setTitle("title"); 

     // set dialog message 
     alertDialogBuilder.setMessage("You entered: " + getMood()) 
       .setCancelable(false).setPositiveButton("Okay", 
       // When Okay button clicked the write mood string to file 
         new DialogInterface.OnClickListener() { 
          public void onClick(DialogInterface dialog, 
            int id) { 
           try { 
            // This is the string that should be 
            // written to file 
            String data = getMood(); 
            // This is the file that should be 
            // written to 
            File heapFile = new File(Environment.getExternalStorageDirectory(), "heapFile.csv"); 

            // if file doesn't exists, then create 
            // it 
            if (!heapFile.exists()) { 
             heapFile.createNewFile(); 
             FileWriter heapFileWritter = new FileWriter(
               heapFile.getName(), true); 
             BufferedWriter heapBufferWritter = new BufferedWriter(
               heapFileWritter); 
             heapBufferWritter.write(data); 
             heapBufferWritter.close(); 

             System.out.println("Done"); 
            } 

            // true = append file 
            FileWriter heapFileWritter = new FileWriter(
              heapFile.getName(), true); 
            BufferedWriter heapBufferWritter = new BufferedWriter(
              heapFileWritter); 
            heapBufferWritter.write(data); 
            heapBufferWritter.close(); 

            System.out.println("Done"); 

           } catch (IOException e) { 
            e.printStackTrace(); 
           } 
          } 

         }) 
       // If they press either the cancel button or the back button 
       // on their device (Same thing) then close the dialog and 
       // give the user a chance to change what they've entered 
       .setNegativeButton("Cancel", 
         new DialogInterface.OnClickListener() { 

          @Override 
          public void onClick(DialogInterface dialog, 
            int id) { 
           // TODO Auto-generated method stub 
           dialog.cancel(); 
          } 
         }); 

     // create alert dialog 
     AlertDialog alertDialog = alertDialogBuilder.create(); 

     // show it 
     alertDialog.show(); 
    } catch (Exception buttonListenerException) { 
     Log.e(TAG, "Exception received", buttonListenerException); 
    } 
    return; 
} 

public String getMood() { 
    try { 
     int month = dPick.getMonth(); 
     int day = dPick.getDayOfMonth(); 
     int year = dPick.getYear(); 
     int minute = tPick.getCurrentMinute(); 
     String moodAntePost = "AM"; 
     boolean hourType = tPick.is24HourView(); 
     int moodHour = tPick.getCurrentHour(); 
     if (hourType == false && moodHour > 12) { 
      moodHour = (moodHour - 12); 
      moodAntePost = "PM"; 
     } else if (hourType == false && moodHour <= 0) { 
      moodHour = 12; 
     } else { 
     } 
     String noteText = noteField.getText().toString(); 
     Mood = "Happiness," + happyValue + ",Energy," + energyValue 
       + ",Anxiety," + anxietyValue + ",Pain," + painValue 
       + ",Date," + month + "/" + day + "/" + year + ",Time," 
       + moodHour + ":" + minute + "," + moodAntePost + ",Note," 
       + noteText; 
     System.out.println(Mood); 
    } catch (Exception getMoodException) { 
     Log.e(TAG, "Exception received", getMoodException); 
    } 

    return Mood; 
} 

} 

編輯我的問題,包括清單,所以你可以看到我的權限。我認爲這是正確的,但我不能肯定......

<?xml version="1.0" encoding="utf-8"?> 
<manifest xmlns:android="http://schemas.android.com/apk/res/android" 
package="com.loch.meaptracker" 
android:versionCode="1" 
android:versionName="1.0" > 

<uses-sdk 
    android:minSdkVersion="8" 
    android:targetSdkVersion="17" /> 

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> 
<uses-permission android:name="android.permission.INTERNET"/> 
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> 
<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name="com.loch.meaptracker.MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 
    <activity android:name="com.google.ads.AdActivity" 
     android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/> 
</application> 

</manifest> 
+0

快速問題,您是否添加了「WRITE_EXTERNAL_STORAGE」和「READ_EXTERNAL_STORAGE」的權限? –

+0

哦對!讓我編輯並在問題中包含我的清單。雖然我認爲我確實是對的,但可能會在這方面有所作爲。 – fauxfire76

+0

我實際上並不需要包含讀取外部存儲的權限,因爲我從來沒有真正需要有關文件的內容。還沒有。當我包含我計劃的其他一些功能時,我將需要在此程序的更高版本中執行此操作。 – fauxfire76

回答

3

使用本:

String file = heapFile.getAbsolutePath(); 
FileWriter heapFileWritter = new FileWriter(file, true); 

的getName()會給你的文件只是名字。但是你需要爲FileWriter提供絕對路徑。

+0

好吧,你的建議工作除了某些原因,它寫了兩次字符串。 > _ < – fauxfire76

+0

* facepalm *我是個白癡。我現在看到它爲什麼做了兩次。非常感謝你。我認爲這會完成它。 – fauxfire76

+0

對於那些閱讀過這篇文章的人來說,這只是因爲我忽略了在if {{this this stuff *})之後的代碼包裝在else {}中。一旦我做到了,它完美運作。 – fauxfire76

相關問題