2013-10-05 4 views
0

Я пишу цифры в файл и хочу отправить файл по электронной почте. Файл получен по электронной почте, однако пуст.Файл не прикреплен по электронной почте при отправке

Но когда я посмотрел на «data/data/com.example.write_file/files/samplefile.txt», файл ok и мои записи записаны.

Кто-нибудь знает, что я делаю неправильно, пожалуйста?

package com.example.write_file; 

+import java.io.FileOutputStream; 

public class MainActivity extends Activity { 
private EditText getInput;  
    int D; 
    String W; 
    char chr; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState);   

    setContentView(R.layout.activity_main); 
    getInput = (EditText) findViewById(R.id.getInput);  
    D=0; 
    TextView textView1 = (TextView) findViewById(R.id.textView1); 
    textView1.setText("Write a number you want to send in the txt file") ; 

} 

public void onClick(View view) {   

    write_file();  

    D=D+1; 
    W=getInput.getText().toString(); //will get a string 
    if (getInput.getText().length() > 0){  
     chr=W.charAt(0);} //W convert to char 
     switch (view.getId()) { 
     case R.id.button1: 
      if (((chr==(char)45)&&(getInput.getText().length() < 2))||(getInput.getText().length() == 0)){    
      Toast.makeText(this, "Please enter a text", 
       Toast.LENGTH_LONG).show();    
      return; 
      } 

      TextView getInput1 = (TextView) findViewById(R.id.textView1); 
      getInput1.setText("Write a number you want to send in the txt file") ; 
      break;     }       

} 

public void onClick2(View view) {  
sendfile(); 
finish(); 
}  

public void write_file() { //writes into local not to a sdcard 

    try { // catches IOException below    
     FileOutputStream fOut = openFileOutput("samplefile.txt",MODE_APPEND); 
     OutputStreamWriter osw = new OutputStreamWriter(fOut);    
     osw.append(W + "\n"); // Write the string to the file - "\n" similar to writeln in pascal (use wordpad not notepad) 

     osw.flush(); 
     osw.close(); 

     if (D>=55) { finish();} 

     Toast.makeText(this, "I am writing to the file", 
     Toast.LENGTH_SHORT).show(); 
     // the file you can find in DDMS-File Explorer-"/data/data/your_project_package_structure/files/samplefile.txt" 
     // there is an icon mobile phone for pulling file from device or putting file onto device  
} 
    catch (IOException ioe) 
    {Toast.makeText(this, "Exception-file not exists?", 
      Toast.LENGTH_SHORT).show();} 
} 
/*  
public void sendfile(){ 
    String nfile; 
    nfile="samplefile.txt"; 
    Intent emailIntent = new Intent(Intent.ACTION_SEND); 
    emailIntent.setType("text/plain"); 
    emailIntent.putExtra(android.content.Intent.ACTION_SENDTO, new String[] 
      {"[email protected]"}); 
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, 
    "File attached."); 
    emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("data/data/com.example.write_file/files"+ nfile)); 
     startActivity(Intent.createChooser(emailIntent, 
    "Send email using..")); 

    Toast.makeText(this, "The file was sent", 
      Toast.LENGTH_SHORT).show(); 

} */ 
public void sendfile(){ 
    Intent emailIntent = new Intent(Intent.ACTION_SEND); 
    emailIntent.setType("text/plain"); 
    emailIntent.putExtra(android.content.Intent.ACTION_SENDTO, new String[] 
      {"[email protected]"}); 
    emailIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, 
    "File attached."); 
    File file = getFileStreamPath("samplefile.txt"); 
    emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://"+file.getAbsolutePath())); 
     startActivity(Intent.createChooser(emailIntent, 
    "Send email using..")); 

    Toast.makeText(this, "The file was sent", 
      Toast.LENGTH_SHORT).show(); 

} 
}  

**in the manifest I put:** 
<provider 
android:name="android.support.v4.content.FileProvider" 
android:authorities="com.example.write_file" 
android:exported="false" 
android:grantUriPermissions="true"> 
<meta-data 
     android:name="android.support.FILE_PROVIDER_PATHS" 
     android:resource="@xml/my_path" /> 
</provider> 
    <activity 
     android:name="com.example.write_file.MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

**and in the my_path.xml :** 
<paths> 
<files-path name="files" path="files/"/>  
</paths> 

ответ

3

Во-первых, сторонние приложения не имеют доступа к вашему внутреннему хранилищу. Либо напишите файл на внешнее хранилище, либо try FileProvider, чтобы обеспечить выборочный доступ к внутреннему хранилищу.

Во-вторых, никогда не было жестких путей. Ваш код не будет работать на многих устройствах Android. Используйте getFilesDir() или getFileStreamPath(), вместо жесткого кодирования data/data/com.example.write_file/files.

+0

Я отредактировал код (вверху), но он все еще не работает. Не могли бы вы проверить, что сейчас не так? спасибо – user2556278

+0

Также он делает всю работу в UIThread ... – m0skit0

+0

@ user2556278: Как я уже писал, сторонние приложения не имеют доступа к вашему внутреннему хранилищу. Либо напишите файл на внешнее хранилище, либо попробуйте 'FileProvider' обеспечить выборочный доступ к внутреннему хранилищу. – CommonsWare

0

Чтобы отправить электронное письмо, вы должны использовать внешнее хранилище. Если вы используете путь к файлу данных приложения, который в настоящее время вы делаете, вы получите исключение, исключенное разрешением.

Вместо этого сохраните файл во внешнем хранилище, а затем отправьте его с использованием Intent.

Смежные вопросы